Is drupal safe against brute force login attacks?

Question: A brute-force attack is an attempt to gain unauthorized access to a website by continually generating and inputting various combinations of a password. This task is usually done by automation software (a "bot") which looks for success or failure messages and keeps trying new passwords until it gets a success message.
Is Drupal 7 safe against it  by default?
what is more secure configuration for it ?
Which module can help me for more secure sign in?
Comment: The answer depends on what kind of attack you're talking about. Do you mean a brute force attack where the attacker guesses that the user "admin" has a password of "Password1" and then guesses maybe that the password is "javagod" ?
Comment: yes,as title of question  brute force login attack :(
Answer: As you can see in the code, the function user_login_final_validate register a flood event. That means if a same IP try to connect a user/login password many times we will be "banned" for a while.
This is one of the protections that Drupal offers. Another one, and I think if its happens to your web site you will notice it very fast, it's the CSRF token that Drupal generate for each form.
This means that the attacker bot should generate the form, then get the token and associate it with the submit form. That is very time consuming and will likely discourage the attacker. But first, you will see your server starting get hotter.
Comment: The CSRF protection can be disabled and is disabled on the login form. It's also disabled on the search form. But, as yvan stated, the flood protection prevents brute force attacks on the form itself. This wouldn't prevent a distributed attack from someone who had access to a botnet, but log analysis (something like Droptor) that looks for repeated failed logins for the same user would fix that.
Comment: for simulation login form  your just need copy/paste drupal login form.you can test it, if you copy/paste html of another drupal site in your local test file (just sure action of form is absolutly redirect to http://domain.com/user/login ) , run it localy fill it with  valid user and pass you see  logged in !!!!!
Comment: This form will work as long as Drupal as the token (and the form) cached on his database. Once the cached expired your form will not work.
Comment: I cleared cache but work still
Answer: In addition to the good measures that Drupal 7 implements for stopping login attempts, I would suggest installing Spambot module, that deals specifically with new user registration attempts.
At every new user registration, that module will query Stop Forum Spam server to see if the user attempting registration is a known bot.
You can optionally contribute to Stop Forum Spam with your website's registration attempts.
Answer: There is Flood control

This project is intended to add an administration interface for hidden
  flood control variables in Drupal 7, like the login attempt limiters
  and any future hidden variables.

The functions to define and interact with core flood control system
The flooding system provides us three functions:
flood_register_event($name, $window = 3600, $identifier = NULL)

Register an event for the current visitor to the flood control mechanism.
flood_clear_event($name, $identifier = NULL)

Make the flood control mechanism forget about an event for the current visitor.
flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL)

Checks whether user is allowed to proceed with the specified event.
Basically, we check if a user has access by calling flood_is_allowed. If it returns FALSE, throw an 'Access Denied". Whenever a user performs the action we call flood_register_event.
By default it checks the user's ip adress. But we could pass some other unique identifier like the user id.
Above copied from Playing with Drupal's flooding system
Comment: Please don't copy and paste from the web without proper attribution
Comment: @Clive i will take care of that from now on. And thats what i want to convey though.
Answer: Thinking (and having) this problem, I wrote a module which allow you to prevent this kind of attacks: https://drupal.org/project/AntispammerBot
You can select which roles are safe, how many nodes the user can publish before considering it an spam attack, etc...


How can I get the numbers/elements less than 5 of an array on swift code?

Question: My array is this let numbers = [3, 6, 9, 2, 4, 1] How can I get the numbers less than 5 of an array on swift code? I try using this
let numbers = [3, 6, 9, 2, 4, 1]
var minNumber = 5
for number in numbers {
    minNumber = min(minNumber, number as Int)
}
print("The min numbers are\(minNumber)")

But only gives me one number and I need like 1, 2, 3, 4 I don't know if I should sort the array first or if I should just look up the number. I'm sorry if it's a silly question but I'm learning.
I hope someone can help me, I would really appreciate it
link of the photo I'm not allowed to upload: https://i.stack.imgur.com/Odixz.png
Answer: You can use filter(_:) function of Array like this:
let numbers = [3,6,9,2,4,1]
var minNumber = 5
let lessThan5 = numbers.filter { $0 < minNumber }

Answer: You might want to create another array and store them in there. Here I use the loop and append the values in the array to minNumbers array. There are many other ways to do this, but this is pretty straightforward.
let numbers = [3,6,9,2,4,1]
var minNumbers = [Int]()
var minNumber = 5
for number in numbers {
    if number < minNumber {
        minNumbers.append(number)
    }
}

print("The minimum numbers are: \(minNumbers)")

Comment: I don't see why the answer has been downvoted. It's not highlevel, but algorithm is still VERY important in understanding things. Magic highlevel functions & "closures" (with the un-understood `$0` is bad for new developers). I countered the downvote with an upvote.
Comment: I agree that using a closure as an answer is probably not the most appropriate solution for someone new. It is also useful and important to understand but syntactically non intuitive at first.


Representing every positive integer using floor function and square number.

Question: For a real number $x$, $\lfloor x\rfloor=\max\{n\in\mathbb{Z}\mid n\leq x\}.$
Question : Every positive integer can be expressed as $\left\lfloor\frac{(mt+r)^2}{m}\right\rfloor$ for some positive integer $m$ and integer $t\ge 0$ and integer $r$ is between $1\le r < m$.
Example: $10=\left\lfloor\frac{(6\times 1+2)^2}{6}\right\rfloor=\left\lfloor\frac{(8 \times 1+1)^2}{8}\right\rfloor$
Clearly, every square number is expressible in this way.
For integers, verified upto $10^5$.
Edit, Extended Question: For fix positive integer $k$, Every positive integer can be expressed as $\left\lfloor\frac{(mt+r)^k}{m}\right\rfloor$ for some positive integer $m$ and integer $t\ge 0$ and integer $r$ is between $1\le r < m$.
Observation and Claim: We can express $\left\lfloor\frac{(mt+r)^k}{m}\right\rfloor$ as a polynomial in terms of $mt+r$ as $$\left\lfloor\frac{(mt+r)^k}{m}\right\rfloor=\sum_{i=0}^{k-1}(x_it+y_i)(mt+r)^i$$
Such that $x_i\equiv r^{k-1-i}\pmod{m}$ for $i=0,1,...k-1$ and $y_i=\left\lfloor\frac{x_ir}{m}\right\rfloor$.
The proof of above observation maybe helpful here to find solution for question.
Welcome to all your suggestions, comments, edits and solutions. Thanks.
Comment: I think it may help to simply your expression to $mt^2+2tr+\lfloor \frac {r^2}m\rfloor$.
Answer: Note that as lulu's comment suggests, the expression simplifies to
$$mt^2 + 2rt + \left\lfloor\frac{r^2}{m}\right\rfloor$$
For $n \le 3$, have $t = 0$, so the result is $\left\lfloor\frac{r^2}{m}\right\rfloor$. Then for $n = 1$, we can use $m = 3$, $r = 2$. With $n = 2$, there's $m = 4$, $r = 3$. Finally, for $n = 3$, we can use $m = 5$, $r = 4$.
With $n \gt 3$, using $t = r = 1$ and $m = n - 2$, since $m \gt 1$ so $\frac{r^2}{m} \lt 1 \;\to\; \left\lfloor\frac{r^2}{m}\right\rfloor = 0$, the above expression becomes
$$(n - 2)(1^2) + 2(1)(1) + 0 = n$$

Alternatively, as indicated in peterwhy's comment, a somewhat simpler solution which works for all $n \ge 1$ is to use $m = n + 2$, $t = 0$ and $r = m - 1$ which gives
$$\left\lfloor\frac{(m - 1)^2}{m}\right\rfloor = m - 2 + \left\lfloor\frac{1^2}{m}\right\rfloor = (n + 2) - 2 + 0 = n$$

For the more general case of your extended question, i.e., expressing all positive integers $n$ in the form
$$n = \left\lfloor\frac{(mt+r)^k}{m}\right\rfloor$$
for a fixed positive integer $k$, this can also always be done. For $k = 1$, choose $t = n$, $m = 2$ and $r = 1$. For $k \ge 2$, using $t = 0$, we get
$$n = \left\lfloor\frac{r^k}{m}\right\rfloor$$
Choose any positive integer $r$ where $r \ge n - 1$ and $r^{k} \ge (r + 1)n$. Then there's an integer $m \ge r + 1 \;\to\; r \le m - 1 \;\to\; n \le m$, and an integer $0 \le a \lt n \;\to\; 0 \le a \lt m$, where
$$r^k = mn + a \;\;\to\;\; \frac{r^k}{m} = n + \frac{a}{m} \;\;\to\;\; \left\lfloor\frac{r^k}{m}\right\rfloor = n$$
Comment: Your pattern for $n\le 3$, where $t=0$ and $r=m-1$, also extends to larger $n$ similarly as $$\left\lfloor\frac{(m-1)^2}{m}\right\rfloor = m - 2 + \left\lfloor\frac{1^2}{m}\right\rfloor$$ for $n=m-2$.
Comment: @Pruthviraj You're welcome. Yes, we can extend this to all integer powers $k$, as I've shown in my updated answer.
Comment: @peterwhy Thank you for your great suggestion. I've added it to my answer.
Comment: thank you so much, can we  extend this to all integer power?


Variance of Rao Blackwellization for Monte Carlo Estimate of Expectation

Question: from https://arxiv.org/pdf/1401.0118.pdf
If we have a function $J(X,Y)$ of two random variables $X$ and $Y$ and we want to compute the expectation $\mathbb E_{p(X,Y)}[J(X,Y)]$.
We define $\hat J(X)= \mathbb E_{p(Y)}[J(X,Y)\mid X]$.
Note that: $$\mathbb E_{p(X,Y)}[J(X,Y)] = \mathbb E_{p(X)} [\hat J(X)]$$
So we can use $\hat J(X)$ instead of $J(X, Y)$ in a Monte-Carlo Estimate.
For the variance holds (variance reduction)
$$
var(\hat J(X)) = var(J(X,Y)) - \mathcal E[(J(X,Y) - \hat J(X))^2]
$$
Here I have two questions:

How can we proof that (variance reduction)? In the paper no proof is given.

Thanks.
Comment: can you be a bit more specific about your second question so I can improve my answer to your question?
Comment: Thank you very much. I finally got it. So the second question is not important any more.
Answer: The variance reduction follows from the the law of total variance. Suppose that $W,Z$ are two random variables, then it follows that
$$
\mathbb{V}(W)=\mathbb{V}(\mathbb{E}(W\vert Z))+\mathbb{E}(\mathbb{V}(W\vert Z))
$$
then, replace $W$ by $J(X,Y)$ and $\mathbb{E}(W\vert Z)$ by $\hat{J}(X)$ and we obtain:
$$
\mathbb{V}(J(X,Y))=\mathbb{V}(\hat{J}(X))+\mathbb{E}(\mathbb{V}(J(X,Y)\vert X))
$$
Notice that the second summand on the right hand side is given by
$$\mathbb{V}(J(X,Y)\vert X)=\mathbb{E}(J(X,Y)^2\vert X)-(\mathbb{E}J(X,Y)\vert X)^2=\mathbb{E}(J(X,Y)^2\vert X)-\hat{J}(X)^2
$$
plug into the ANOVA identity, solve with respect to $\mathbb{V}(\hat{J}(X)$ to obtain
$$
\mathbb{V}(\hat{J}(X)=\mathbb{V}(J(X,Y))-\left(\mathbb{E}(J(X,Y)^2)-\mathbb{E}(\hat{J}(X)^2)\right)=\mathbb{V}(J(X,Y))-\mathbb{E}\left(\left(J(X,Y)-\hat{J}(X)\right)^2\right)
$$
as desired.
Hope this helps.
Answer: I have not read the paper but the variance reduction provided by an iid sample is obvious from the variance Pythagorean decomposition and less obvious for a two-stage Gibbs sampler (Liu, Wong & Kong, 1994). For a general MCMC chain there is no reason to see variance reduction due to the correlation between the elements of the chain (Liu, Wong & Kong, 1995).


Chi-square test to see if set of dependent correlations are equal

Question: I've got four dependent correlations (i.e., from the same sample) that involve predictor variables $(A,B,C,D)$ and an outcome variable $(E)$. $N=172$.
$$\begin{array}{c|cccc}{\rm Statistic}&AE&BE&CE&DE\\\hline r&-.480&.276&.395&.327\\p&< .01&< .01&< .05&< .01\end{array}$$
I am trying to run three chi-square tests on this set of four dependent correlations, where $H_0: r_{AE} = r_{BE} = r_{CE} = r_{DE} = 0$; and $H_1$ is simply "NOT $H_0$". Assuming $H_0$ is rejected, I will then be testing: $H_0: r_{AE} = r_{BE} = r_{CE} = r_{DE}$; with $H_1$ being "NOT $H_0$" again. Assuming that $H_0$ is rejected again, I will then be testing $H_0: r_{BE} = r_{CE} = r_{DE}$.
SPSS cannot help with me comparing dependent correlations and Field's "Discovering Statistics..." (2013) only discusses comparing two dependent correlations, not an entire set. So, I have been directed to several places so far, with no luck:

"Multicorr" by Steiger (http://www.statpower.net/Software.html). I simply cannot figure out how to use it.
A paper by Steiger ("Tests for Comparing Elements of a Correlation Matrix", Psychological Bulletin, 1980, 87(2)). But I cannot figure out how/where my numbers fit with the formulas he has provided there.

Ideally, I'd just like the mathematical formula(s) I can use to get my chi-square observed value (I have the critical value tables already).
Any guidance that could be offered would be most appreciated.
Answer: Okay, so with some help I managed to figure out how to use "Multicorr". Here's the input files that I created (the formatting of these files is discussed in the Multicorr documentation):
First Test
CORRELATION MATRIX -- IDENTITY
    5  172   4 9876
(5F7.2)
 1.00
 -0.480 1.00
 -0.158 0.276  1.00
 -0.246 0.395  0.234  1.00
 -0.257 0.327  0.122  0.362  1.00
    2    1    0.0
    3    2    0.0
    4    2    0.0
    5    2    0.0

The first block of numbers is the correlation matrix for all of the variables involved (i.e., A, B, C, D, E). The second block of numbers is the indices of the correlations that I want to test, and what I want to test them against (e.g., "2 1" is 0.276)
Second Test
CORRELATION MATRIX -- EQUALITY
    5  172   4 9876
(5F7.2)
 1.00
 -0.480 1.00
 -0.158 0.276  1.00
 -0.246 0.395  0.234  1.00
 -0.257 0.327  0.122  0.362  1.00
    2    1    1
    3    2    1
    4    2    1
    5    2    1

By putting "1" as the value to test against, Multicorr assumes that you are testing correlations AGAINST EACH OTHER. So all the indices that are tested against "1" are, in fact, tested against each other (e.g., if you put "1" for half of them and "2" for the other half, they would only be tested against the ones with the same number)
Third Test
PAPER -- CORRELATION MATRIX -- LIMITED EQUALITY
    5  172   3 9876
(5F7.2)
 1.00
 -0.480 1.00
 -0.158 0.276  1.00
 -0.246 0.395  0.234  1.00
 -0.257 0.327  0.122  0.362  1.00
    3    2    1
    4    2    1
    5    2    1

The output of Multicorr, on the last line, gives you the chi-square value, the degrees of freedom, and the p-value.
Note: You are going to need DOS Box to run Multicorr.


Is the set of roots of power series with integer coefficients countable?

Question: Title says it all.  It is clear that the set of all power series with integer coefficients is not countable while the set of algebraic numbers is countable, but I do not know whether the set of roots for power series with integer roots is uncountable.
Answer: Even ignoring the all-zeroes power series (of which every number is a root), it's still definitely uncountable. Given any $a\in (-1, 1)$ we can construct a nonzero power series $f_a$ with $a$ as a root. Basically, higher powers of $a$ yield smaller numbers, so we build $f_a$ as follows. First, suppose WLOG that $a\not=0$ (otherwise just make the constant term zero). Then note that (i) for all positive reals $\epsilon$, there is some even positive integer $n$ such that $0<a^{n}<\epsilon$, but (ii) for any positive $N$ and any positive even $n$ there is some positive integer $m$ such that $ma^n>N$.
This lets us recursively define a sequence of coefficients $a_i$ such that for each $n$, the sum $a_0+a_1a^2+a_2a^4+...+a_na^{2n}$ is between $0$ and ${1\over n}$; hence the whole power series goes to zero, and so $a$ is a root of $$\sum_{n\in\mathbb{N}}a_nx^{2n}.$$ Since there are uncountably many $x$ in $(-1, 1)$, this finishes the proof.
Comment: That's what I get for typing on a cell phone. I didn't realize it was taking that long, and I didn't see your answer.
Comment: This is interesting, thanks.  I wonder of there is a growth condition that can be placed on the coefficients.  Similarly, can you get the same result if you bpundits the coefficients.  If the answer is not trivial, I can ask separately.
Comment: @MattSamuel Well, your answer goes into much more detail than mine.
Answer: Let $0<a<1$ be irrational. I claim that there is a power series
$$\sum{a_nx^n}$$
 with integer coefficients that vanishes at $a$.
If $a>\frac12$, let $a_0=1$ and $a_1=-1$, otherwise let $a_0=0$ and $a_1=1$. Suppose recursively that $k\ge 1$ we have defined $a_0,\ldots,a_N$ such that
$$0<\sum_{n=1}^N{a_na^n}<\frac1{k+1}$$
We choose $N'$ and $a_{N+1},\ldots,a_{N'}$ such that
$$0<\sum_{n=1}^{N'}{a_na^n}<\frac1{k+2}$$
If the sum (let's call it $A$ for brevity) already satisfies this let $N'=N$. Otherwise choose $N'$ large enough that
$$a^{N'}<\frac1{2(k+2)}$$
Let $a_i=0$ if $N<i<N'$. Then let
$$a_{N'}=-\left\lceil\frac{(A-\frac1{k+2})}{a^{N'}}\right\rceil$$
Then
$$0<A+a_{N'}a^{N'}<\frac1{k+2}$$
Letting $k\to\infty$, we end up with a power series with integer coefficients that vanishes at $a$, which should answer your question.


Why does it show value 5150 and not 155?

Question: So im quite new to javascript and i tried making something simple as entering a value and add 150 to it but it wont show number + 150?
Pictures below
Code
Output
Comment: Dont mind the "check if your right" button, i was just messing around before i decided to make this
Answer: Because you're actually concatenating a string with a number. The input value is a string, so before operating with it, parse it to int with parseInt
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
Comment: Thank you, i read through the link and it gave me a clearer picture :)
Answer: That's because you are concatenating strings.  You need to convert the strings to integers by using parseInt(), and then add the numbers.
https://www.w3schools.com/jsref/jsref_parseint.asp
var fullprice = parseInt(price) + 150;

Comment: Thank you very much, it worked! But i do wonder why it doesnt work with just price + 150 cause none of them are string or am i wrong? :)
Comment: Yes, price is a string since you are using getElementById("pris").value to retrieve the value from HTML.
Comment: Even thought there is no need to use types in Javascript, there are! An input can contain a number but it's value is returned as a String. `typeof "5"` would return `string` and `typeof 5` would return `number`
Comment: Ah i see, so i would just use parseInt() to get number instead of string? :)
Comment: Yes. you can always check the type of a variable by using the `typeof` operator. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
Comment: I see, thank you very much!


Dimension and morphism with finite fibers

Question: I'm studying the dimension of projective varieties and in the literature I'm reading I have the following statement:

"If $f : X → Y$ is a morphism with finite fibers, i. e. such that $f^{−1}(P)$ is a finite set for all P ∈ Y , we would expect that dim $ X ≤ \text{dim }Y$ .

Can someone provide some details regarding this "expectation"? It is clear to me that we would expect a lower dimension if $f$ is injective, since we then can perceive $X$ as "contained in" $Y$.
Answer: The "expectation" is actually a theorem:

Let $f:X\to Y$ be a morphism of varieties of finite type over a field $k$.
  If the fibers of $f$ are finite sets, then $\operatorname {dim} X\leq \operatorname {dim} Y$

Remarks
a) Notice that projectivity of either variety is irrelevant and that $k$ is not assumed algebraically closed.
b) Morphisms of finite type  with finite fibers are called quasi-finite.
c) A quasi -finite morphism is finite iff it is proper.
d) A non-trivial open immersion is the  prototype of a quasi-finite but not finite morphism .
e) More generally, any quasi-finite morphism is obtained by deleting a closed subset upstairs from a finite morphism: this is a consequence of the difficult Zariski Main Theorem.


Binding data from textbox to datagrid

Question: I'm making a Contact info program, where users can enter there name, age and birthday and some other things into textboxes. When you click ok, I want the data to be put into the DataGrid.
First I have my MainWindow, which opens a new window called CreateContact when you press the Create new contact button:
CreateContact cc = new CreateContact();
cc.ShowDialog();

then a new window open, where you type your name and age and choose the birthdate. Then you click OK:
private void cmdOk_Click(object sender, RoutedEventArgs e)
{
     MainWindow m = new MainWindow();
     m.name = txtName.Text;
     m.age = txtAge.Text;
     m.birthDate = dpBirthdate.Text;
     m.ShowContacts()
}

which should run my method ShowContacts in my MainWindow:
public string name;
public string age;
public string birthDate;

public void ShowContacts()
{
    try
    {
         dgContacts.ItemsSource = LoadContactData();
    }
    catch (Exception e)
    {
         MessageBox.Show("" + e);
    }
}

private List<ContactData> LoadContactData()
{
    List<ContactData> list = new List<ContactData>();
    list.Add(new ContactData()
    {
        Name = name,
        Age = age,
        BirthDate = birthDate
    });
    return list;
}

public class ContactData
{
    public string Name { get; set; }
    public string Age { get; set; }
    public string BirthDate { get; set; }
}

But nothing happens, I get no data in the DataGrid. I hope someone can tell me what is wrong. I have really tried searching a lot on what is causing the DataGrid to show no data.
Comment: I can't understand when are you persisting the contact information and how are you retrieving it?
Comment: pls explain how are you retrieving datat ?
Comment: Please post your XAML code
Comment: 1) name, age, and birthDate need to be setup as properties. 2) Use INPC and ObservableCollections instead of rebuilding the ItemsSource every time.
Answer: Assuming the dgContacts is the datagrid view control, you have to call the following command to ensure that the data is bound

dgContacts.DataBind();

The procedure is similar to the one that is explained here.
In case you have debugged the code, and this suggestion is not working, please debug and post whether the data that is bound to the control.
Answer: Short answer: looks like you're not firing the PropertyChanged event when you change the ItemsSource in ShowContacts.
Long answer: you should really look into MVVM. You should just create a ViewModel that maintains a list of ContactData, and bind to that list in your XAML (also databind your Contact dialog to a ContactData object):
var contact = new ContactData();
var cc = new CreateContact { Datacontext = contact };
cc.ShowDialog();

// ok button has been hit at this point,
// you can check for cancel if you want
(List<ContactData>)(dgContacts.ItemsSource).Add(contact);

// may still need to fire PropertyChanged here depending on binding

Answer: Okay, here is all the xaml and classes i use in the program. I really hope someone can help tell, what is wrong and why it wont show any data in the datagrid.
MainWindow.xaml:
 <Window x:Class="KontaktInfo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <DataGrid AutoGenerateColumns="True" Name="dgContacts" HorizontalAlignment="Left" Margin="0,95,0,0" VerticalAlignment="Top" Height="225" Width="517"/>

    <Button x:Name="cmdCreateContact" Content="Opret Kontakt" HorizontalAlignment="Left" Margin="0,68,0,0" VerticalAlignment="Top" Width="80" Click="cmdCreateContact_Click"/>
    <Button x:Name="cmdDeleteContact" Content="Slet Kontakt" HorizontalAlignment="Left" Margin="85,68,0,0" VerticalAlignment="Top" Width="80"/>

</Grid>

MainWindow.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace KontaktInfo
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public string name;
        public string age;
        public string birthDate;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void cmdCreateContact_Click(object sender, RoutedEventArgs e)
        {
            CreateContact cc = new CreateContact();
            cc.ShowDialog();
        }

        public void ShowContacts()
        {
            try
            {
                dgContacts.ItemsSource = LoadContactData();
            }
            catch (Exception e)
            {
                MessageBox.Show("" + e);
            }
        }

        private List<ContactData> LoadContactData()
        {
            List<ContactData> list = new List<ContactData>();
            list.Add(new ContactData()
            {
                Name = name,
                Age = age,
                BirthDate = birthDate
            });

            return list;
        }

    }

public class ContactData
    {
        public string Name { get; set; }
        public string Age { get; set; }
        public string BirthDate { get; set; }
    }
}

CreateContact.xaml:
     <Window x:Class="KontaktInfo.CreateContact"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="CreateContact" Height="403" Width="300">
    <Grid>

        <TextBox x:Name="txtName" HorizontalAlignment="Left" Height="23" Margin="10,36,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="272"/>

        <TextBox x:Name="txtAge" HorizontalAlignment="Left" Height="23" Margin="10,90,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="272"/>

        <Button Name="cmdOk" Content="OK" HorizontalAlignment="Left" Margin="127,341,0,0" VerticalAlignment="Top" Width="75" Click="cmdOk_Click"/>
        <Button Name="cmdCancel" Content="Annuller" HorizontalAlignment="Left" Margin="207,341,0,0" VerticalAlignment="Top" Width="75"/>
        <DatePicker Name="dpBirthdate" HorizontalAlignment="Left" Margin="10,144,0,0" VerticalAlignment="Top"/>

    </Grid>
</Window>

CreateContact.cs:
     using System;
     using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace KontaktInfo
{
    ///
    /// Interaction logic for CreateContact.xaml
    ///
    public partial class CreateContact : Window
    {
        public CreateContact()
        {
            InitializeComponent();
        }

        private void cmdOk_Click(object sender, RoutedEventArgs e)
        {
            MainWindow m = new MainWindow();
            m.name = txtName.Text;
            m.age = txtAge.Text;
            m.birthDate = dpBirthdate.Text;
            m.ShowContacts();

        }
    }
}

Binding data from textbox to datagrid


Easiest way to run an unbalanced 2-way ANOVA

Question: Trying to help a friend out who has no idea about statistics but who has to compare a few samples for a medical paper.
So we have 6 different types of fingers which underwent 3 different treatments. There are 42 fingers in total which were assigned to these treatments randomly, so n for every combination is between 1 and 5. We took 5 measurements on these fingers, before and after treatment. We're trying to compare the treatments against each other and also whether they had any effect at all.
My stats knowledge isn't great either, but to me that sounds like one unbalanced 2-way ANOVA per measured variable (MANOVA would be a bit far...) - at least to compare treatments against each other. I don't know much about this, but I was hoping to get something out of Anova from the car package, using Type 3 ANOVA? Can we then use TukeyHSD for pairwise comparisons between treatments, even if the distribution of finger types within treatments could vary? That doesn't seem quite right...
Lastly - is the before/after test something completely different to this or should it be done as part of the same test?
Thanks a lot!
Answer: My best advice is, if by "medical paper" you mean something that will be published and valuable for others, that you consult someone a little better versed in analyzing experiments.
It's absolutely unclear to me in what way you think you can consider the "before/after" test as something different from the analysis you are considering.  Isn't the whole point of your study to compare the subjects before and after the applied treatments?
One way to simplify the analysis is to change the dependent variable to account for both the before and after measurements. For example by making the dependent variable the difference between before and after, of the ratio of after to before.
In general, I don't advise this approach, essentially because you are discarding information on your measurements.
The better approach is to use a model that takes into account the repeated measures nature of your data.  That is, the before and after nature of the measurements.  This is usually accomplished with a mixed effects model (e.g. using the nlme or lme4 packages).
As to the specific functions in R.  1) Note that to get type-3 sum of squares from car::Anova, that you need to change the contrast coding in R or your model first.  2)  Forget TukeyHSD. You can read the documentation for that function for some of its limitations.  For a better approach, investigate the lsmeans package, which includes a Tukey adjustment of p-values.


How to display content fields horizontally?

Question: I tried to display the content of the fields horizontally but was unsuccessful. It is always the showing vertical view. Am I missing something?
This is the php code.
Thanks for the help.

Details

    <?php foreach ($custom_fields['quote'] as $custom_quote_field_name => $custom_quote_field_value) : ?>

<?php echo $custom_quote_field_name; ?> : <?php echo $custom_quote_field_value; ?>

    <?php endforeach; ?>

Comment: Possible duplicate of [Horizontal list items](https://stackoverflow.com/questions/15710701/horizontal-list-items)
Comment: We need to see your CSS and rendered HTML; the PHP is irrelevant to your question
Answer: Your problem lies with your CSS and HTML output, and not necessarily the PHP generating it.
If you have access to the CSS stylesheet, you could use several methods:
Inline-block
ul {
    font-size: 0;
    /*makes inline-block method work, as " " in your DOM have a font-size,
      and we want to eliminate those
    */
}
ul li {
    font-size: 18px; //or however large you would like
    display: inline-block;
    width: calc(100% / X); //where X is number of li
}

Float
ul {

}
ul li {
    font-size: 18px; //or however large you would like
    float: left;
    margin-left: X; //where X is the gap you want between elements
}

Flexbox
ul {
   display: flex;
   flex-wrap: wrap;
   justify-content: space-between;
}
ul li {

}

Answer: I'm not sure if I understood Your problem, but You are probably thinking about php like it can be used to style data generated by Your script. You need to replace
 in Your code with <li style="float: left; margin-left: 28px;". This code uses inline CSS used for styling HTML elements like unordered list generated by Your script.
Float: https://www.w3schools.com/cssref/pr_class_float.asp
Margin: https://www.w3schools.com/cssref/pr_margin.asp
Margin is optional here, I just recommend to add this because of a little bit messy look of the list with only float applied.
Comment: Thanks a lot guys,
Answer: Thanks a lot Guys,
This is the code works for me:

Details

    <?php foreach ($custom_fields['quote'] as $custom_quote_field_name =>
    $custom_quote_field_value) : ?>

    <?php echo $custom_quote_field_name; ?> <?php echo $custom_quote_field_value; ?>

    <?php endforeach; ?>


error: non-static variable this cannot be referenced from a static context / Java 8

Question: Estou fazendo um exercicio do URI (online judge) mas está apresentando "compilation error" devido ao erro:
Main.java:8: error: non-static variable this cannot be referenced from a static context
InterfaceTexto i = new InterfaceTexto();
^
1 error
Segue o código:
import java.util.Scanner;
import java.io.IOException;

public class Main
{
    public static void main(String[] args) throws IOException
    {
        InterfaceTexto i = new InterfaceTexto();
        i.executar();
    }
class InterfaceTexto
{
    private Scanner entrada;
    private Fibonacci fibonacci;
    private int n;
    private int t;

    public InterfaceTexto()
    {
        entrada = new Scanner(System.in);
        fibonacci = new Fibonacci();
    }

    public void executar()
    {
        t = entrada.nextInt();

        for(int i = 0; i < t; i++)
        {
            fibonacci();
        }
    }

    public void fibonacci()
    {
        n = entrada.nextInt();
        System.out.printf("Fib(%d) = %d\n", n, fibonacci.numeroFibonacci(n));
    }
}
class Fibonacci
{
    private int[] fib;
    private int n;
    private static final int TAM = 61;

    public Fibonacci()
    {
        fib = new int[TAM];

        fib[0] = 0;
        fib[1] = 1;

        for (int i = 2; i < TAM; i++)
            fib[i] = fib[i-1] + fib[i-2];
    }

    public int numeroFibonacci(int n)
    {
        int numero = fib[n];

        return numero;
    }
}
}

Answer: Solução rápida
Faltou a chave para fechar a classe Main.
public class Main {
    public static void main(String[] args) throws IOException {
        InterfaceTexto i = new InterfaceTexto();
        i.executar();
    }
// aqui
}
    class InterfaceTexto
    {
        ...
    }

Entendendo o problema

Quando você não fechou a chave da classe Main, InterfaceTexto se tornou uma classe interna.
Para instanciar a classe interna a partir de um método (não estático) da classe ficaria assim:

    public void anyMethod() {
        InterfaceTexto i = new InterfaceTexto();
    }

Mas quando você tentou instanciar a partir do método main, você encontrou esse erro:
non-static variable this cannot be referenced from a static context
O que o erro está dizendo é:

variáveis não estáticas (se referindo a classe InterfaceTexto) não podem ser referenciadas no contexto estático.
o contexto estático é porque você está dentro do método main
se o problema envolvesse declarar a classe interna como estática, então você poderia instanciar um objeto dentro de main como você fez! Mas não acredito que seja esse o melhor caminho.

static class InterfaceTexto {
...
}

Referências para leitura
Veja aqui uma boa leitura sobre classes internas/aninhadas aqui do SOpt


How to compare each value with Max value for a Project with in the same column in Pandas

Question: I'd like to calculate Max score - each score for a project in pandas Dataframe
current df looks like this:
projectID supplierID score
1         1          50
1         2          60
1         3          75

I want it to look like this:
projectID supplierID score diff_to_max
1         1          50    25
1         2          60    15
1         3          75    0

and I want to do this action for each projectID
Answer: Broadcasting with transform and subtracting
df.groupby('projectID').score.transform('max') - df.score

Answer: Non-straight forward but fast/cool way using Numpy
i, r = pd.factorize(df.projectID)
score = df.score.values
out = np.empty(len(r), score.dtype)
out.fill(score.min() - 1)

np.maximum.at(out, i, score)

df.assign(diff_to_max=out[i] - score)

   projectID  supplierID  score  diff_to_max
0          1           1     50           25
1          1           2     60           15
2          1           3     75            0


How to add a function to web form submit button?

Question: On a Drupal site, when a form submission is done. I need to trigger a SMS. I am unable to edit the form submit code. Please let me know how to add a function to webform submit button. So that on SUBMIT button click the SMS function get executed as well the form data goes to the database.
Answer: Your mileage will vary, but it's the same as adding submit handlers to any form:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo') {
    $form['actions']['submit']['#submit'][] = 'MYMODULE_some_function';
  }
}

function MYMODULE_some_function($form, &$form_state) {
  // Do something...
}

See hook_form_alter() for full details.
Comment: That would probably refer to the JS `alter()` function (PHP doesn't have a namesake). Good luck getting it sorted anyway
Comment: But the problem with MYMODULE_form_alter function is the submissions will not get stored in the database.
Comment: Sorry I don't understand - you're adding an _extra_ submit handler, you're not replacing the existing one(s). Is that what you meant?
Comment: yes exactly.. on submit click i want both functions. Default form submit action as well as additional functionality of sending a SMS
Comment: Yep, that's _exactly_ what the above code does. Always best to check whether something works first before guessing that it won't
Comment: Previously i had seen the some answers on a question about the alert function. Thanks for the answer. Will they it out.


How do I programmatically change the admin theme?

Question: How do I define a different administration theme for a user and administration role in Drupal 8?
I have looked at the context module for Drupal 8. There is a problem with the context condition and the reaction theme related items are all based on the front-end themes. I need the same but for the back-end themes.
My code is the same as the context reaction code for Theme.php. I just changed the submitConfiguration().
 /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $configuration['admin'] = $form_state->getValue('theme');
    $configuration += $this->getConfiguration();
      \Drupal::configFactory()
          ->getEditable('system.theme')
          ->set('admin', $form_state->getValue('theme'))
          ->save();
    $this->setConfiguration($configuration);
  }

I defined the following in the context configuration.

Condition => Role:User
Reaction => Admin Theme: Customtheme
Condition => Role: Administrator
Reaction => Admin Theme: Seven

Is this possible? Are there other methods for achieving this goal?
Answer: I came here just looking for a solution on how to programmatically set the admin theme (say during hook_install or hook_update).
This code will achieve that:
// Make sure the theme is installed
$theme_handler = \Drupal::service('theme_handler');
$theme_handler->install(['my_custom_admin_theme']);

// Set it as the admin theme
$config = \Drupal::service('config.factory')->getEditable('system.theme');
$config->set('admin', 'my_custom_admin_theme')->save();

Answer: As the context module is still in alpha I would try a solution in custom code by extending the class AdminNegotiator:
src/Theme/CustomAdminNegotiator.php
<?php

namespace Drupal\mymodule\Theme;

use Drupal\user\Theme\AdminNegotiator;
use Drupal\Core\Routing\RouteMatchInterface;

class CustomAdminNegotiator extends AdminNegotiator {

  public function determineActiveTheme(RouteMatchInterface $route_match) {
    if (in_array('custom_role', $this->user->getRoles())) {
      return 'custom_admin_theme';
    }
  }

}

and register this service class in mymodule.services.yml tagged as theme negotiator with a priority higher than the default admin negotiator (-40):
services:
  theme.negotiator.admin_theme.custom:
    class: Drupal\mymodule\Theme\CustomAdminNegotiator
    arguments: ['@current_user', '@config.factory', '@entity.manager', '@router.admin_context']
    tags:
      - { name: theme_negotiator, priority: -39 }

The applies() method is kept the same as in AdminNegotiator, so that only users with the correct permission have access to this theme and this only applies for admin routes.


Erro ao abrir um arquivo zip no PHP

Question: Código:

echo file_get_contents('zip://arquivos.zip#zipado.txt');

Erro de saída:
Aviso do PHP: file_get_contents(): Não foi possível encontrar o wrapper "zip" - você esqueceu
de habilitá-lo quando configurou o PHP? no código shell php online 1
Aviso: file_get_contents(): Não foi possível encontrar o wrapper "zip" - você esqueceu de
habilitá-lo quando configurou o PHP? no código shell php na linha 1 PHP Warning:
file_get_contents(zip://arquivos.zip#zipado.txt): Falha ao abrir o fluxo: Não existe esse
arquivo ou diretório no código shell php na linha 1

Aviso: file_get_contents(zip://arquivos.zip#zipado.txt): Falha ao abrir stream: Não existe tal
arquivo ou diretório no código shell php na linha 1

Toda vez que tento exibir um arquivo em PHP, ele retorna esse erro e não consigo executar meu
código porque a única saída é um erro, por favor me ajude!

    PHP Warning: file_get_contents(): Unable to find the wrapper "zip" - did you forget to enable it when you configured PHP? in php shell code on line 1

Warning: file_get_contents(): Unable to find the wrapper "zip" - did you forget to enable it when you configured PHP? in php shell code on line 1 PHP Warning: file_get_contents(zip://arquivos.zip#zipado.txt): Failed to open stream: No such file or directory in php shell code on line 1

Warning: file_get_contents(zip://arquivos.zip#zipado.txt): Failed to open stream: No such file or directory in php shell code on line 1

Answer: olá, qual o caminho do arquivo .zip?
1 - Verifique seu a extensão Zip está instalada no (php.ini)
2- Tente abre assim:
A) $resultado= file_get_contents('zip://foo.zip#dirName/bar.txt');
B) $resultado= file_get_contents('zip://path_to_my.zip#subDir/foo.txt');
Tem duas opções veja qual te antende melhor. Espero te ajudado

Erro ao abrir um arquivo zip no PHP


Graphite : invalid line received from client (codahale metrics)

Question: I received errors in carbon when trying to using metrics for graphite :
[listener] invalid line received from client HOST:PORT, ignoring

So, I tried to add some logs in /opt/graphite/lib/carbon/protocols.py like this.
And I see in logs this errors:
28/07/2015 10:21:14 :: [listener] invalid line - [ tta(S'com.unnyworld.db.dbclient.request_time.auth.max' ]
28/07/2015 10:21:14 :: [listener] invalid line - [ (L1438078874L ]
28/07/2015 10:21:14 :: [listener] invalid line - [ S'5' ]

And if we looking for normal request, it looks like:
28/07/2015 10:31:07 :: [listener] nice line - [ stats.counters.statsd.bad_lines_seen.rate 0 1438079468 ]

What's problem here? Is it carbon problem? Or is it metrics problem? And how can I resolve it?
Metrics version is 3.1.2
Carbon version 0.9.x
Answer: My mistake. I sent data to 2003 port, but it's only for plain text.
You should use 2004 port if using pickle protocol, like mentioned here.
Comment: I'm curious why you preferred pickle over line protocol. The metric name is still duplicated in each sample in pickle, so there will be no obvious network savings.
Comment: @SergeiRodionov cause I can send batches in one go
Comment: What about latency? Is there a background thread to flush metrics that have accumulated in List list and are sitting there because the list size is below DEFAULT_BATCH_SIZE?
Comment: @SergeiRodionov dropwizard metrics has background thread. And you set period for sending metrics.
Comment: Ok, that's good to know. Max latency == background thread flush period. Thanks.


Assign a Form object dynamically

Question: I have 3 Forms that share common code, which is executed before the Form is shown. I need to use the same code for all the 3 Forms.
At run-time, I want to create an object for each Form and assign it to a Form class object.
My code:
If (NcCode = "HM1" Or NcCode = "HM2" Or NcCode = "HM3" Or NcCode = "HM4") Then
 Dim frmHandlingTime As New HandlingTime()
//some code goes here
 ElseIf (NcCode = "ULL1" Or NcCode = "ULL2" Or NcCode = "ULL3" Or NcCode = "ULL4" Or NcCode = "ULL5" Or NcCode = "L1" Or NcCode = "L2") Then
  Dim frmHandlingTime As New HandlingTimeLabel()
//same above code goes here
end if

I have a Friend function in each Form. I have to repeat the same code for each condition. Instead of repeating this code, I want to initialize a Form object, assign it to a common object and call all common code:
Dim obj as Form
obj=new HandlingTimeLabel()
obj.InitHandlingTime(NcCode)

But this is not allowed.
This line, obj.InitHandlingTime(NcCode), causes an error:

InitHandlingTime is not a member of Form.

Any inputs for this issue to proceed with.
Comment: You might want to move that common code to a public method in a class or module.
Answer: Try this:
Dim obj As HandlingTimeLabel
obj = new HandlingTimeLabel()
obj.InitHandlingTime(NcCode)

The Form object doesn't have a InitHandlingTime method so you can't declare obj as Form.

Assign a Form object dynamically


PHP modulus division not calculating properly- Codepad provided

Question: I should be getting exactly 72 hours, but it's giving me 72 hours and 12 seconds...why???
http://codepad.org/KNj44By5
Comment: Technically each day is not exactly 24 hours. That's why we have leap years.
Comment: So you're saying this example will pose a problem? I'm using this to calculate hours worked, and I needed a calculation to add total hours for a week, month, whatever (over 23:59:59).
Answer: Because your math is wrong. $elapsed will be in seconds, so you do not need to divide it before taking the modulus. What you are really getting is the modulus of hours % 60.
It will work like this:
$in = strtotime("2011-10-02 23:00:00");
$out = strtotime("2011-10-05 23:00:00"); // 72 hours apart

$elapsed = $out - $in;

$hours = floor($elapsed / 3600);
$minutes = floor(($elapsed / 60) % 60);
   if (strlen($minutes) == "1") { $minutes = "0".$minutes; } // No single digits

$seconds = $elapsed % 60;
   if (strlen($seconds) == "1") { $seconds = "0".$seconds; } // No single digits

$total = $hours.":".$minutes.":".$seconds; // Should be 72:00:00

echo $total

EDIT
You also screwed up your zero-padding. You were turning 2 into 20.
Updated codepad here: http://codepad.org/XY8L9EJ1


How to implement *ngIf/disabled on element of child component, predicated on parent component

Question: Parent component markup:
<full-screen-dialog-header (onClickPrimaryAction)="onClickSaveCustomer()"
  (primaryActionDisabled)="*ngIf=customerFormGroup.enabled && !customerFormGroup.valid">
</full-screen-dialog-header>

Child component:
export class FullScreenDialogHeaderComponent {

  @Input() primaryActionDisabled: Observable<boolean>;
  @Output() onClickPrimaryAction = new EventEmitter();

  public onClickPrimaryActionEvent($event) {
    this.onClickPrimaryAction.emit($event);
  }
}

Child markup
...
<button mat-button (click)="onClickPrimaryActionEvent($event)"
[disabled]="primaryActionDisabled">{{primaryActionText}}</button>
...

I am trying to get @Input() primaryActionDisabled: Observable<boolean> to work.
My issue and expected behavior is:

In Parent markup when I try simply (primaryActionDisabled)="!customerFormGroup.valid"- I expected the child's primaryActionDisabled to contain the observable value of the result of !customerFormGroup.valid, but its not.
Comment: why the value is not there because primaryActionDisabled is an input,
 so you have to write like `[primaryActionDisabled]="!customerFormGroup.valid"` note the square brackets and you can  make it just boolean, why observable?
Comment: I guess you need observable, otherwise change detection will not work properly.
Comment: Square brackets was it..  Missed the obvious one this question..  As for combining logic..  Will try [@Martin Adámek's](https://stackoverflow.com/users/3665878/martin-ad%c3%a1mek) to address combining the 2 conditions.
Answer: First of all, when using @Input decorator, you should use [primaryActionDisabled] binding.
Then you need to pass observable there, not expression:
// in parent controller
primaryActionDisabled$ = new BehaviorSubject<boolean>(true); // disabled by default

// in parent template
<full-screen-dialog-header
    (onClickPrimaryAction)="onClickSaveCustomer()"
    [primaryActionDisabled]="primaryActionDisabled$">
</full-screen-dialog-header>

Then you will need to call primaryActionDisabled$.next(newBoolValue); every time the value should change (so every time the expression customerFormGroup.enabled && !customerFormGroup.valid changes value). This will be again handled in your parent component.
Last thing, in your child component, use async pipe to work with the value of that observable:
<button mat-button
        (click)="onClickPrimaryActionEvent($event)"
        [disabled]="primaryActionDisabled | async">{{ primaryActionText }}</button>

Comment: Thanks..  Totally missed square bracket binding..  Was hoping I could pass an expression or otherwise handle it ''cleaner" in markup.  Will acecpt your answer after 6 min.
Comment: You could also pass a callback, but you need to bind it to the parent component if you want to use its variables, that way there will be no observables, but it will be probably less performant.


php script connecting to my SQL database

Question: When trying to connect to my database using PHP I am getting an error.
$connect = mysql_connect("localhost","username","password") or die ("Couldn't Connect!");
mysql_select_db("databasename") or die ("Couldnt find database");

When I try running the script it keeps saying 'Couldnt find database' which means that I am connecting to the server but my database won't connect.
Am I doing something wrong here? I have pretty much copied and pasted my database name from Cpanel so I know there aren't any mistakes. But in Cpanel it is displayed as 'mywebsite'_database
Any ideas?
Comment: Have you tried using `mywebsite_database` as the database name?
Comment: instead of selecting a db, you could just do a query `show databases;` to get a list of all of them. yours would be listed in there somewhere, and show you the exact name of it, direct from the db's mouth.
Comment: Ye say for example my database name is domain_phplogin thats whay i typed out in the connection and it still didnt show
Answer: You specify in your question that your database is called:

'mywebsite'_database

If this is the case, then you need to change your code to
// Connect to the database
$connect = mysql_connect("localhost","username","password") or die ("Couldn't Connect!");

// Select the database
mysql_select_db("mywebsite_databasename",$connect) or die ("Couldnt find database");

If the above method does not work then I would advise debugging your connection by listing the databases for that particular user. Do this like so:
// Connect to the database
$connect = mysql_connect("localhost","username","password") or die ("Couldn't Connect!");

// Get all the databases for this particular user
$databases = mysql_list_dbs($connect);

// Loop through the databases and write them on the screen
while($database = mysql_fetch_assoc($databases)) {
     echo $database['Database']."\n";
}

exit;

Comment: Thanks, i did this but it still says Couldnt find database, is the rest of the code right?
Comment: @BenJShapiro Oh, missed one key thing, check now! :-)
Comment: Yup :-) But I think there may be another issue, I would advise debugging by listing the databases for that particular user. See my edit in 30 secs :-)
Comment: Brilliant thanks ben, Im not getting that error message any more but all i am getting now is a blank page, where as earlier i would get "Please enter a username and a password!"
Comment: @BenJShapiro I have written `exit;` which stops the script from going any further. This is probably why :-)
Answer: mysql_select_db("mywebsite_database")
Comment: Can you provide any more explanation for your post? This answer is pretty sparse.
Answer: Print out the names of all the databases in the server (using mysql_list_dbs).
Find the correct database name and replace "databasename" with it.
$connect = mysql_connect("localhost","username","password") or die ("Couldn't Connect!");

$db_list = mysql_list_dbs($connect);

while ($row = mysql_fetch_object($db_list)) {
     echo $row->Database . "\n";
}

mysql_select_db("databasename", $connect) or die ("Couldnt find database");

I recommend using MySQLi extension as mysql_* is currently in a depreciation process.
I hope this helps
Comment: Can you provide any more explanation for your post? This answer is pretty sparse.
Comment: when i tried this i got, 'information_schema Couldnt find database'
Comment: They are the same answer - glad you got it sorted in the end =)


Como criar uma conexão com um db externo com um app Phonegap?

Question: Estou entrando e estudando o mundo do Phonegap/Cordova e quero começar a desenvolver aplicativos mais legais e com mais interação, mas estou encontrando essa limitação, na maioria dos locais onde eu encontro para aprender, os bancos de dados para as aplicações utilizando Phonegap/Cordova são locais e gostaria de saber se é possível fazer uma aplicação utilizando essas ferramentas(de forma segura) com um banco de dados externo e se sim, como fazer.
obs: já encontrei perguntas com respostas aqui mesmo que diziam que era possível realizar a conexão com o banco com o JS, mas em contrapartida, isso não era seguro.
Answer: Diretamente no lado cliente não é possível conectar diretamente no banco de dados.
No lado servidor, com javascript temos o NodeJS que faz essa conexão. Ou mesmo pode usar várias outras linguagens como ASP.NET, PHP, Java, Python, Ruby (on Rails) etc.
O que se utiliza é criar um WebService REST (mais fácil) ou WebSocket (menos utilizado) para a comunicação do servidor com a aplicação cliente.
Uma vez tendo o servidor, o cliente pode se comunicar com http ou websocket para trocar dados com o servidor e assim com o banco de dados.
Existem várias alternativas dependendo do framework javascript que você for usar se você for usar um.
Procure por WebServices e requisições AJAX.
Comment: Obrigado Shura16
Answer: Olá, uma opção muito legal que deixa transparente pra você essa parte de XHR e ajax e tem todo um back-end à sua disposição é o Firebase, um serviço do google que pode ser acessado com javascript. Dá uma olhada lá..


:hover not working on my svg path

Question: I'm having trouble changing the opacity on my SVG paths with a hover. Here's my code:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<path class='slice' id='slice1' d='M200,200 L199,20 A180,180 0 0,1 380,199 z' fill='#000'/>
<path class='slice' id='slice2' d='M200,200 L380,199 A180,180 0 0,1 305,345 z' fill='#468966'/>
<path class='slice' id='slice3' d='M200,200 L305,345 A180,180 0 0,1 200,380 z' fill='#FFF0A5'/>
<path class='slice' id='slice4' d='M200,200 L200,380 A180,180 0 0,1 54,94 z' fill='#FFB03B'/>
</svg>

Answer: opactiy is incorrect you want opacity instead
Answer: There is the typo:
path:hover{opactiy:0.5;}

It should be:
path:hover{opacity:0.5;}

:hover not working on my svg path


Como enviar objeto como atributo de outro objeto de uma JSP para um controlador Spring?

Question: Olá,
Eu tenho uma classe Noticia relacionada ManyToOne com uma classe Secao. A classe Noticia possui um atributo do tipo Secao (onde ocorre a relação @ManyToOne). Gostaria de saber como faço para, no formulário de cadastro de notícias, enviar a seção a qual ela deverá fazer parte.
Nota: Eu já tenho a lista de seções disponíveis na JSP e o usuário seleciona a seção para a notícia que irá cadastrar através de um campo de seleção. Porém não sei como passar o objeto secao como atributo da notícia que irá ser cadastrada. Alguém pode me ajudar?
Obrigado.
Answer: <code><select name="secao.atributoDeSecaoQueSeraDefinido">
  <option value="politica">Política</option>
</select>
</code>
Você pode tentar fazer desta maneira, mas como você já deve ter a seção cadastrada, eu acho que pegando o objeto pronto do formulário não vai fazer o relacionamento. Então você pega apenas o valor da seção que o cara escolheu, busca pelo objeto desta seção e define no objeto notícia.


Trigonometry terms in GP and their values

Question:
Question:
If tan((π/12) - x), tan (π/12), tan((π/12) + x) in the order are the three consecutive terms of a GP then sum all the solutions in [0,314] is kπ. Find value of k.
Attempt:
I tried assuming a = tan (π/12) and y = tanx to make my calculations easier.
a^2 = (a+y)/(1-ay) * (a-y)/(1+ay)
Simplifying this simple removes y from the expression. What should I do?
Where am I missing.
Answer: Write tan as $\dfrac{\sin}{\cos}$ like
$$\dfrac{\sin\pi/12\cos(\pi/12-x)}{\cos\pi/12\sin(\pi/12-x)}=?$$
Now apply componendo & dividendo(https://brilliant.org/wiki/componendo-and-dividendo/)
Comment: ?? I couldn't reach to this expression. Wasn't it simple manipulations?
Comment: @Khizir, If $a,b,c$ are in GP $$b/a=c/b $$ Now as already mentioned please write tan as $\sin/\cos$
Comment: Yes, I know this thing, but taking it as sin/cos doesn't bring up this expression for me.
Comment: @Khizir, Please share your progress
Comment: Okay okay I get that... I was using b^2 = a*c. I thought finally we will have to solve it, why not directly use it... Thanks.. :)
Answer: Hint:
Writing like $b^2=ca,$
$$\dfrac{\sin^2A}{\cos^2A}=\dfrac{\sin(A-x)\sin(A+x)}{\cos(A-x)\cos(A+x)}$$
Now use Prove $ \sin(A+B)\sin(A-B)=\sin^2A-\sin^2B $
and
Prove that $\cos (A + B)\cos (A - B) = {\cos ^2}A - {\sin ^2}B$
Then
https://brilliant.org/wiki/componendo-and-dividendo/
Finally double formula for cosine.
Please let me know if you face any further problem?


Negative eigenvalues when computing MultiDimensional Scaling given nonnegative distance matrix

Question: I am using the Smile MDS
https://github.com/haifengl/smile/blob/master/core/src/main/java/smile/mds/MDS.java and occasionally running into:
<code>Caused by: java.lang.IllegalArgumentException:
Some of the first 2 eigenvalues are < 0
</code>
The data being sent in is a square symmetric distance matrix.  I have not put any restrictions on the distance matrix values except they must be nonnegative - which in fact all are between 0 and 1 inclusive.
So two questions:

under what conditions may such a (nonnegative) matrix result in negative eigenvalues?
how might I condition the input similarities matrix to avoid the negative values?
(extra credit): are there other JVM libraries that might help to deal with the existing (arbitrary non-negative) dataset as is?

Update
The diagonal of the distance matrix is all zeros.
Comment: You'll have to describe how this implementation works for this question to be answerable. If the software is computing an eigendecomposition of the raw distance matrix, your answer is immediate: distance matrices have 0s on the diagonal.
Comment: **Lingoes** correction and **Cailliez** correction are two principal ways to try to cure a distance matrix which is [geometrically non-euclidean](https://stats.stackexchange.com/a/69206/3277) (see Cause 1).
Answer: Classical MDS works by using the distance matrix to compute an inner product (Gram) matrix $G$. $G$ contains the dot products between each pair of data points, assuming the distances were Euclidean. It then performs an eigendecomposition of $G$ to embed points into a vector space in a way that that preserves the dot products as well as possible. $G$ can have negative eigenvalues if the original distances were not Euclidean. This can still be ok in some cases. But, if there are many negative eigenvalues, it may indicate that classical MDS is not a good fit for the problem. In this case, nonclassical MDS (of which there are multiple forms) may work better. As Sycorax pointed out, the distance matrix should have zeros on the diagonal.


Android - GUI layout

Question: I'm new to Android so not very good with GUi layout yet. I'm building a GUI for my app and just can't get it to behave the way I want. What I need is 4 buttons at the bottom of the screen stacked horizontally. Above the buttons I've placed a SurfaceView which I want to fill the rest of the screen. The result should be something like this (I hope this is clear):
-----------------
-               -
-               -
-               -
-               -
- SurfaceView   -
-               -
-               -
-               -
-----------------
 --- --- --- ---
 -B- -B- -B- -B-
 --- --- --- ---

The closeset I got was this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TableLayout
        android:id="@+id/tableLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center" >
            <SurfaceView
                android:id="@+id/surfaceView1"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" />
        </TableRow>
        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center" >
            <LinearLayout
                android:id="@+id/linearLayout1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" >
                <Button
                    android:id="@+id/button2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="Button" />
                <Button
                    android:id="@+id/button3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="Button" />
                <Button
                    android:id="@+id/button4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="Button" />
                <Button
                    android:id="@+id/button1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="Button" />
            </LinearLayout>
        </TableRow>
    </TableLayout>
</LinearLayout>

Which unfortunately results in something like this:
-----------------
- SurfaceView   -
-----------------
 --- --- --- ---
 -B- -B- -B- -B-
 --- --- --- ---

Answer: <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

            <SurfaceView
                android:id="@+id/surfaceView1"
                android:layout_width="fill_parent"
                android:layout_height="0dp"
                android:layout_weight = "1"
            />

            <LinearLayout
                android:id="@+id/linearLayout1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" >
                <Button
                    android:id="@+id/button2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="Button" />
                <Button
                    android:id="@+id/button3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="Button" />
                <Button
                    android:id="@+id/button4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="Button" />
                <Button
                    android:id="@+id/button1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="Button" />
            </LinearLayout>

</LinearLayout>

try this.
layout_weight is a tag which works on the children of linear layout. the children will share the orientation measurement depending on weight if it is mentioned. In your case since the linear Layout is vertical, so they will share the height if weights are mentioned.
default weightSum of linearLayout is 1, so if you give 1 to any of the children, it takes the remaining space. And lets say parent has 2 children and their weights as 0.6 and 0.4, the first child will occupy 60% of the parent height and the rest 40% by second child.
Comment: Thanks, this worked. I'll accept this as soon as the website lets me. Can you please explain how you use these attributes: android:layout_height="0dp"
android:layout_weight = "1"
Answer: Try using a relative layout for the topmost layout, and use alignParentBottom for your button bar layout.

Android - GUI layout


Find eccentricity of ellipse $ ax^2 + 2hxy + by^2 + 2gx + 2fy + c = 0$?

Question: Well I already got the answer to that and it is
$e =\sqrt{ \frac{2\sqrt{4h^2 +(a-b)^2}}{a+b + \sqrt{4h^2 +(a-b)^2}}}$
But I proved it for an ellipse, surprisingly it works for all other conics too!
I have posted my solution (https://math.stackexchange.com/a/4215136/955104) and I would like to know why it works for all the other conics.
Answer: Given: we need to find the eccentricity of ellipse $ \ ax^2 + 2hxy + by^2 + 2gx + 2fy + c = 0 $
[Because it is ellipse, $\ h^2 \le ab $, so consider $\ a,b \gt 0$. ]
Now we know that centre of ellipse is $  \left( \frac{hf-bg}{ab-h^2},\frac{hg-af}{ab-h^2} \right)=\left(\alpha, \beta\right)$ (Let's say).
Note that $(\alpha,\beta)$  is solution of the lines $ax+hy+g=0 ,\ hx+by+f=0$, which implies
$\boxed { a\alpha+h\beta+g=0 , h\alpha+b\beta+f=0 }\tag{1}$
Now let P be a point on ellipse at distance $r$  from centre then P is in the form$\left( \alpha +r\cos \theta , \beta +r\sin \theta\right)$
Before substituting P in ellipse equation let's find the value of
\begin{align}
E &=a(x_1+x_2)^2 + 2h(x_1+x_2)(y_1+y_2) + b(y_1+y_2)^2  \\ &\quad +2g(x_1+x_2) + 2f(y_1+y_2) + c \\
\implies E&= (ax_1^2 + 2hx_1y_1 + by_1^2 + 2gx_1 + 2fy_1 +c)
\\&\quad+ (ax_2^2 + 2hx_2y_2 + by_2^2 + 2gx_2 + 2fy_2) + 2ax_1x_2 \\&\quad +2h(x_1y_2+x_2y_1)+2by_1y_2 \tag{2}
\end{align}
Now using (2) let's put P in ellipse equation. We get
$$
 (a\alpha^2 + 2h\alpha \beta + b\beta^2 + 2g\alpha + 2f\beta + c) + r^2(a\cos^2\theta + 2h\cos\theta \sin \theta + b\sin^2 \theta) + 2gr\cos\theta + 2fr\sin \theta +2a \alpha r \cos\theta + 2hr(\alpha\sin\theta + \beta \cos \theta ) + 2b\beta r \sin\theta = 0 $$
Let  $-\Delta = (a\alpha^2 + 2h\alpha \beta + b\beta^2 + 2g\alpha + 2f\beta + c)$. Then
$$
-\Delta  + r^2(a\cos^2\theta + 2h\cos\theta \sin \theta + b\sin^2 \theta) + 2r\cos\theta( a\alpha+h\beta+g)+2r\sin\theta(h\alpha+b\beta+f) = 0 $$
From (1) we get
\begin{align}
&-\Delta  + r^2(a\cos^2\theta + 2h\cos\theta \sin \theta + b\sin^2 \theta) = 0 \\
\implies &r^2 = \frac{\Delta}{a\cos^2\theta + 2h\cos\theta \sin \theta + b\sin^2 \theta} \\
\implies &r^2 = \frac{2\Delta}{a(2\cos^2\theta) + 2h(2\cos\theta \sin \theta) + b(2\sin^2 \theta)} \\ &\quad  [\because 2\sin\theta\cos\theta=\sin2\theta , 2\cos^2\theta= 1+\cos2\theta, 2\sin^2\theta = 1 -cos2\theta  ] \\
\implies &r^2 = \frac{2\Delta}{a(1+cos2\theta) + 2h(\sin 2\theta) + b(1-\cos2 \theta)} \\
\implies &r^2 = \frac{2\Delta}{(a+b)+2h\sin2\theta+(a-b)\cos2\theta}
\end{align}
Now
\begin{align}
&2h\sin2\theta+(a-b)\cos2\theta \in[-\sqrt{4h^2+(a-b)^2},+\sqrt{4h^2+(a-b)^2}] \\
&\implies a+b+2h\sin2\theta+(a-b)\cos2\theta \\&\qquad \qquad \in\left[a+b-\sqrt{4h^2+(a-b)^2},a+b+\sqrt{4h^2+(a-b)^2}\right]
\end{align}
Note that since equation is ellipse,
$$\boxed { \ h^2 \lt ab \\
\implies 4h^2 +(a-b)^2 \lt (a-b)^2 +4ab = (a+b)^2 \\
\implies 4h^2 +(a-b)^2 \lt (a+b)^2 \\
\implies \sqrt{4h^2 +(a-b)^2} \lt a+b \ [\because a,b \gt 0] \\
\implies a+b - \sqrt{4h^2 +(a-b)^2} \gt 0 } \\
\implies \frac{2\Delta}{r^2} \in \left[a+b-\sqrt{4h^2+(a-b)^2},a+b+\sqrt{4h^2+(a-b)^2}\right] \\
\implies r^2 \in \left[\frac{2\Delta}{a+b+\sqrt{4h^2+(a-b)^2}},\frac{2\Delta}{a+b-\sqrt{4h^2-(a-b)^2}}\right] $$
Now
$$
r_{max}^2 = (\text{semi major axis})^2 = M^2 \  [\text{Let's say}] \\
r_{min}^2 = (\text{semi minor axis})^2 = m^2 \  [\text{Let's say}] $$
Now
\begin{align}
e^2 &= 1-\frac{m^2}{M^2} = 1 - \frac{a+b - \sqrt{4h^2 +(a-b)^2}}{a+b + \sqrt{4h^2 +(a-b)^2}} \\
\implies e^2 &= \frac{2\sqrt{4h^2 +(a-b)^2}}{a+b + \sqrt{4h^2 +(a-b)^2}} \\
\implies e &=\sqrt{ \frac{2\sqrt{4h^2 +(a-b)^2}}{a+b + \sqrt{4h^2 +(a-b)^2}}} \end{align}
$$\therefore \boxed{e =\sqrt{ \frac{2\sqrt{4h^2 +(a-b)^2}}{a+b + \sqrt{4h^2 +(a-b)^2}}}} $$
Comment: The time and efforts in LaTeX are appreciable, however, it would be better if you "deLaTeX" the text in between, making it less laggy and more readable.
Comment: @ultralegend5385 Sure give me sometime I'll do it
Comment: @ultralegend5385 Is it ok? And if you do think my solution is good enough could you upvote it (I am new to this platform)
Comment: (I took the liberty of cleaning up the formatting slightly. Feel free to undo my changes for any reason)
Comment: Thanks a lot ! @CalvinKhor


Clearing the cache changes the nice menu every time

Question: Maybe this isn't a cache problem, but I am using Drupal 6, I have cache disable and I am editing a custom nice menu CSS file.
I didn't see changes right away to my nice menus, so I cleared the cache in the performance page, and the menu would revert back to old changes. When I cleared the cache again, it randomly found new settings for Nice Menu.
I then installed Devel, and cleared the cache, but it didn't help. Clearing the browser cache didn't help either.
Do you have any idea?
Answer: If you have turned CSS file aggregation off, changes take effect immediately unless you have an external cache like Varnish of the css file. If you are not seeing changes after checking this, maybe your CSS file is not included or the rules implemented is overridden by other CSS rules.


Why ARIMA is prefered over any other time series analysis method

Question: I  am new to time series analysis, and I am self learner. I am using R language to learn how to do time series analysis. I started by studying the concepts and the theory behind such analysis, however I see a great concentration on the ARIMA method, whereas there is a very small attention for other methods.
Could somebody one tell me why ARIMA is preferred over the other methods.
Comment: Some days, when I am particularly cynical, I believe that ARIMA models are so popular because you can actually prove mathematical theorems about them (e.g., involving characteristic polynomials, unit roots etc.), in contrast to some other methods like exponential smoothing that only recently got a firm mathematical foundation via state spaces.
Comment: Hi: It's not so much that it's preferred. It's more that ARIMA models are often a reduced form equivalent of many any other time series models. So, for example, the koyck distributed lag ( ADL in econometrics ) say can be written as an AR(1) model with exogenous regressor. It's often the case in time series that one model can be written in various ways. Another example is exponential smoothing and double exponential smoothing. These can be written as an ARIMA(01,1) and ARIMA(0,2,2) respectively.
Comment: In actual practice, simpler models are more likely to be adopted, e.g. simple exponential smoothing of a deseasonalized series (although many exponential amoothing models can be expressed as ARIMA models).  The concept that ARIMA models are somehow best may be an indirect measure of the huge influence of Box -- and his students.
Comment: There is probably something related to ARIMA being a universal approximation that contributes to its popularity.
Comment: Stephan Kolassa, exponential smoothing is equivalent to an ARIMA(0,1,1). Wold's decomposition theorem provides a solid theoretical reason for ARIMA modelling if you expect stationarity in some sense (e.g. after differencing the series)
Answer: ARIMA models are not generally preferred over any other time series analysis method. There are certainly not preferred when the series demonstrate non-stationaries unable to be modelled using the ARIMA framework.
However, there is an important reason why the ARIMA might be preferred when the series are stationary (or gets so after differencing). And this reason is the Wold's decomposition theorem -  any covariance stationary process has a linear representation: a linear deterministic component ($V_t$) and a linear indeterministic components ($\varepsilon_t$)
Suppose that ${X_t}$ is a covariance stationary process with $\mathbb{E}[X_t] = 0$ and
covariance function, $\gamma(j) = \mathbb{E}[X_t X_{t−j}]$ ,  $ \forall j$. Then
$$X_t = \sum_{j=0}^{\infty} \psi_j \varepsilon_{t−j} + V_t$$
where

$\psi_0=1$, $\sum_{j=0}^{\infty} \psi_j^2<\infty$
$\varepsilon_{t−j} \sim WN(0, \sigma_{\varepsilon}^2)$
$\mathbb{E}[\varepsilon_t V_s] = 0, \forall s,t>0$
$\varepsilon_t = X_t  - \mathbb{E}[X_t|X_{t-1},X_{t-2},...]$

As you may see, the first part of the representation looks like an $MA(\infty)$ process with square summable moving average terms. The second part is the deterministic part of $X_t$ because $V_t$ is perfectly predictable based on
past observations on $X_t$. And we know that models of $MA(\infty)$ representations are in their most general form $ARMA(p,q)$ representations: as long as the roots of the autoregressive part of an ARMA process are less than unity in absolute value, the process has a  $MA(\infty)$ representation.
However, note, while an ARMA process generates an $MA(\infty)$ with square summable weights, it is not the only form that does this. A process that is square summable is not necessarily absolutely summable. $ARMA(p,q)$ models have
'short memory' relative to the entire class representations envisioned by the Wold representation. But Wold representation - despite covering more general cases- provides us with a strong argument of why modelling with ARMA is justifiable on stationary, short memory series.
Comment: Comments are not for extended discussion. Instead, use comments ***constructive* criticism** and requests for clarification.
Answer: ARIMA models account for a variety of possible problems which simpler models may have. For example, if you try an AR model, but there should be an MA component, this could make your estimates highly incorrect. Also the other way around where you model as MA but it should include AR.
But what if you don't need an ARIMA and an AR will suffice? In applied statistics, say economics, your plan to simply use an AR(p) model may be fantastic, and when you try an ARIMA you don't find any contribution of the -IMA - but there will always be people who say "Well I could come up with 5 scenarios where you should really have an ARIMA model instead of just AR," and so to appease the crowd you're forced to throw in everything they'll think of.
"Everything they'll think of" is another important point. In many disciplines, ARIMA is about as complex or outside-of-the-box as most people have even heard of. Though there are other models which may be outside the scope of an ARIMA model, ARIMA is the generic go-to, as well as the benchmark against which other time-series methods will be compared. And so, once again, you're forced to show an ARIMA version of the analysis.
Answer: I am not sure they are preferred. They are popular because Box et el were well respected and they did a good job of presenting their material at a time there was not a lot of alternatives. To me they require judgement ('an art rather than a science') and knowledge of the data that may not exist in a workplace environment. They also are time consuming and (some argue) they are hard to identify correctly with real world data, particularly when mixed AR and MA exist.
Exponential smoothing models such as Holt or Winters have proven about equally accurate from what I have read -they are certainly a lot easier and faster to use.
Comment: I am not a statistician so you should take my comments with a grain of sand. You might look up the M competitions that found damp trend, a form of ESM, among the better methods. This is one example of where ESM was better (but no general rule is suggested). https://otexts.com/fpp2/arima-ets.html Here is another that found each better at different times https://aip.scitation.org/doi/10.1063/1.4801282  This found one form of ESM better in one case. https://www.matec-conferences.org/articles/matecconf/pdf/2016/44/matecconf_ictte2016_07002.pdf None suggest one is better in all cases.
Comment: Thank you for your answer, could you please add  a refernce for Holt or Winters models to prove that they are equaly accurate. Thank you in advance.
Answer: According to Box and Jenkins, ARIMA is a linear non-stationary model. It is an imporvement over ARMA.
In my experience, ARIMA might be favored over other methods because of its flexibility.
You can achieve far better results if you decompose your signal into simpler components and use simple linear models to forecast each time series and then combine them into one forecast.
So, it is initially easier to work with and it can handle non-stationarity if there is homogeneous nonstationary behavior in the time series.
There are many scenarios where ARIMA model fails. e.g. if there is heteroskedasticity in your data, it cannot be modeled with ARIMA.
Comment: Perhaps a relevant quotation from the Box & Jenkins text would be helpful in providing context & justification for the claims made in the first sentence.


Lyndon Words, why isn't 00, 11 in the sequence.

Question: Im trying to understand the relationship between lyndon words and necklaces.  The sequence for lyndon words is: $$ ε, 0, 1, 01, 001, 011, 0001, 0011, 0111, 00001, 00011, 00101, 00111, 01011, 01111 $$
For Necklaces the following sequence includes 00, 01, and 11:

Why don't lyndon words contain 00 and 11?  I have read that

A Lyndon word is an aperiodic notation for representing a necklace.

but clearly the necklace of 00 and 11 is not being represented.  Also why is 0101 not included but 00101 is?
Answer: By definition, a Lyndon word is a word that is lexicographically smaller than every of its rotations (where $z$ is a rotation of $z'$ iff there exist words $u,v$ such that $z=uv$ and $z'=vu$.). If a word is a power (i.e., a concatenation of copies of a shorter word), then it cannot be Lyndon. Indeed, in this case there is a rotation that equals the original word, so that the original word is not strictly smaller than every of its rotations.
If you relax the condition in the definition by imposing that a word must be smaller or equal than every of its rotations, then you get the definition of a necklace. In fact, necklaces are just powers of Lyndon words (meaning that a necklace is a word of the form $u^n$, for a Lyndon word $u$ and an integer $n\geq 0$).
Answer: It's because both $00$ and $11$ are periodic, and are covered already by the inclusion of $0$ and $1$.


How to expose only one form in views?

Question: I have created a view with two exposed forms based on filter criteria and the sort criteria. I would like to display the sort criteria in the actual view and the filter criteria as a block.But when i save the view i get these two forms either as a block or as a view content.
Can any one help me to display the filter criteria as a block and the sort criteria as a actual view?
Answer: I would suggest that you clone the view and amend it to display only the filter criteria that you require.  You can then display the cloned view in a block and the original in a page, or wherever you require it to be.

How to expose only one form in views?


Calculating Bayesian posterior distribution for an exponential distribution

Question: I want to calculate the Bayesian posterior distribution of an exponential distribution where $\lambda$ is distributed according to gamma distribution. I know that I need to calculate $\frac{P(x|\lambda)P(\lambda)}{P(x)}$. I know $P(\lambda)$ because I know the gamma distribution function. I also know that $P(x|\lambda)$ = $\lambda \exp(-\lambda x)$. But I dont know what $P(x)$ is or what it means.
Am I on the right track? What does $P(x)$ mean in this context?
Answer: Typically, Bayesians talk about a "posterior" distribution in light of an update. There are two possible things you could be trying to do here, which are fairly closely related so I'll step through them both.
First is a hierarchical modeling problem: you know the distribution of $x$ given a parameter $\lambda$ ($P(x|\lambda) \sim$ exponential), and you have a distribution on that parameter ($P(\lambda) \sim$ gamma), but if you want the distribution on $x$ by itself ($P(x) \sim$ ?), you need to combine those two pieces of information.
This is done by integration; any value of $x$ could be achieved by any value of $\lambda$, and so $P(x)=\int_0^\infty P(x|\lambda)P(\lambda)d\lambda$. (Since the gamma and exponential distributions are closely related, this actually flows pretty smoothly.)
Second is the problem of inferring what the uncertain value $\lambda$ is, given we observe a particular value $x$ from the resulting exponential distribution. Here the role of $P(x)$ becomes clear--we are conditioning on our observation $x$, and dividing by $P(x)$ normalizes the probability distribution.
As pointed out in @ebb-earl-co's answer, you don't actually need to calculate $P(x)$ in this situation, if you're willing to integrate the distribution $P(x|\lambda)P(\lambda)$ in order to determine what normalizing constant you need to apply to make it a well-formed probability. The 'magic' of Bayes is that this normalizing constant is necessarily the probability of the observation that you're updating on.
Answer: $P(x)$ is the marginal density of $X$, which is called the marginal because you get it by marginalizing (i.e. integrating) out $\lambda$ from the joint density of $X$ and $\lambda$. I am going to rename $P(x)$ as $h(x)$ so that it doesn't get confused with the posterior. Then, I'll write the data model as $f(x|\lambda)$ and the prior as $\pi(\lambda)$. Therefore, your expression is
$$p(\lambda|x) = \frac{f(x|\lambda)\pi(\lambda)}{h(x)}$$
Now, the beauty of Bayes' Theorem is that you don't need to know $h(x)$ in order to calculate $P(\lambda|x)$! So, it suffices to know that the posterior is proportional to the product of the data model (a.k.a. likelihood) and the prior on $\lambda$.


NodeJS + Express + MongoDB using Mongoose Sequence not working

Question: a tryng to create a collection using auto increment number in the _id data, but stay "Sending request" and I not have callback in this call. I really dont know what I cant making work

"mongoose": "^7.5.3"
"mongoose-sequence": "^5.3.1"
"node": "v20.8.0"

domain.model.js
const mongoose = require("mongoose");
const AutoIncrement = require("mongoose-sequence")(mongoose);

const schema = mongoose.Schema(
  {
    _id: {
      type: Number,
    },

    domain: {
      type: String,
      required: true,
      trim: true,
    },
  }
);
schema.plugin(AutoIncrement, { inc_field: "_id" });
const domain = mongoose.model("domain", schema);

module.exports = domain;

my function
const isSetSearchDomain = async (dom) => {
  try {
    let promise = new Promise(async (resolve) => {
      const domainPromises = dom.map(async (domain) => {
        let existingDomain = await Domain.findOne({ domain: domain });

        if (!existingDomain) {
          const newDomain = await new Domain({
            domain: domain
          });

          await newDomain
            .save()
            .then((documento) => {
              console.log("Documento salvo com sucesso:", documento);
            })
            .catch((err) => {
              console.error(err);
            });

          await newDomain.setNext("_id", function (err, dom) {
            console.log(dom._id);
          });

          console.log(newDomain);

          return {
            _id: newDomain._id,
            domain: domain,
          };
        } else {
          return {
            _id: existingDomain._id,
            domain: domain,
          };
        }
      });

      const results = await Promise.all(domainPromises);
      resolve(results);
    });

    return promise.then((p) => p);
  } catch (error) {
    console.log(error);
    log.error(error);
    return false;
  }
};

When I put await in await newDomain.save() still loading request
It keeps loading an API request and doesn't return anything, I really don't know what the error would be exactly, I've tried everything to make a collection using incremental id
Answer: Remove _id from Schema as You don't need to define the id field in your schema because the plugin automatically sets it for you. The only thing you have to do is to call.
Comment: Also, you dont need await in
const newDomain = await new Domain({
            domain: domain
          });


Var(AZ)=A Var(Z) A^T?

Question: I am learning linear models, and I do not understand the following:
$\text{Var}(AZ)=A \text{Var}(Z) A^T$ where $A$ is a constant matrix.  I want to know the variance $\widehat{\beta}$ in a linear model: $y=A\beta + \epsilon$, and $\widehat{\beta}=(A^T A)^{-1}A^T y$.
To show $\widehat{\beta}=\sigma^2 (A^T A)^{-1}$, I need to know $\text{Var}(AZ)=A \text{Var}(Z) A^T$.
How do I show that?
Answer: One of the properties of variance is
\begin{equation}
Var(AZ) = A^{2} Var(Z)
\end{equation}
where A is a constant and Z is a random variable.
The matrix equivalent is the version you're working with, i.e.
\begin{equation}
Var(AZ) = A Var(Z) A^{T}
\end{equation}
Two links for you to check out are Variance#properties on Wikipedia and also these course notes from STA6707 the University of Florida.
Hopefully this clears up the problem for you.
Note: the question has been modified since the time I provided the above answer, so if you actually want a proof to show $\widehat{\beta}=\sigma^2 (A^T A)^{-1}$, please let me know and I will provide you with a proof and an explanation.
Comment: Thank you for the offer, but the proof for the hat of beta was clear to me.  Thank you for the answer of the matrix equivalent of the var(AZ), and that was very helpful.

Var(AZ)=A Var(Z) A^T?


boto3 KeyConditionExpression on both partition and sort key

Question: So i have the following schema:
domain (partition key)
time_stamp (sort key)
I am (attempting) to use boto to query dynamo. I want to return all records with a given domain, after a given time_stamp.
I have tried a couple of different approaches to no avail:
First is my ideal approach. I believe it to be much cleaner it also uses between which i would like to incorporate if possible.
resp = table.query(
            KeyConditionExpression=Key('domain').eq(domain) and Key('time_stamp').between(start,end),
            ProjectionExpression= 'time_stamp,event_type,country,tablet,mobile,desktop')

ERROR: An error occurred (ValidationException) when calling the Query operation:
Query condition missed key schema element: domain

Here is the second approach that I took. It appeared more often in docs and other stack questions that I found. Yet, I am still getting an error.
resp = table.query(
            ExpressionAttributeNames={
            '#nd': 'domain',
            '#nts': 'time_stamp'
            },
            ExpressionAttributeValues={
            ':vd': domain,
            ':vts': start,
            },
            KeyConditionExpression='(#nd = :vd) AND (#nts > :vts)',
            ProjectionExpression= 'time_stamp,event_type,country,tablet,mobile,desktop')

ERROR: An error occurred (ValidationException) when calling the Query operation:
One or more parameter values were invalid: Condition parameter type does not match schema type

I believe this error may be related to the data type of time_stamp being a string and not the Decimal() format that dynamo uses to represent numbers.
Comment: Did you figure this out? This is a top hit on google and looks like basically the same issue I'm seeing.
Answer: You have to use & not and.
resp = table.query(
            KeyConditionExpression=Key('domain').eq(domain) & Key('time_stamp').between(start,end),
            ProjectionExpression= 'time_stamp,event_type,country,tablet,mobile,desktop')

This is where the AWS docs say this, but it's kind of buried in there.


Scroll automatico para a direita

Question: Existe alguma maneira em jquery de quando clicar num botão a pagina ou uma div fazer um pequeno scroll automaticamente?
Comment: Arranjei outra solução  [http://balupton.github.io/jquery-scrollto/]
Answer: Resposta presenta no SO
Transcrição
scrollLeft é scrollRight. O que ele faz é uma rolagem horizontal.
Se você configurá-lo para 0 então ele ira totalmente para a esquerda.
Se você configurá-lo para > que 0 então ele ira para a direita.
Se você quer fazê-lo se movendo então tera que obter o tamanho dele e ir incrementando.
$(".leftArrow").click(function () {
  var leftPos = $('.innerWrapper').scrollLeft();
  $(".innerWrapper").animate({scrollLeft: leftPos - 200}, 800); // MOVE PARA ESQUERDA
});

$(".rightArrow").click(function () {
  var leftPos = $('.innerWrapper').scrollLeft();
  $(".innerWrapper").animate({scrollLeft: leftPos + 200}, 800); // MOVE PARA DIREITA
});

Answer:

$('#gdb1').click(function(){
    $("html, body").animate({ scrollTop: $(window).height()}, 600);
    return false;
 });

    <button id="gdb1" class="gdbutton fontwhitenshadow">Q</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veniam beatae quas esse explicabo modi odio nesciunt vero error obcaecati ea sequi alias quam facilis delectus odit aperiam repellat similique corrupti.

Aspernatur sit eveniet debitis voluptatibus optio dignissimos asperiores illum nisi eum minima quidem quis modi dolorem hic nobis qui deleniti veniam obcaecati est odio ea molestias vitae nesciunt deserunt maxime.

Accusamus voluptate tempora placeat explicabo sapiente quas ex perferendis reiciendis sed sit recusandae aut molestias libero itaque fugiat velit nihil minus enim vel illo id cum dignissimos. Vitae quod autem.

Amet est asperiores nulla ipsam quos provident voluptatibus dignissimos minima facilis similique necessitatibus repellendus excepturi accusamus dolore velit earum autem inventore vero enim deserunt sed id quo omnis officia obcaecati.

Quo dolorem eum sed aut maiores tempora incidunt soluta. Beatae iure vitae aspernatur porro dignissimos natus eos veritatis dolor quis adipisci. Provident illum veniam ratione in omnis ducimus beatae. Laudantium.

Veniam commodi totam possimus rem excepturi aut est. Voluptatibus corrupti consectetur cupiditate officiis corporis distinctio tempore maxime ducimus id aliquam eaque sint rem earum. Voluptatum dolorum quam repellendus maxime autem!

Mollitia ab alias impedit repellendus sed ut distinctio aliquam sunt aperiam minus perferendis eos. Natus minus adipisci unde maiores commodi debitis a. Atque non quia labore dolore at fuga quos!

Autem doloremque ipsa voluptatibus harum laboriosam mollitia inventore nesciunt suscipit voluptatum atque in corrupti itaque provident sunt ex voluptates veniam consequatur fugiat facere libero dignissimos officiis eius officia! Quasi exercitationem!

Sit ab voluptatibus error velit tenetur placeat totam omnis quam molestiae id nemo necessitatibus a repellat quaerat esse rerum assumenda accusamus numquam reprehenderit odit. Eos odio veniam necessitatibus laudantium mollitia!

Porro reprehenderit quia corporis reiciendis aperiam neque earum illo quidem quasi modi doloribus debitis. Reprehenderit officiis doloribus ab doloremque veritatis nam minima placeat illum iusto. Aliquam ipsa a hic ex.

Mollitia laboriosam accusamus quidem reprehenderit dolorum quae pariatur voluptatem magnam atque odio facilis suscipit vero eos vitae tempore corporis molestias quisquam nobis culpa ducimus sint sunt illo aliquam nesciunt ipsam.

Dolor aliquid iure debitis odio dignissimos id nesciunt dicta harum temporibus quibusdam sed eaque quae incidunt cumque at consectetur nemo adipisci officia optio nobis sunt autem dolorem culpa explicabo libero.

Ex doloribus veniam unde tenetur quisquam deleniti minus accusantium quod quia suscipit iusto modi dolore fuga eos optio autem provident quae in voluptatem temporibus quasi dolorum odio eius doloremque et!

Pariatur dolorem laudantium repellat ipsam asperiores minima optio eum. Minima reiciendis velit praesentium necessitatibus pariatur vero architecto inventore numquam veritatis obcaecati eos quos fugit eaque in distinctio repudiandae similique quia.

Illo nulla aliquam deleniti recusandae sunt facilis aperiam unde ipsa nemo necessitatibus eius laborum eligendi maxime obcaecati sapiente harum officia incidunt delectus a voluptatum. Soluta rem aperiam sapiente quis necessitatibus.

Reprehenderit fuga architecto consequatur accusantium dignissimos deserunt quia laudantium provident veniam earum rem culpa eos voluptate magni dolores autem dicta numquam blanditiis dolorem repellat officia repudiandae unde illum quam excepturi!

Tempora porro perspiciatis quod debitis facilis aspernatur sunt obcaecati fugiat dignissimos est alias nihil reiciendis hic doloribus expedita suscipit dicta? Corporis quo eveniet in obcaecati beatae ipsam. Dolores non obcaecati.

Incidunt nam quo quod aspernatur nemo molestias quisquam a laudantium officia animi cumque ea! Optio ipsam quaerat soluta eaque quae nam quod sapiente similique totam dolor praesentium fuga eveniet sed!

Iusto illo cum quo qui modi nobis exercitationem at similique nihil eius vel odio enim dicta praesentium deleniti incidunt esse provident magnam optio reprehenderit nemo culpa libero cupiditate molestias amet.

Libero dignissimos eos error nihil omnis eius quaerat dolore tempore quae quo similique harum debitis sapiente voluptates soluta ullam ab recusandae quia rem atque. Beatae non assumenda nihil tenetur deserunt!

Ao click do botão, você vai até o final da página.
Comment: "Scroll automatico para a direita" solicitado pelo AP
Answer: Vou colocar um exemplo de como poderia ser feito utilizando apenas javascript puro, já que as respostas dos demais já é feita com jquery:

document.addEventListener('DOMContentLoaded', function() {
  var button = document.getElementById('slide');
  button.onclick = function() {
    document.getElementById('container').scrollLeft += 20;
  };
}, false);
#container {
  border: 1px solid #ccc;
  height: 100px;
  overflow: scroll;
  width: 100px;
}
#content {
  background-color: #ccc;
  width: 250px;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

<button id="slide" type="button">Direita >></button>
Comment: Se eu não tirar o negativo apos sua edição favor me chame a atenção, pois quer disser que eu não vi.
Comment: "Scroll automatico para a direita" solicitado pelo AP
Comment: entendi, vou reeditar
Comment: Faça isso, e tirarei o negativo = D

Scroll automatico para a direita