Is it considered polytonality if the song is using two keys but not on top of each other

Question: I've run into a couple songs recently that use two keys at the time, but not in the way that would meet the definition of polytonality.
What they do is they establish one key as the primary key and then blend in a second key but don't change to that key. They'll use it for a riff or a couple measures, or the song will take the groupings of notes that make up both scales and use them as if they are one scale.
I did some research on this but the best thing I could find is polytonality, and based on what I've read and the videos I've watched this doesn't seem to meet the definition of polytonality.
So would this be considered polytonality? If not, what would this be considered?
One example is a song called "Coloring Book" by a Kpop group called Oh My Girl. The song is in E Major, it blends in E Minor in the chorus, but doesn't change to E Minor, it just kind of uses it.
Comment: Can you tell us which piece it is, or at least tell us the keys? C Major against C Minor would be a much different texture, for example, than C Major against C# Major.
Comment: What are the songs? It's possible that, when I listen to them, I classify them as polytonal anyway.
Comment: In this case, since the song mentioned blends tonalities from the parallel major / minor, it would be classified as **modal mixture**.
Answer: No, that isn't polytonality.  Key ambiguity perhaps.  But songs aren't required to stick to one key or mode.  These are just convenient ways of analysing styles of music that DO choose to do so, and a lot of Common Practice music did. That's why we call it 'Common Practice'.
But, yet again, Theory Describes, It Does Not Command.  Keys are a framework, not a set of rules.
Here's a much nicer piece that doesn't.
Answer: That is not polytonality. I couldn't bear listening to that song very closely, but it appears to just borrow some chords from the parallel minor key. I.e. the center of tonality is always the same.
By contrast, polytonality deliberately uses different tonal centers at the same time which would normally be considered incompatible.


Why is ANOVA in R showing a different result than ANOVA from another source?

Question: I am new to R and statistics both. I am trying to perform 2x2 ANOVA on an excel dataset where the 2 factors are Gender and Athletes and the dependent variable is Anger Expression. When I am calculating ANOVA on the dataset the Gender Sum Sq always shows 1 for some reason, however when I check on http://vassarstats.net it gives different summary which is actually the correct one. Could you please help me with this?
I have tried to change the Gender and Athletes values from M/F & S/NS to 1/2.
Also tried to switch the columns in the hope that something might change.
I checked on vassarstats.net by entering the same values which gives me the correct answer.
Dataset - https://drive.google.com/file/d/15cR4OR1hdso9Xm6fKc5jiFsSDzJK5pOn/view?usp=sharing
Code that I have executed
> Angry_moods_r$Gender <- as.factor(Angry_moods_r$Gender)
> Angry_moods_r$Athletes <- as.factor(Angry_moods_r$Athletes)
> anova1 <- aov(Anger_Expr ~ Gender+Athletes+Gender*Athletes, data = Angry_moods_r)
> summary(anova1)
                Df Sum Sq Mean Sq F value  Pr(>F)
Gender           1      1     1.4   0.009 0.92598
Athletes         1   1357  1357.2   8.709 0.00424 **
Gender:Athletes  1      5     5.2   0.034 0.85505
Residuals       74  11532   155.8

Correct answer
                Df   Sum Sq Mean Sq F value  Pr(>F)
Gender           1    20.87   20.87   0.13  0.7195
Athletes         1  1286.93 1286.93   8.26  0.0053 **
Gender:Athletes  1     5.24    5.24   0.03  0.863
Residuals       74 11532.19  155.84
Total           77    12896

Comment: I have no idea how you derived the "correct answer" and thus I can't reproduce it, but I get a somewhat similar result if I calculate a Type II ANOVA using `library(car); Anova(anova1, type = 2)`.
Comment: Thanks for providing your data and showing the output that gave rise to your question.
Comment: One note: The SS in the first output are being rounded to integers. That doesn't  answer your question (I think @Roland may be on the path to doing that) but it's worth noting.
Comment: This shouldn't be tagged as "mathematical-statistics".
Answer:
In R you can obtain the result like this:
# the data transformed to +/- values
#      this will give a different behaviour for dropping a
#      fixed effect term while keeping the interaction term
a <- (0.5-(data$Athletes == 'S'))
g <- (0.5-(data$Gender == 'M'))
y <- data$Anger_Expr

# linear model
m <- lm(y~a*g)

# the sum of squares by using type III sums
> drop1(m,.~.)
Single term deletions

Model:
y ~ a * g
       Df Sum of Sq   RSS    AIC
<none>              11532 397.70
a       1   1286.93 12819 403.95
g       1     20.87 11553 395.84
a:g     1      5.24 11537 395.74

The reason for these differences is that the analysis of variance can be performed in different ways.

You are comparing models with and without the factor, but this is ambiguous (see the different type I/II/III sums).
In addition the interaction term can be defined in various ways and this influences the difference in the sum of squared residuals when dropping a fixed effect term. This explains the difference between the answer from BruceET and the comment from Roland.
Answer: This is an unbalanced design. That is, you do not have the same number of replicates in each of the four cells.
In Minitab, the 'Balanced ANOVA' procedure (correctly) shows an error because of the imbalance.
Below is output from the general linear model procedure in Minitab 17, which handles
unbalanced designs.
Analysis of Variance

Source             DF   Adj SS   Adj MS  F-Value  P-Value
  Athletes          1   1286.9  1286.93     8.26    0.005
  Gender            1     20.9    20.87     0.13    0.715
  Athletes*Gender   1      5.2     5.24     0.03    0.855
Error              74  11532.2   155.84
Total              77  12896.0

My guess is that the R procedure you are using is not appropriate for unbalanced designs.
Perhaps see this link about two-factor ANOVA in R --at the end, where unbalanced designs are
discussed.

Notes: (1) If you just look at Mood scores and Athlete types (*53 'NS' and 25 'S'), you can do a two-sample t test. Results from a Welch (separate variances)
test are as follows:
T-Test of difference = 0 (vs ≠):
T-Value = 3.21  P-Value = 0.002  DF = 57

The corresponding test for Gender (48 'F' and 30 'M') does not show a significant
difference.
(2) You can see the imbalance because there are unequal sample sizes in the two t tests. If this were a balanced design, the rows of the ANOVA table (other than Total) would
correspond to orthogonal subspaces of a 77-dimensional vector space and (assuming normality) their
SS's would be independent statistics. The Adjustments in SS's reflect compromises
based on non-orthogonal projections.
(3) I did not check for normality or equal variances because the main issue of your Question is
to explain differences in output between two software programs, But you should
check ANOVA assumptions before interpreting results.


Decision Tree Categorical and Continuous Variable

Question: I'm new to data science and currently trying to learn and understand decision tree algorithm. I have a doubt, how the algoritham works when we have some continuous variables in a classification problem and categorical variables in regression problems. Usually algo works on the basis of gini index in classificaton problems and variance reduction technique in regression problem.
But when it comes to dealing with continuous variable in a classification problem, how the algo consider continuous variable, in the selection of best split (with highest gini index) done. -- vice versa for regression problem
Thanks in advance :)
Answer: It works very similarly. The whole idea is to find a value (in continuous case) or a category (in categorical case) to split your dataset.
If it's continuous, it is intuitive that you have subset A with value <= some threshold and subset B with value > that threshold.
If it's categorical, to make things simpler, say the variable has 2 categories. Then subset A will be a subset of original dataset with this variable equals category 1 and subset B will be the subset with this variable equals category 2.
If there are more than 2 categories for that variable, it's likely that 1 vs rest strategy is used. For example, if variable has 3 categories: [red, blue, green], then the splitting will be red vs non-red, and split the dataset into two subsets.
Then from there, the gini impurity or information gain scores are calculated.


How to use same filegroup definition in different subprojects

Question: I need to declare specific resources for some of sub-projects and I'm doing it following way
filegroup(
    name = "some_resources",
    visibility = ["//:app"],
    srcs = glob([
        "src/my/resources/**/*.resources",
    ]),
)

In any subproject however the path where one can find resources is the same. My question would be - what is the most bazelian (bazelish?) way to minimize code duplication in this particular case?
Basically I want to have something like
expose_some_resources() in relevant subprojects.
and then make this resources visible for every app.
Answer: You can put the filegroup into a macro in a .bzl file, and load and run that macro in the relevant subprojects.
so something like:
workspace/resources.bzl:
def expose_some_resources():
  native.filegroup(
    name = "some_resources",
    visibility = ["//:app"],
    srcs = native.glob([
        "src/my/resources/**/*.resources",
    ]),
  )

workspace/subproject/BUILD:
load("//:resources.bzl", "expose_some_resources")
expose_some_resources()

You might also consider adding some error checking to the macro, like checking that the macro is called only once per package using native.existing_rule, or checking that the glob returns 1 or more files.
Comment: In macros it should be `native.filegroup`, plain `filegroup` only works in build files. I've edited my answer to include the native part, sorry for the confusion.
Comment: are you 100% sure? The thing is that putting it into function is the first thing I've tried before asking the question - I'm getting 'name 'filegroup' is not defined'
with this definition - even if I'm not using it anywhere (bazel version: Build label: 0.14.0-homebrew)
Comment: I've reexamined everything and quite positive this does not work - I've also checked with 0.15.0-homebrew


How do I find the shaded area?

Question: This is how it looks like:

It is given that the area of the shaded region is $35 cm^2$.
All of my attempts so far ended up in a two-variable equation in terms of $r_1$ and $r_2$ (the radii of the larger circle and smaller circle respectively).
So, how do I find the area enclosed between the two circles, that is, the area of the larger circle minus the area of the smaller circle?
Comment: Then the hint becomes $\frac12(r_1^2-r_2^2) = 35 \implies \pi(r_1^2-r_2^2) = ?$ which is essentially what Manika's answer does.
Comment: No, I mean the area between the smaller circle and larger circle, excluding all other shapes.
Answer: Say $R_s$ is the radius of small circle and $R_b$ is the radius of big one, then

What you need to find is $S = \pi*(R_{b}^2 - R_{s}^2)$
What you already know is $0.5R_b^2 - 0.5R_s^2 = 0.5(R_b^2 - R_s^2) = 35$ (subtracting the areas of triangles)

From (2) you just find, that $R_b^2 - R_s^2 = 70$ and then substituting it into (1) you get $70\pi$
Comment: Never thought it is that simple, thanks a lot dude :)

How do I find the shaded area?


Regular Expression is not working for SSN

Question: SSN i have added a bootstrap validation but is not working
SSN: {
     validators: {
        notEmpty: {
                  message: 'Social Security number is required and cannot be empty'
                },
         regexp: {
                     // regexp: /^\d{9}$/,
                        regexp: /^\d{3}-\d{2}-\d{4}$/,
                       message: 'Social Security Number must be 9 digits'
                                }

                            }
                        },

Comment: Please get into a habit of NEVER saying _It is not working_.  Elaborate on what that means. What are you observing and what are you expecting to observe?
Comment: Write that in the question itself. Post *actual* code and explain what's wrong. As it is, it's impossible to answer why you have any kind of problem with C# when you post some unrelated strings
Comment: What isn't working? What is the format you want to match, what did you try, what did you expect and what did you get? The question is tagged `C#` and yet you posted a snippet that has nothing to do with C#
Comment: I want Social Security Number should display in XXXXXXXXX (i.e., 123-45-6789)
Answer: Try this pattern: ^\d{3}-\d{2}-\d{4}$
\d is a digit, {X} is repeat the previous element X times.
Adding ^ at the beginning and $ at the end will cause the regex to only match if the entire string is a SSN. Without those anchors strings like abc123-45-6789xyz would also match.
Comment: Well it's tested as working for me.  Not sure why a downvote for that.  Maybe it's something else in your implementation.  Explain your issue in more detail.


Proof of Bound for Growth of Divergent Trajectory in $3x+1$ Problem

Question: In this paper, Lagarias makes the following claim in section 2.7 (Do divergent trajectories exist?).
Context
$$T(x) = \left\{ \begin{array}{rl} \dfrac{3x + 1}{2}, & 2 \nmid x \\ \dfrac{x}{2}, & 2 \mid x \end{array} \right.$$
$$\begin{align*} \tag{2.30} \lim_{k \to \infty} |T^{(k)}(n_0)| = \infty \end{align*}$$
Claim
If a divergent trajectory $\{T^{(k)}(n_0) : 0 \leq k < \infty\}$ exists, it cannot be equidistributed $\pmod{2}$. Indeed if one defines
$N^*(k) = |\{j : j \leq k \mathrm{\ and\ } T^{(j)}(n_0) \equiv 1 \pmod{2}\}|$,
then it can be proved that the condition (2.30) implies that
$$\begin{align*} \tag{2.31} \liminf_{k \to \infty} \dfrac{N^*(k)}{k} \geq (\log_2 3)^{-1} \approx .63097 \end{align*}$$
Question
How can this statement be proved?
Difficulty
It seems like the author may be ignoring the $+1$ term under the assumption that the factors will dominate. (I've seen this assumption made often for heuristic arguments for the truth of the Collatz conjecture.) I don't see how such an assumption can be justified.
Given any length $n$ sequence of $n - k$ zeros and $k$ ones, we can find an $x \in \mathbb{N}$ such that
$$T^n(x) = \dfrac{3^k x + m}{2^n}$$
where
$$3^k - 2^k \leq m \leq 2^{n-k}(3^k - 2^k)$$
Now, suppose, for example, $n = 2k$. Then, we have the bound
$$T^n(x) \leq \dfrac{3^k x + 2^{n-k}(3^k - 2^k)}{2^n} = \left(\dfrac{3}{4}\right)^k x + \left(\dfrac{3}{2}\right)^k - 1$$
and the exponential "$+1$" term dominates for large $n$. Now, of course, $m$ won't always be as large as possible, but even if we look at "random" $m$, that only introduces a constant factor in front of the exponential.
Additional Questions
Is the proof of this statement difficult? Is that why the author doesn't include it? Is there a paper containing a proof?
Comment: I contacted the author, and he sent me an 11 page handwritten proof sketch. I tried to make it better (shorter, so less typing) to post, but I accidentally had an inequality backwards in my head (sigh). The proof is technical (many epsilons) and long, which is why it was cut from the paper by the editor. The trick is to use a result from lattice theory to find a spot where you can bound the "+1" term. Then, you can use the divergence of the trajectory to find a large enough value such that it actually gets smaller than the initial value, contradicting a certain choice of divergent elements.
Comment: @rukhin, $T^n(x)$ is maximized by the pattern $00\ldots011\ldots1$, with $k$ zeros followed by $k$ ones. If $\sigma(x) = (3x+1)/2$ and $\tau(x) = x/2$, then this corresponds to the situation when $T^n(x) = \sigma^k(\tau^k(x)) = (3^k x + 2^{k}(3^k - 2^k))/2^{2k} = 3^k/2^{2k}x + 3^k/2^k - 2^k/2^k = (3/4)^k x + (3/2)^k - 1$. Did that help?
Comment: It is unhelpful in working out what part you don't understand, that you have conflated Lagarias' $k$ which counts the same thing as your $n$, then reused $k$ for his $N^*(k)$
Comment: With $n=2k$, you will always have $T^n(x)\leq x$ whatever large $k$ you choose. And you will always have $\left(\dfrac{3}{4}\right)^k x \geq \left(\dfrac{3}{2}\right)^k$
Comment: @Collag3n, can you prove that $T^{(n)}(x) \leq x$ for all $x, k \in \mathbb{N}$ with $n = 2k$?
Comment: Of course I can prove what I said above for your "k zeroes, k ones" trajectory. But it is pretty obvious.
Comment: @Collag3n
$$T^n(x) = \dfrac{3^kx+m}{2^n}$$
where the bounds
$$3^k-2^k\leq m\leq 2^{n-k}(3^k-2^k)$$
are sharp, meaning there are always integers that attain those values. What you are claiming is that for every single one of the
$$\binom{n}{k}$$
different cosets of integers $x+r2^n$ that satisfy $n=2k$, for every single $k$, absolutely none of them satisfy
$$m>(2^n-3^k)x$$
which is making a statement relating the size of $x$ to the parity of its trajectory. This statement is _not at all_ obvious, and a proof would probably be very informative and likely solve the whole conjecture.
Comment: I talked about the maximized v-shape one. not about solving the whole conjecture
Comment: Why does the $\left(\frac{3}{2}\right)^k$ term (where $k=k(n)$ is presumably increasing in $n$) give you difficulty as an upper bound? Is that the "+1 term" you are referring to?
Comment: @rukhin, yes, that is the "+1" term in that example. This upper bound is sharp and shows that the term can increase exponentially. This example just demonstrates that care needs to be taken to control the value of this term in a proof (i.e., you can't just say it's obvious because it isn't).
Answer: I contacted the author, and he was kind enough to write up a proof for me. I have attempted to simplify his proof for presentation here. I also use some notation without explanation to reduce clutter; the meanings should be clear. The trick is to use an apparently well known result from lattice theory.
Proposition 1 (Lattice Theory rotation trick)
If $b_1, b_2, \ldots, b_\ell$ are real numbers such that
\begin{align*}
   b_1 + b_2 + \cdots + b_\ell = r \ell
  \end{align*}
($\ell \geq 2$) then the lattice path
\begin{align*}
   (0, 0), (1, b_1), (2, b_1 + b_2), \ldots, (\ell, b_1 + b_2 + \cdots + b_\ell) = (\ell, r \ell)
  \end{align*}
has a cyclic forward shift by some $k$ with $0 \leq k \leq \ell - 1$
\begin{align*}
   (0, 0), (1, b_{k+1}), (2, b_{k+1} + b_{k+2}), \ldots, (\ell, b_{k+1} + b_{k+2} + \cdots + b_\ell + b_1 + b_2 + \cdots + b_k) = (\ell, r \ell)
  \end{align*}
so that
\begin{align*}
   b_{\overline{k+1}} + b_{\overline{k+2}} + \cdots + b_{\overline{k+j}} \leq jr
  \end{align*}
for all $1 \leq j \leq \ell$, where $\overline{k+i} \equiv k + i \pmod{\ell}$ and $1 \leq \overline{k+i} \leq \ell$.
Proof
Let $k$ be the smallest index such that the point $(k, b_1 + b_2 + \cdots + b_k)$ is not above the line $y = rx$ and the distance between this point and the line is maximum. Notice that $k \leq \ell - 1$ by the extreme value theorem.
Corollary 2
If $n_1 < n_2 < \ldots < n_k$ and $r = n_k/k$, then there is some $\hat{k}$ with $1 \leq \hat{k} \leq k - 1$ such that
\begin{align*}
    n_{k-\hat{k}+1} - n_j \geq (k - \hat{k} + 1 - j) r
   \end{align*}
for all $1 \leq j \leq k - \hat{k}$.
Proof
Apply Propositon 1 to the sequence
\begin{align*}
   b_1 = n_k - n_{k-1}, b_2 = n_{k-1} - n_{k-2}, \ldots, b_{k-1} = n_2 - n_1, b_k = n_1
  \end{align*}
Lemma 3 (bound on additive term)
For odd $x \in \mathbb{N}$, suppose that
\begin{align*}
   T^n(x) = \dfrac{3^k}{2^n}x + e(x, k)\;\;\;\;\; e(x, k) = \sum_{i=0}^{k-1} \dfrac{3^i}{2^{n_k - n_{k-1-i}}}
  \end{align*}
where $r = n/k \geq \log_2 3$. Then there is a $1 \leq \hat{k} < k$ such that
\begin{align*}
   e(x,k-\hat{k}) \leq \dfrac{1}{2^r - 3}
  \end{align*}
Proof
Let $r = n/k = (\log_2 3)(1 + \delta)$, where $\delta > 0$, and apply Corollary 2 to $0 = n_0 < n_1 < \cdots < n_{k-1}$ to find an index $\hat{k}$ such that $1 \leq \hat{k} < k$ and
\begin{align*}
   n_{k-\hat{k}} - n_{j-1} \geq (k - \hat{k} - j + 1)r
  \end{align*}
for all $1 \leq j \leq k - \hat{k}$. Then,
\begin{align*}
   2^{n_{k-\hat{k}} - n_{i-1}} \geq 2^{(k-\hat{k}-i+1)r} = 3^{(k-\hat{k}-i+1)(1+\delta)}
  \end{align*}
and
\begin{align*}
   e(x, k - \hat{k}) & = \sum_{i=1}^{k-\hat{k}} \dfrac{3^{k-\hat{k}-i}}{2^{n_{k-\hat{k}}-n_{i-1}}} \\
    & \leq \sum_{i=1}^{k-\hat{k}} \dfrac{3^{k-\hat{k}-i}}{3^{(k-\hat{k}-i+1)(1 + \delta)}} \\
    & = \dfrac{1}{3} \sum_{i=1}^{k-\hat{k}} \dfrac{1}{3^{(k-\hat{k}-i+1)\delta}} \\
    & \leq \dfrac{1}{3^{1+\delta} - 3} \\
    & = \dfrac{1}{2^r - 3}
  \end{align*}
Remark
The key fact about Lemma 3 is that the bound is independent of both $x$ and $e(x,k)$, depending only on the value of $r = n/k$. It achieves this by making the choice $\hat{k}$ that depends on $x$ and showing that such a choice must exist for every $x$ with $r \geq \log_2 3$. This is the ``trick."
Theorem 4
If $x, T(x), T^2(x), \ldots$ is a divergent trajectory with
\begin{align*}
   k(x, n) = |\{T^j(x) \equiv 1 \pmod{2} : 0 \leq j < n\}|
  \end{align*}
then
\begin{align*}
   \liminf_{n \to \infty} \dfrac{k(x, n)}{n} \geq \log_3 2
  \end{align*}
Proof
Since $x$ has a divergent trajectory, there must be a sequence $y_0 < y_1 < y_2 < \cdots$ such that $y_j = T^{n_j}(x)$, for some natural numbers $n_0 < n_1 < n_2 < \cdots$, and such that $T^n(y_j) > y_j$ for all $n \in \mathbb{N}$. For each (fixed) $y_j$, we have
\begin{align*}
   \liminf_{n \to \infty} \dfrac{k(x, n)}{n} = \liminf_{n \to \infty} \dfrac{k(x, n) - k(x, n_j)}{n - n_j} = \liminf_{n \to \infty} \dfrac{k(y_j, n)}{n}
  \end{align*}
Now, suppose that
\begin{align*}
   \liminf_{n \to \infty} \dfrac{k(x, n)}{n} < \log_3 2
  \end{align*}
Then, there is some constant $c$ such that
\begin{align*}
   \dfrac{k(x, n)}{n} \leq \dfrac{1}{c} < \log_3 2
  \end{align*}
infinitely often, and, in particular, for each $y_j$, there is always an $n$ such that
\begin{align*}
   \dfrac{k(y_j, n)}{n} \leq \dfrac{1}{c} < \log_3 2
  \end{align*}
Let $d = c - \log_2 3 > 0$. Then, $n \geq k(y_j, n)(\log_2 3 + d)$ implies
\begin{align*}
   2^n \geq 3^{k(y_j, n)} 2^{kd} \geq 3^{k(y_j, n)} 2^d \iff \dfrac{3^{k(y_j, n)}}{2^n} \leq 2^{-d}
  \end{align*}
Let $r = n/k(y_j, n) \geq c$. Applying Lemma 3, we have an $n^*$ such that
\begin{align*}
   T^{n^*}(y_j) \leq 2^{-d} y_j + \dfrac{1}{2^r - 3} \leq 2^{-d} y_j + \dfrac{1}{2^c - 3}
  \end{align*}
where the values $c$ and $d$ are constant across all the $y_j$ (i.e., for each $y_j$, there is an $n^*$ such that the bound holds). Since $2^{-d} < 1$ and $y_j$ grow unbounded, there is a
\begin{align*}
   y_j > \dfrac{1}{(2^c - 3)(1 - 2^{-d})}
  \end{align*}
at which point
\begin{align*}
   T^{n^*}(y_j) < y_j
  \end{align*}
contradicting our construction of the $y_j$ and proving
\begin{align*}
   \liminf_{n \to \infty} \dfrac{k(x,n)}{n} \geq \log_3 2
  \end{align*}
Remark
If you find any errors in the above, it is almost certainly from my attempt to simplify the proof I was given and not from the author.
Comment: @user334732, yes, but first he has to place a bound on the "+1" term (Lemma 3). The trick makes this bound depend only on the ratio of the exponents. This is the key step that allows one to move to larger and larger numbers.
Comment: I'm surprised such heavyweight machinery is necessary to formalise this. Scanning it, it looks like he's essentially done what I tried to communicate in a nutshell - namely that you can consider the $1$ to vanish over successive subsequences of some longer sequence, by taking a sequence of subsequences that diverges.
Answer: The "+1" term is just included in the bound,
$$3^{N^*(k)}\leq\frac{T^{(k)}(n_0)}{n_0}2^{k}$$
see construction here: A possible way to prove non-cyclicity of eventual counterexamples of the Collatz conjecture?
If you start with this:
$$T^{(k)}(n_0) = \frac{3^{N^*(k)}}{2^{m_1+m_2+...+m_i}}\cdot n_0+\frac{3^{N^*(k)-1}}{2^{m_1+m_2+...+m_i}}+\frac{3^{N^*(k)-2}}{2^{m_1+m_2+...+m_{i-1}}}+...+\frac{3^0}{2^{m_1}}$$
see construction here: $(n_0) \to (n_i)$ and $(n_0+k\cdot2^j)\to(n_i+k\cdot3^i)$, same Glide?
This can be simplified to
$$T^{(k)}(n_0) = \frac{3^{N^*(k)}}{2^k}\cdot n_0+\alpha N^*(k)$$
where $\alpha < \frac{1}{3}$ as shown in this paper: https://arxiv.org/abs/1710.01525v1
$$2^k = 3^{N^*(k)}\frac{n_0}{T^{(k)}(n_0)-\alpha N^*(k)}$$
$$k = N^*(k)\log_23+\log_2(\frac{n_0}{T^{(k)}(n_0)-\alpha N^*(k)})$$
Now as long as $T^{(k)}(n_0)-\alpha N^*(k)>=n_0$
$$k \leq N^*(k)\log_2(3)$$
$$\frac{N^*(k)}{k} \geq \frac{1}{\log_23}$$
I didn't check Theorem F, but i guess this is linked to his remark "cannot go too slowly"
Comment: @Collag3n, I put a bounty on this question with my own reputation. It's looking like a solution to this problem is just as hard as the conjecture itself. If I don't select an answer, then half the bounty will automatically go to the highest upvoted question with at least two upvotes. It's not personal; I just don't want my bounty to go to a completely useless and wrong answer, especially when that person is so adamant that they are right about something so obviously wrong.
Comment: This answer is wrong. Please do not upvote.
$$3^{N*(k)}\leq \dfrac{T^{(k)}(n_0)}{n_0}2^k$$
and
$$T^{(k)}(n_0)-\alpha N^*(k)\geq n_0\implies\dfrac{N^*(k)}{k}\geq\dfrac{1}{\log_2 3}$$
are trivial: just plug in definition of $T^{(k)}(n_0)$ and simplify.
$$\alpha < \dfrac{1}{3}$$
was NOT shown in that paper. This answer did not prove anything, nor did it contribute in any way toward finding a proof.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/96414/discussion-on-answer-by-collag3n-proof-of-bound-for-growth-of-divergent-trajecto).
Comment: You gonna tell everyone how to vote? what is your problem ? There is a contribution towards finding a proof, and even though, this is not a prerequisite for anyone to find something usefull in what is written.
Comment: what a beautifull mind
Comment: @Collag3n, bounty on this site represents control of the content. People who hold obviously false convictions about mathematics should not be in control. Like I said, it's not personal, and I was obviously very willing to help you understand, as I spent a good deal of my time explaining every aspect in the comments that were removed. But this answer is not helpful, and it should not award you more control of the content on this site. If you truly believe that your answer contributed in any way to this question, then I implore you to edit it and elaborate how because I certainly don't see it.
Comment: Obviously "control" is what is driving you.
Answer: Lagarias likely hasn't included it because it's trivial.
Let the down transform $t_d$ be an instance of $(3x+1)/4$ and the up transform $t_u$ be an instance of $(3x+1)/2$.
Then take as a representative of a sequence equidistributed mod $2$ the following: $t_d,t_d,t_d,\ldots$
Mod 2, this goes $1,0,1,0,1\ldots$
Now supposing the ones vanished, i.e. $T(x)=3x/2$ or $x/2^r$, then $T^{(2k)}(x)=(3/4)^kx$ which is clearly descending so this equidistributed sequence falls.
With a little work on what ratio of $t_l$ to $t_d$ are required to make a sequence constant, Lagarias' inequality instantly follows from his earlier assumption that the sequence diverges and is therefore greater than constant:
$\begin{align*} \tag{2.31} \liminf_{k \to \infty} \dfrac{N^*(k)}{k} \geq (\log_2 3)^{-1} \approx .63097 \end{align*}$
Now, on the vanishing of the $1$ part of $3x+1$:
Since the sequence is assumed to diverge, for every subsequence $S_{x_0}$ of length $n_0+1$ and satistying $x_n>x_0$ we can identify a higher subsequence $S_{x_{n_0+1}}$ of length $n_1$ which also satisfies $x_{n_0+n_1+1}>x_{n_0+1}$.
Then by induction over the $p$ in $n_p$, we see that:
$\lim_{p\to\infty}T^{(k)}(x_{n_p})/x_{n_p}=3^r/2^q$ where $r$ counts $3x+1$ and $q$ counts $/2$.

It then follows from the commutativity of multiplication, that as $x\to\infty$ the order of $t_l,t_d$ in the sequence ceases to matter and the result above for $1,0,1,0,\ldots\pmod2$ holds for all equidistributed sequences.

I haven't accommodated for e.g. divisions by $8$ or greater but this is throguh lack of time, care and skill rather than these being difficult to accommodate.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/96415/discussion-on-answer-by-user334732-proof-of-bound-for-growth-of-divergent-trajec).


JS ou Jquery Diminuir o tamanho da imagem e não apenas redimensionar

Question: Existe alguma forma de diminuir o tamanho da foto antes do upload?
Nota: Não é apenas redimensionar, pois alguns teste que eu fiz so redimensionava e não diminuía o tamanho da foto.
Gostaria de verificar se o upload é do tipo imagem e Diminuir o tamanho, por exemplo: de 5mb para 1 ou 2Mb, mesmo que para isso a imagem redimensione.
Jquery do Upload:
$(document).ready(function () {

    var files;

    // Add events
    $('input[name=fileUploader]').on('change', prepareUpload);

    // Grab the files and set them to our variable
    function prepareUpload(event) {
        files = event.target.files;
        console.log("aqui",files);
    }

    $('#Salvar').click(function () {
        if (validaDados()) {

             var erro = "";

            var formID = document.getElementById("formulario");

            // files = this.files; // SELECIONA OS ARQUIVOS
            var qtde = files.length; // CONTA QUANTOS TEM
            var tamanho = 0;

            if (qtde > 5) { // VERIFICA SE É MAIOR DO QUE 5
                alert("Não é permitido enviar mais do que 5 arquivos.");
                return false;
            } else {
                for (i = 0; i < qtde; i++) {
                    tamanho += files[i].size;
                }

                if (tamanho > 10000000) {
                    alert("Arquivo acima de uma mega;")
                    return false;
                } else {
                    // SE NÃO FOR MAIS DO QUE 5 ELE CONTINUA.
                    if ($("#destinatario").val() == "") {
                        $("#destinatario").css({ "border-color": "red", "padding": "1px" });
                        $("#errodestinatario").html("E-mail obrigatório!");
                        return false;
                    } else {

                        if (validaEmail($("#destinatario").val())) {
                            $("#destinatario").css({ "border-color": "blue", "padding": "1px" });
                            $("#errodestinatario").html("");
                            $("#formulario").submit();
                        } else {
                            $("#destinatario").css({ "border-color": "red", "padding": "1px" });
                            $("#errodestinatario").html("E-mail Inválido!");
                            return false;
                        }

                    }

                }

            }
        }

    });
    });

HTML:
 <form class="form-horizontal" id="formulario" name="formulario" action="~/Gerenciamento/EnvioEmail/EnviaEmail" method="post" enctype="multipart/form-data">

            Destinatario

                <input type="text" class="form-control" id="destinatario" name="destinatario" />

            Assunto:

                <input type="text" class="form-control" id="assunto" name="assunto" />

            Mensagem

                <textarea class="form-control" id="mensagem" name="mensagem"></textarea>

            Anexo

                <input class="form-control" id="fileUploader" name="fileUploader" type="file" multiple />

        <button type="button" class="btn btn-primary" id="Salvar">Enviar</button>

    </form>

Comment: Do lado server é bem mais simples fazer, em várias linguagens. Do lado client, você pode usar o `canvas` para isso. Veja nessa pergunta do SO em inglês como pode fazer isso: [resizing-an-image-in-an-html5-canvas](https://stackoverflow.com/questions/2303690/resizing-an-image-in-an-html5-canvas)
Answer: Você pode usar a biblioteca compress.js. Ela utiliza a API do canvas para compactação de imagem do lado do cliente.

const compress = new Compress()
const preview = document.getElementById('preview')
const output = document.getElementById('output')

const upload = document.getElementById('upload')

upload.addEventListener('change', (evt) => {
  const files = [...evt.target.files]
  compress.compress(files, {
    size: 4, // the max size in MB, defaults to 2MB
    quality: 0.75, // the quality of the image, max is 1,
    maxWidth: 1920, // the max width of the output image, defaults to 1920px
    maxHeight: 1920, // the max height of the output image, defaults to 1920px
    resize: true // defaults to true, set false if you do not want to resize the image width and height
  }).then((images) => {

    const img = images[0]
    // returns an array of compressed images
    preview.src = `${img.prefix}${img.data}`

    const {
      endSizeInMb,
      initialSizeInMb,
      iterations,
      sizeReducedInPercent,
      elapsedTimeInSeconds,
      alt
    } = img

    output.innerHTML = `Start Size: ${initialSizeInMb} MB
End Size: ${endSizeInMb} MB
Compression Cycles: ${iterations}
Size Reduced: ${sizeReducedInPercent} %
File Name: ${alt}`
  })
}, false)

  <input type="file" name="" id="upload" accept="image/*">

Comment: Implementei sem complicação em uma aplicação já em produção, obrigado!
Comment: O upload implementa para ser com base64?


What's wrong with this sequential reasoning for a formula for a_n?

Question: The following sequence is given. Write a formula for $a_n$.
$\displaystyle\{1,2,4,7,11,16\}$
Note the arithmetic formula.
$\displaystyle a_n=a_1+\left(n-1\right)d$
Define $d$ as $d_n$, where $d_n$ is the difference between term $n$ and its succeeding term, $n+1$.
$\displaystyle a_n=a_1+\left(n-1\right)d_n$
$\displaystyle d_n=d_1+\left(n-1\right)g$
Where $g$ is the common difference for $d_n$.
$\displaystyle a_n=a_1+\left(n-1\right)\left(d_1+\left(n-1\right)g\right)$
$a_n\in\{1,2,4,7,11,16\}$
$d_n\in\{1,2,3,4,5\}$
$g=1$
$\displaystyle a_n=a_1+\left(n-1\right)\left(d_1+\left(n-1\right)\right)$
$\displaystyle a_n=1+\left(n-1\right)\left(1+\left(n-1\right)\right)$
$\displaystyle a_n=n^2-n+1$
But this doesn't yield the correct sequence.
Comment: You are making the mistake when assuming $a_n=a_1+(n-1)d_n$
Comment: The fact that two differences yield a constant says that the formula for $a_n$ is quadratic in $n$.  More generally, if $k$ differences yield a constant the formula for $a_n$ is of $k$th degree.  The leading term is the constant divided by $k!$, so here the $n^2$ term should be $\frac 12n^2$.  It is the same effect that integrating a constant $k$ times gives $\frac 1{k!}x^k$
Comment: @RossMillikan correct. But how in the WORLD is this supposed to help the OP?
Comment: @bers:  it gets the fact that the expression is quadratic and the quadratic term.  Subtracting that off gives a liner expression which can be solved by inspection
Answer: Following your notations :-
$d_n$ is the difference between the $(n+1)th$ and $nth$ term $\implies d_n=a_{n+1}-a_n$.
Also, $d_n=d_1+(n-1)g$ and $d_1=1$ and $g=1\implies d_n=n$.
Thus $a_{n+1}-a_n=n\implies a_{n+1}=a_n+n, \ n\geq 1$.
The mistake you were making is to assume that $a_n=a_1+(n-1)d$, which is true with a fixed common difference.
Answer: As others have already suggested in their comments and answer, your mistake lies in the step $a_n=a_1+(n-1)d_n$. Actually it should be replaced by $\boxed{a_n=a_1+\sum_\limits{i=1}^{n-1}d_i}$ where $n \ge2 $.
The rest of the solution will be as you have solved.


Tensorflow error: Variable gru_def/rnn/gru_cell/gates/kernel does not exist, or was not created with tf.get_variable()

Question: This is my first time in programming with python and tensorflow. I would like to use dynamic RNN to construct sentence embeddings.
Here is a part of my code written in jupyter.
graph = tf.Graph()
x_data = tf.placeholder(tf.int32, [None,None])
sequence_lengths = tf.placeholder(tf.int32, shape=[None])
embedding_mat = tf.Variable(tf.random_uniform([vocab_size,embedding_size],  0.0, 1.0),dtype=tf.float32)
embedding_output = tf.nn.embedding_lookup(embedding_mat,x_data)

with tf.variable_scope('cell_def'):
    cell =tf.contrib.rnn.GRUCell(num_units = rnn_size)
    hidden_state_in =cell.zero_state(batch_size,tf.float32)
with tf.variable_scope('gru_def'):
    output, state = tf.nn.dynamic_rnn(cell,embedding_output,initial_state=hidden_state_in,dtype=tf.float32,sequence_length=sequence_lengths)

with tf.Session(graph=graph) as sess:
    sess.run(tf.global_variables_initializer())
    feed_dict = {x_data:embedding_output}
    sess.run(output,feed_dict=feed_dict)
    #tf.get_variable_scope().reuse_variables()
sess.close()

When I run my code I get this error:

Variable gru_def/rnn/gru_cell/gates/kernel already exists, disallowed.
  Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope?
  Originally defined at:

I try to solve this problem  by calling tf.get_variable_scope().reuse_variables() to set the reuse flag to True but the error persists.
Then, I add a reuse parameter to the GRUCell but I have this error:

ValueError: Variable gru_def/rnn/gru_cell/gates/kernel does not exist,
  or was not created with tf.get_variable(). Did you mean to set
  reuse=tf.AUTO_REUSE in VarScope?

cell = tf.contrib.rnn.GRUCell(num_units = rnn_size,reuse=True)

Can you help me please.
Answer: In tensorflow 1.3+:
cell = tf.contrib.rnn.GRUCell(num_units=rnn_size, reuse=tf.AUTO_REUSE)

Comment: Thank you for response. It works but I get an other error:    "TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, numpy ndarrays, or TensorHandles." I think that I have a problem with feed_dict specifically with tf.nn.embedding_lookup which return a tensor. Can you help me to solve this problem.
Comment: You should better write a different question so that I or anybody else could answer. But in short you need to the word indices. `embedding_output` is the embedding that you feed to RNN, this is correct, but not into `feed_dict`
Comment: I'm sorry. I have click the check-mark now. Thanks for response. I will write a different question if i can't solve the problem after your suggestion.


What Security Implications Does WSMan "TrustedHosts" Have?

Question: I found that WinRM requires TrustedHosts (in WSMan:\client) to be set to run remote PowerShell commands.  I am unable to find official documentation on the security ramifications and risks of trusting dangerous hosts.
In my situation I have a shared RDP server connected to a domain.  I would like to give users access to connect remote PowerShell to potentially compromised systems, which are not on the same DC.
Comment: it's just an acl for source IPs that can connect, you should also enable https
Answer: Client side TrustedHosts allows you to connect to remote machines whose identities can't be verified either through domain membership or SSL certification. Since it's impossible to know if the endpoint is friendly or hostile, the security model requires you to vouch for it by taking an explicit step.
Your question wasn't clear about running commands remotely, so I'll touch on a few topics.
This has little to do with whether you can run scripts hosted on a remote share - that's execution policy.
Likewise, with a knowable host via domain or https you don't need to set the TrustedHosts to run commands in a remote context.
TrustedHosts is just about making the connection in the first place.
Think very hard about your stated goal that you want to allow remote connections into compromised systems. You start opening yourself to pass impersonation attacks. If you know a system is compromised, you should be very wary.
Additional info:

Managing Non-Domain Computers
  When you make a connection, by default, remoting delegates your logon
  credentials to the remote computer. The remote computer uses those
  credentials to impersonate you, executing the commands on your behalf.
  As you can imagine, there are security risks involved when delegating
  your credentials to a remote server. For instance, if a malicious user
  was able to successfully impersonate a known remote computer, you
  could possibly turn in your credentials to that impostor, who could
  use them against you and other people in the network
  http://resources.intenseschool.com/remote-management-with-powershell-part-2/


Howto use the Silverlight Toolkit

Question: I'm trying to implement a Drag and Drop interface for my windows phone application. I'm following this tutorial. I have downloaded and installed the Silverlight toolkit from their site. Also I have added a reference to it.
I get the following error when I try to compile my code.
Error   1   'toolkit' is an undeclared prefix. Line 33, position 14.    C:\Users\USER\Documents\Visual Studio 2010\Projects\DragEventDemo\DragEventDemo\MainPage.xaml   33  14  DragEventDemo

This is the code I have in the content grid in my MainPage.xaml
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"></Grid>
    <Rectangle Width="100" Height="100" Fill="Red">
        <toolkit:GestureService.GestureListener>
            <toolkit:GestureListener DragDelta="OnDragDelta"
        GestureBegin="OnGestureBegin" GestureCompleted="OnGestureCompleted" />
        </toolkit:GestureService.GestureListener>
        <Rectangle.RenderTransform>
            <TranslateTransform />
        </Rectangle.RenderTransform>
    </Rectangle>
</Grid>

What am I missing out on?
Comment: Have you included the Toolkit namespace in the page?

`xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"`
Answer: Have you got a prefix declaration within your PhoneApplicationPage tag?
    <phone:PhoneApplicationPage
        (...)
        xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
        (...)
    >

Comment: How do I get this to add automatically?
Comment: There are extentions that help with that, eg. Resharper: http://www.jetbrains.com/resharper/

Howto use the Silverlight Toolkit


Methods for fitting a distribution to regression data

Question: I'm hoping to find a method/algorithm/approach for fitting to a distribution to regression data.
Essentially I have a problem where I have survival data with independent variables, but only cases that actually had an event. All data where an event did not occur before censoring has been purged.
I understand a cox model should still work here, but as there is no censored data it would not be as strong or appropriate as typical survival data. I assume there are other methods that would work better.
Really I have a regression problem, attempting to use multiple independent variables to predict time-to-event, but I need a distribution/curve output instead of a single point. Then I can produce different probabilities of an event occurring within one week, two weeks etc, for new cases.
What are some approaches or methods for doing so?
Answer: I don't see a reason why the standard survival analysis methods wouldn't work here, you can choose to go non-parametric (e.g. Kaplan-Meier), semi-parametric (Cox proportional hazards) or fully parametric (accelerated failure time models). All of these can provide you with estimates of the survival function over time, obviously with different assumptions underpinning them.
The larger problem is that you do not have all relevant data; the power of these methods is exactly in their ability to incorporate censored observations into the survival estimate to the extent they are still informative. They work just as well when everything has been observed. You won't have much of an issue if you have follow-up until a large majority of the sample experienced the event, but in practice this is not often the case.
If your uncensored-only sample is not sufficiently representative of the full survival curve your best option is to go get the censored observations. Otherwise you'll have to make strong, possibly unverifiable assumptions on the censoring distribution, or accept that your estimates will likely be flawed. No model can fix a lack of reliable data.
Comment: The problem is that such "complete-data analysis produces unbiased estimates only if the missing (censored observations) are missing (censored) completely at random" ([Leung et al, Annu. Rev. Public Health 1997. 18:83–104](https://doi.org/10.1146/annurev.publhealth.18.1.83), page 90). That's an extremely strong assumption.
Comment: The standard survival methods should certainly still work but I assume that due to the lack of censored data, would lose a lot of strength compared to other methods. Without this data I'm ending up with a regression problem, which is fine for my needs.

I assume there are methods, similar to the cox, but fit distributions to more typical regression data and would be more suitable for me. I'm hoping to find something like that.
Comment: No, these methods don't *give away* power to handle censoring, it is rather the opposite. Your first choice is whether you want to make parametric assumptions on the time-to-event, if so an AFT model is going to be as powerful as any (provided your assumptions are correct). It is rather that non-survival methods *cannot* handle censoring, so they are always at most as powerful as what your are being forced to do now if you cannot re-include censoring in some way.


How do I bulk delete questions

Question: Let's say there 's a 30- question in my hand.
I would like to delete these 30 questions at a time.
But there are some coding errors and much appreciated if you could help me
public function Clear()
    {
        $stmt = $this->db->prepare("SELECT id FROM ask_data WHERE standart=0");
        $stmt->execute();

        if ($stmt->rowCount() > 0)
        {
            $ask_cnt = $stmt->rowCount();

            $ask_data = array();

            while ($row = $stmt->fetch())
            {
                $data = array("ask_id" => $row['id']);
                $stmt2 = $this->db->prepare("DELETE FROM  id FROM questions WHERE ask_id=(:ask_id)");
                $stmt->bindParam(':ask_id', $ask_data[$i], PDO::PARAM_INT);
                $stmt2->execute();
            }
            $i = 0;
            $count = count($ask_id);

            for ($i=0;$i<$count;$i++)
            {
                $data = array("ask_id" => $row['id']);
                $stmt2 = $this->db->prepare("DELETE FROM  id FROM questions WHERE ask_id=(:ask_id)");
                $stmt->bindParam(':ask_id', $ask_data[$i], PDO::PARAM_INT);
                $stmt2->execute();
            }
        }
    }

Comment: Syntax seems wrong delete from table from table again?
Comment: not clear from the table code does not work at all br way
Answer: The delete statement is wrong - you have two from clauses. You should remove the FROM id:
DELETE FROM questions WHERE ask_id=(:ask_id)

Having said that, you could dramatically simplify your program by using the IN operator instead of a separate query:
DELETE FROM questions
WHERE ask_id IN (SELECT id
                 FROM   ask_data
                 WHERE  standart = 0)

Comment: Thank you but this your code not delete my questions
Answer: hy,Your delete query is not correct.You can use it like
"DELETE FROM questions WHERE ask_id=".$row['id'].";
Answer: I'm not understanding why you need a loops in your code to run thirty separate DELETE statement.
If the goal is delete rows from the questions table which have an ask_id column value that matches an id value from ask_data where the standart column has a value of zero...
this could be done in one SQL statement. One database roundtrip. No need for a separate SELECT statement, fetching rows, and running through a loop to perform more SQL statements.
  DELETE q.*
    FROM ask_data d
    JOIN questions q
      ON q.ask_id = d.id
   WHERE d.standart=0

How do I bulk delete questions


ListView carrega pela chamada do construtor mas não pelo botão

Question: Tenho um listview no meu app e criei na minha ViewModel uma metodo CarregarListView();
Quando eu chamo ele pelo construtor da minha ViewModel, uma lista ObservableCollection é carregada e é dado o binding na minha view.
Quando chamo o método CarregarListView() por um command de um botão o método CarregarListView() é chamado e a lista é carregada, mas não dá binding na minha view.
Alguém sabe o motivo disso?
Esse é meu listView
<code>    <ListView Grid.Row="2"
                      Grid.Column="1"
                      Grid.ColumnSpan="3"
                      ItemsSource="{Binding ListaIntervalos }"
                      HasUnevenRows="true">

                <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="20"/>
                            </Grid.RowDefinitions>

                            <Grid.ColumnDefinitions>
                                <ColumnDefinition />
                                <ColumnDefinition />
                            </Grid.ColumnDefinitions>

                            <Label Grid.Row="1" Grid.Column="0" Text="{Binding De}"  FontSize="20" VerticalOptions="Start" TextColor="Black"/>
                            <Label Grid.Row="1" Grid.Column="1" Text="{Binding Ate}"  FontSize="20" VerticalOptions="Start" TextColor="Black"/>

                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</code>
E na minha View Model esta assim
<code>    public ObservableCollection<Intervalo> ListaIntervalos { get; private set; } = new ObservableCollection<Intervalo>();

    //Construtor
    public VMBuscarSalto()
    {
        // Aqui funciona
        this.CarregaIntervalos();
    }

    public Command BuscaSaltosCommand
    {
        get
        {
            return new Command(() => ExecuteBuscaSaltosCommand());
        }
    }

    private void ExecuteBuscaSaltosCommand()
    {
        // Aqui a lista é carregada mas não dá o bind no listview
        this.CarregaIntervalos();
    }
</code>
Comment: Teria [Como criar um exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/mcve) para poder ser analisado ?
Comment: Olá, obrigado pela atenção.
Eu complementei meu post com o código.
Answer: Acredito que o problema relatado não tenha sido algo que eu tenha feito errado, e sim deva ser bug no componente ListView da Xamarin, que cá entre nós, esta cheio de falhas com relação ao uso de suas funcionalidades utilizando MVVM.
Resolvi meu problema utilizando o Code Behind, que é simplesmente carregando a propriedade  ItemsSource do listview em XAML
<code>    <ListView Grid.Row="2"
                      Grid.Column="1"
                      Grid.ColumnSpan="3"
                      x:Name="GridDeIntervalos">
</code>
e no code behind
<code>     List<Intervalo> listIntervaloModel = new List<Intervalo>();

            for (int i = 0; i < 10; i++)
            {
                listIntervaloModel.Add(new Intervalo
                {
                    De = "teste " + i,
                    Ate = "teste " + i
                });
            }

            GridDeIntervalos.ItemsSource = listIntervaloModel;
</code>


best-practice for mid-sized shared storage

Question: Our old 32TB RAID6 (net capacity: 26TB) system is showing its age and requires an upgrade,
so we are currently thinking about building up a new 100TB system.
The storage is mostly used for our user's home directorie, for sharing project data (working with media, so projects can get up to 1TB) and for
The old storage is attached to a Debian host via iSCSI; the file server exports the data via NFS (for the un*x hosts) and SMB (for W32).
For practical reasons, we would like to keep that.
In the past we found that project data grows at unexpected ends, so we use a flat storage pool where all the projects (and home dirs) are located in the same filesystem (rather than pre-allocating a certain amount of storage capacity to a given project, and then having to re-allocate when hitting limits).
While this is a simple and flexible solution, I remember hitting some limitations even with the old setup. The biggest partition on the old RAID system is 20TB, because xfs wouldn't allow me to create a larger filesystem (back then; not to talk about ext4; and I didn't really consider zfs or btrfs - and still don't).
Since I haven't particularily followed recent progress on the storage front, I'm a bit lost what the current best-practices in creating such mid-sized storages are: JBOD, LVM, RAID, distributed filesystems; stacking which on which?
Some blogs suggest that RAID6 is obsolete anyhow, but what are the alternatives?
My requirements are:

~100TB net capacity
"flat" filesystem view
redundant (survives multiple concurrent disk failures)
white-box system
runs on Debian (Debian/stretch)
iSCSI
scalable: ideally such a system would allow for growing (e.g. I start off with 70TB and later buy disks on the go until I reach full capacity, and the stack scales along: the filesystem grows and data is still stored redundantly, hopefully without having a handful of separate RAID6 systems).
Answer: Go ZFS. If you want Debian ZoL is your best friend.
https://github.com/zfsonlinux/zfs/wiki/Debian
Answer: RAID 6 is far from obsolete - RAID 5 is however. I'm not a fan of single-controller storage, single point of failure you see, but if you're happy with that then by all means carry on with something similar to what you have now. Of course what you may well choose to go for now is some form of flash-based front-end - either through caching or tiering - it depends where you want to do the actual RAIDing - I like hardware controllers, you may not. Either way if you can get to a point where 90% of your IO is coming from/to flash (SSD/NVME etc.) then your users will be very happy indeed.
Comment: Well, RAID50 or RAID60 are still a good consideration. RAID5/6 are still good for all-flash storage arrays.
Answer: Honestly it seems like you describe something similar to Linus's workload, maybe smaller file sizes but same linux based OS and large size requirements. Take a look at his storeanator review and give the guys at 45drives a look see.
Comment: Link-only answers aren't very helpful, links rot over time (many of my early answers met that fate). Please add at least a summary of the linked content so that this answer can stand alone.


Generalization of name and nice names

Question: Let $\mathbb{P}$ be poset.
Let $D, B$ be sets. We say that a $\mathbb{P}$-name $\dot{z}$ is a nice name for a function from $D$ into $B$ if there is $\left<{A_{d},h_{d}}\right>_{d \in D}$ such that $\dot{z}(d)=\left<{A_{d},h_{d}}\right>$(as a nice name) for all $d\in D$, that is, $A_{d}$ is a maximal antichain and $h_{d}:A_{d}\to B$ such that $ p\Vdash\dot{z}(d)=h_{d}(p)$ for all $p \in A_{d}$.
Let $B$ be a set. We say that a $\mathbb{P}$-name $\dot{b}$  is a nice name for member of $B$ if there is a maximal antichain $A\subseteq\mathbb{P}$ and a function $h:A\rightarrow{B}$ such that $ p\Vdash\dot{b}=h(p)$ for all $p\in{A}$. Here, we abuse of the notation and say $\dot{b}=\left<{A,h}\right>$ .
Given a maximal antichain $A$ and a function $h:A\rightarrow{B}$, we can  construct a name $\dot{b}$ such that $\dot{b}=\left<{A,h}\right>$ applying the mixing lemma:

Let $A$ be an antichain in $\mathbb{P}$ and suppose that $\tau_p$ for $p\in A$ are $\mathbb{P}$-names. Then there is a $\mathbb{P}$-name $\sigma$ such that $p\Vdash \sigma=\tau_p$ for each $p\in A$.

For $d \in D$, if $A_{d}$ is a maximal antichain and $h_{d}:A_{d}\to B$ is possible to construct a $\dot{z}$ such that $\dot{z}=\left<{A_{d},h_{d}}\right>$ applying the mixing lemma.?
If not how I can build such $\dot{z}$ such that $\dot{z}=\left<{A_{d},h_{d}}\right>$. Any ideas thanks
Answer:
$(a)$ Given a maximal antichain $A$ and a function $h:A\rightarrow{B}$ you can build your a name $\dot{b}$ such that $\dot{b}=\left<{A,h}\right>$ applying the mixing lemma.

Then use $(a)$ to build $\dot{z}=\left<{A_{d},h_{d}}\right>$

Generalization of name and nice names


Interpret locations from Keen.io JSON file in logstash filter

Question: I'm trying to parse a JSON file from Keen.io with logstash into elasticsearch. The location and timestamp are stored in parameters like this:
{
  "result":
  [
    {
      "keen":
      {
        "timestamp": "2014-12-02T12:23:51.000Z",
        "created_at": "2014-12-01T23:25:31.396Z",
        "id": "XXXX",
        "location":
        {
          "coordinates": [-95.8, 36.1]
        }
      }
    }
  ]
}

My filter currently looks like this:
input {
  file {
    path => ["test.json"]
    start_position => beginning
    type => json
  }
}

filter {
  json {
    source => message
    remove_field => message
  }
}

output {
  stdout { codec => rubydebug }
}

How can I parse the "timestamp" and "location" fields so they are used for the @timestamp and @geoip.coordinates in Elasticsearch?
Update:
I've tried variations of this with no luck. The documentation is very basic - am I misunderstanding how to reference the JSON fields? Is there a way of adding debug output to help? I tried How to debug the logstash file plugin and Print a string to stdout using Logstash 1.4? but neither works.
filter {
  json {
    source => message
    remove_field => message
  }
  if ("[result][0][keen][created_at]") {
    date {
      add_field => [ "[timestamp]", "[result][0][keen][created_at]" ]
      remove_field => "[result][0][keen][created_at]"
    }
  }

Update 2:
Date is working now, still need to get location working.
filter {
  json {
    source => message
    remove_field => message
    add_tag => ["valid_json"]
  }
  if ("valid_json") {
    if ("[result][0][keen][created_at]") {
      date {
        match => [ "[result][0][keen][created_at]", "ISO8601" ]
      }
    }
  }
}

Comment: I don't think that `add_field` is the right one, you'd need `update_field` because the timestamp field already exists. Anyhow, does it jump into the `if (...)` part at all? Add a tag somewhere in there to find out.
Comment: What you want is the `match` attribute of the `date` filter, like `filter {
  date {
    match => [ "[result][0][keen][created_at]", "MMM dd YYYY HH:mm:ss" ]
  }
}`
Comment: http://logstash.net/docs/1.4.2/filters/mutate#update is the one I meant, it is only available via the `mutate` filter. So, store the value in a temporary and then update it using that filter. Concerning the tags, I'd regularly set a tag like `valid_json` in the `json` filter and then check for this tag to decide further processing. I'd also use the else branch to mark this log entry as clearly invalid, as it suggests there's a programming error somewhere.
Comment: But `update_field` doesn't exist? Good idea on the tag, was wondering what they were for.
Answer: Keen.io's "created_at" field is stored in ISO 8601 format and so can easily be parsed by the date filter. Lat/long co-ordinates can be set by copying Keen.io's existing co-ordinates into logstash's geoip.coordinates array.
input {
  file {
    path => ["data.json"]
    start_position => beginning
    type => json
  }
}

filter {
  json {
    source => message
    remove_field => message
    add_tag => ["valid_json"]
  }
  if ("valid_json") {
    if ("[result][0][keen][created_at]") {
      date {
        # Set @timestamp to Keen.io's "created_at" field
        match => [ "[result][0][keen][created_at]", "ISO8601" ]
      }
    }
    if ("[result][0][keen][location][coordinates]") {
      mutate {
        # Copy existing co-orndiates into geoip.coordinates array
        add_field => [ "[geoip][coordinates]", "%{[result][0][keen][location][coordinates][0]}" ]
        add_field => [ "[geoip][coordinates]", "%{[result][0][keen][location][coordinates][1]}" ]
        remove_field => "[result][0][keen][location][coordinates]"
      }
    }
  }
}

output {
  stdout { codec => rubydebug }
}


R code for two sample t-test in case of equal variances

Question: In R, how can I perform a two sample t-test in the case of equal variances?
My actual problem is to compare different algorithms for length measurements in machine vision.
I have studied Applied Statistics and Probability for Engineers by Montgomery & Runger and I have tried to implement the test in R and compare the results to the R command t.test.
This is my code:
# Douglas C. Montgomery, George C. Runger
# Applied Statistics and Probability for Engineers
# Third Edition
# 10-3.1 Hypotheses Tests for a Difference in Means, Variances Unknown, p.337
# Case 1: sigma_1^2 = sigma_2^2 = sigma^2
#
# See also: EXAMPLE 10-5, p.339
two_sample_t_test_equal_variance <- function(x1,x2,Delta_0,alpha)
{
   n1 <- length(x1)
   n2 <- length(x2)
   dof <- n1+n2-2
   S1_squared <- var(x1)
   S2_squared <- var(x2)
   #pooled estimator:
   Sp_squared <- ((n1-1)*S1_squared + (n2-1)*S2_squared)/(n1+n2-2)
   x1_bar <- mean(x1)
   x2_bar <- mean(x2)
   Sp <- sqrt(Sp_squared)
   t0 <- (x1_bar - x2_bar - Delta_0)/(Sp*sqrt(1/n1+1/n2))
   t_half_alpha_dof <- -qt(alpha/2,dof)
   reject_H0 <- (t0 > t_half_alpha_dof || t0 < - t_half_alpha_dof)
   if ( reject_H0 ) {
      cat("Reject H0 (alpha =",alpha,").\nH0 is mu1 - mu2 =", Delta_0, "\n\n" )
   } else {
      cat("Cannot reject H0 (alpha =",alpha,").\nH0 is mu1 - mu2 =", Delta_0, "\n\n" )
   }

   test_result <- t.test(x1, x2, alternative="two.sided", mu=Delta_0,
                          paired=FALSE, var.equal = TRUE )

   accept_H0_by_R <- (test_result$p.value > alpha)
   if ( reject_H0 != !accept_H0_by_R ) {
      cat("WARNING: R t.test gives a different answer for accepting H0.\n" )
   }

   rel_error_warn <- 0.01
   if ( abs(test_result$statistic - t0)/abs(test_result$statistic) > rel_error_warn ) {
      cat("WARNING: t0 relative error is >", rel_error_warn, "\n"  )
   }
}

# data from EXAMPLE 10-5, p.339
cat1<-c(91.50, 94.18, 92.18, 95.39, 91.79, 89.07, 94.72, 89.21)
cat2<-c(89.19, 90.95, 90.46, 93.21, 97.19, 97.04, 91.07, 92.75)
two_sample_t_test_equal_variance(cat1,cat2,0,0.05)

Is my invocation of t.test correct for the case at hand?
Is there any error in the code?
I tagged the question with "homework" even if I am not at school since more than 10 years and I am self-studying statistics for job-related reasons.
Thank you.
Alessandro
Comment: Are you aware that there is already a function in R doing that ? Try help(t.test).
Comment: @steffen Yes, I am aware. I included in the code my invocation of t.test and I would like to know whether it is correct.
Comment: @uvts_csv Sorry, did not read the question properly :(
Answer: If you were still in school then you might have a couple points taken off for saying that you accept the null hypothesis.  The purists (well frequentist purists) will always say that we never accept the null, just fail to reject it.
As a style thing, generally test functions will return an object with the test statistic, p-value, etc. and not print anything.  Then a print method will be used to print the results nicely.  But for learning or simple use what you have done is fine (I would go the other route if you are planning on building on this, or doing more of your own tests).
In your last cat statement you use relative_error_warning, but I don't see it defined anywhere, did you mean rel_error_warn?  Not that that line is ever likely to be run.
Everything looks correct, both your calculations and the running of t.test, I would expect the only differences you ever see to be rounding error (or due to handling of missing values).
Comment: +1, thank you very much for the "frequentist purists" clarification. I fixed the last cat statement.
Comment: I also changed "Accept null" into "Cannot reject".


Contar a quantidade de meses entre uma data e outra

Question: Eu gostaria de contar a quantidade de meses entre uma data e outra.
Vou deixar um exemplo, o que eu quero é basicamente só um contador mesmo.
Ex: quantidade de meses entre 05/02/2018 até hoje (21/03/2019)
Comment: Quantidade de meses entre 05/02/2018 até hoje (21/03/2019). qual é o resultado? 13 ou 12
Comment: se a data for 28/02/2019, quer que o resultado seja 1 mês ou 0?
Comment: nesse caso seria 0 mesmo
Answer: Antes é preciso entender dois conceitos importantes:

uma data é um ponto específico do calendário. Ex: hoje é 21/03/2019 (dia 21 do mês de março do ano de 2019)
uma duração é uma quantidade de tempo. Ex: morei na cidade X por 3 anos e 5 meses (não disse em que data comecei a morar, é apenas a quantidade de tempo, sem nenhuma relação com calendários)

Ambas podem até usar as mesmas palavras (dias, meses, anos etc), mas são conceitos diferentes.
Uma das respostas está obtendo uma duração (o TimeSpan) e usando-a para criar outra data (DateTime), o que não faz sentido: o DateTime representa uma data, e o TimeSpan representa uma duração. Ponto.
É claro que os conceitos estão relacionados: se eu tiver duas datas (instâncias de DateTime) e calcular a diferença entre elas, o resultado será a quantidade de tempo entre essas datas (ou seja, um TimeSpan).

Enfim, para calcular a diferença de meses entre duas datas, vai depender do seu critério para considerar o que é um "mês".
O método mais direto para calcular a diferença entre datas é:
DateTime date = new DateTime(2018, 2, 5);
TimeSpan difference = DateTime.Now - date;
Console.WriteLine(difference.TotalDays);

TotalDays retorna a diferença em dias, incluindo as casas decimais (já que leva em conta o horário atual também). Rodando agora, eu obtive 409.804892438586. Se quiser, pode usar também difference.Days, que retorna o valor como um inteiro (409).
Mas 409 dias são quantos meses?

"Ah, é só dividir por 30, dá 13 meses"

Na verdade depende. Meses têm tamanhos variados, podendo ter 28, 29, 30 ou 31 dias, e nem sempre a conta é tão simples assim.
Por exemplo, entre 01/01/2019 e 01/02/2019 há 31 dias. Dividindo por 30 e arredondando, dá 1 mês.
Mas entre 01/02/2019 e 01/03/2019 há 28 dias. Dividindo por 30, dá 0,93: se arredondar pra baixo, dá zero meses. Mas entre 1 de fevereiro e 1 de março a diferença não é de um mês? Então devemos arredondar pra cima nesse caso?
Mas e se fosse entre 01/01/2019 e 29/01/2019, a diferença também é de 28 dias. Só que entre 1 de janeiro e 29 de janeiro ainda não se passou 1 mês, então eu não posso arredondar pra cima nesse caso. "Ah, então eu só arredondo pra cima se não estiver no mesmo mês".
Aí você vê que entre 01/01/2019 e 27/02/2019 a diferença é de 57 dias, que dividido por 30 dá 1,9. Se arredondar pra cima dá 2, mas entre 1 de janeiro e 27 de fevereiro ainda não se passaram dois meses. E agora?
Dividir por 30 (ou por qualquer outro valor "médio" arbitrário) sempre terá esse problema. Isso acontece porque meses têm tamanhos variados e a quantidade exata de meses equivalente aos dias vai depender das datas envolvidas.
Aritmética de datas não é nada óbvia, e muitas vezes é contra-intuitiva. Não é que nem na matemática, onde 10 unidades sempre são uma dezena, 10 dezenas são uma centena, etc. Com datas, podemos ter "uma dezena que não tem 10 unidades" (como um mês que pode não ter exatamente 30 dias, ou um ano que pode ter 366 dias). Por isso não existe a regra correta para isso, cabe a você escolher uma forma de calcular essas diferenças.

Se quiser, você pode fazer um cálculo considerando apenas o mês e ano:
static int ajustaMesAno(DateTime d) {
    return d.Year * 12 + d.Month;
}

DateTime date = new DateTime(2018, 2, 5);
int mesesDiff = ajustaMesAno(DateTime.Now) - ajustaMesAno(date);
Console.WriteLine(mesesDiff);

Considerando que DateTime.Now retorna a data de 21/03/2019, o código acima calcula a diferença em meses entre 05/02/2018 e 21/03/2019, e o resultado é 13.
Mas e se a data inicial for 22/02/2018? Você vai considerar que a diferença é 12 meses (pois só no dia 22/03/2019 é que completará o décimo terceiro mês) ou de 13 meses (porque só interessa o mês, independente do dia)?
Se quiser considerar que são 12 meses porque só depois do dia 22/03 é que completa o mês, basta incluir o ajuste:
DateTime inicio = new DateTime(2018, 2, 22);
DateTime fim = new DateTime(2019, 3, 21);
int mesesDiff = ajustaMesAno(fim) - ajustaMesAno(inicio);
if (inicio.Day > fim.Day) {
    mesesDiff--;
}
Console.WriteLine(mesesDiff); // 12

No exemplo acima eu usei a data final como 21/03/2019 para fins didáticos (para que o resultado seja 12), mas você pode trocar por DateTime.Now para usar a data atual.

Não confunda DateTime com TimeSpan
Apenas para explicar porque o que uma das respostas sugeriu não é o correto.
Primeiro ela calcula a diferença entre as datas e obtém o TimeSpan. Até aqui OK:
DateTime inicio = new DateTime(2018, 03, 21);
DateTime fim = new DateTime(2019, 03, 21);
TimeSpan ts = fim.Subtract(inicio); // 365.00:00:00

Se você imprimir o TimeSpan, será mostrado "365.00:00:00" (uma duração de 365 dias, zero horas, zero minutos e zero segundos, ou seja, exatos 365 dias).
Depois - e esta é a parte errada - ela usa o valor de Ticks para criar outro DateTime (adicionei um WriteLine para vermos o resultado):
DateTime periodo = new DateTime(ts.Ticks);
Console.WriteLine(periodo); // 1/1/0002 12:00:00 AM

Só que Ticks retorna a quantidade de ticks. Segundo a documentação, um tick corresponde a um intervalo de 100 nanossegundos. No exemplo acima, o valor de Ticks é 315360000000000 (mais de 300 trilhões de ticks, pois esta é a quantidade de intervalos de 100 nanossegundos que existem em 365 dias).
O construtor de DateTime que recebe o valor de ticks cria uma data (não uma duração) correspondente a quantidade de ticks desde 1 de janeiro do ano 1, à meia-noite (não é o ano 2001 nem 1901, é o ano 1). No caso, a data resultante acima é 1 de janeiro do ano 2 (pois é a data correspondente a "315360000000000 ticks depois de 1 de janeiro do ano 1 à meia-noite").
Isso não é uma duração (não é a diferença entre as duas datas). Se você usar as propriedades desta data, vai obter os valores relativos à data. Por exemplo, d.Month retorna 1, mas por acaso a diferença entre as datas é de 1 mês? d.Year é 2, a diferença é de dois anos? Não, porque a variável periodo é um DateTime (uma data), não uma duração.
Por fim, a resposta ainda imprime a data desta forma:
Console.WriteLine("Anos: {0}  Meses: {1}  Dias: {2}", periodo.Year - 1, periodo.Month, periodo.Day);

O resultado é:

Anos: 1  Meses: 1  Dias: 1

Seria uma "duração" de 1 ano, 1 mês e 1 dia? Não, se reparar bem a diferença entre as datas usadas no exemplo é de exatamente 1 ano. O resultado está errado e isso acontece porque os conceitos de data e duração foram confundidos. Foi criada a data de 1 de janeiro do ano 2 e os valores do dia, mês e ano foram impressos como se fossem durações.
Você quer a diferença entre as datas (ou seja, uma duração), e isso já foi obtido quando você criou o TimeSpan. Nesse caso não tem porque criar outra data (outro DateTime) a partir do valor do TimeSpan.
Comment: entendi, muito boa explicação deixou bem claro toda a diferença entre DateTime e TimeSpan e ainda deu uma explicação ainda mais completa que eu queria porque provavelmente eu iria arredondar para 30 mesmo, mas vou optar por esse ajuste. Mas ainda há um problema que é o mesmo que eu tinha comentado acima estou recebendo o valor da date de um DateTimePicker ja tentei tanto pegar a propriedade **.Text** como a propriedade **.Value** e tanto com as duas o codigo -- **DateTime date = new DateTime(dtpVigencia.Text);** acaba resultando em **Argument 1: cannot convert from 'string' to 'long'**
Comment: @PHPatrick O `Value` do `DateTimePicker` já é um `DateTime`, pode fazer `DateTime date = dtpVigencia.Value` direto.
Comment: @PHPatrick O construtor de `DateTime` recebe um `long` (um tipo numérico), por isso a mensagem de erro (isso não quer dizer que o valor é "muito longo", e sim do tipo errado). Outra coisa, vi que vc desmarcou a resposta. Se faltou alguma coisa, me avise que eu adiciono...
Answer: Tente utilizar dessa maneira.
DateTime inicio = new DateTime(2018, 03, 21);
DateTime fim = new DateTime(2019, 03, 21);

TimeSpan ts = fim.Subtract(inicio);
DateTime periodo = new DateTime(ts.Ticks);

Console.WriteLine("Anos: {0}  Meses: {1}  Dias: {2}", periodo.Year - 1, periodo.Month, periodo.Day);

Comment: Seu código retorna `Anos: 1  Meses: 1  Dias: 1` (seria 1 ano, 1 mês e 1 dia?) mas a diferença entre 21/03/2018 e 21/03/2019 é de 1 ano apenas...
Answer: Utilize somente matemática. Como no exemplo abaixo:
DateTime inicio = new DateTime(1980, 01, 28);
DateTime fim = new DateTime(2019, 03, 21);

var i = Math.Truncate(fim.Subtract(inicio).Days / (365.25 / 12));

Caso queira verificar se está correto, entre neste site e insira as datas.
Referência: Difference in months between two dates.
Comment: Tem um *corner case*: entre 01/02/2019 e 01/03/2019 dá zero (mas a diferença entre elas não é de 1 mês?) Discutível, mas ainda sim, um *corner case*... :-)
Answer: Outra opção:
DateTime data = DateTime.Parse("5 / 02 / 2018");
DateTime hoje = DateTime.Today;

int meses = ((hoje.Year - data.Year) * 12) + hoje.Month - data.Month;

meses += data.Day > hoje.Day ? -1 : 0;

Answer:     static int GetQtdMoth(DateTime inicio, DateTime fim)
    {
        int years = fim.Year - inicio.Year;
        if (years < 0)
            return 0;
        if (years == 0)
            return fim.Month - inicio.Month;
        int meses = 12 - inicio.Month;
        return (years - 1) * 12 + meses + fim.Month;
    }


Top parts from Activity got hidden when soft keyboard shown

Question: I have an Activity contains TextView ----> ListView ------> TextField (from top to bottom). My problem when the soft keyboard is shown for TextField, The top parts from the activity scroll up and hidden. I added this line on my manifest but didn't solve the problem
<code><activity android:windowSoftInputMode="stateVisible|adjustResize"
</code>
I want to make the soft keyboard is always shown and in the same time the all parts of my activity are visible, there is no problem to resize the ListView to make free space for the soft keyboard, but how to make that?
Thanks a lot
Answer: What is you container: LinearLayout (vertical) or RelativeLayout ?
For LinearLayout try the following lines for ListView:
<code>   android:layout_height="0dp"
   android:layout_weight="1"
</code>
This will tell ListView to use all available height.
For a RelativeLayout
<code>   android:layout_allignTop="@+id/topTextId"
   android:layout_allignBottom="@+id/bottomTextId"
</code>
will do the same trick.
Comment: unfortunately didn't work  android:layout_height="0dp" cases white screen, Thanks


Javascript - Reduce Method over array. Add point value of cards together to get a total

Question: Currently, it is console logging:
14
16
[ { suit: '♣', value: 'J', points: 10 },
  { suit: '♥', value: 4, points: 4 } ]
[ { suit: '♥', value: 'K', points: 10 },
  { suit: '♣', value: 6, points: 6 },
  { suit: '♠', value: 'J', points: 10 } ]
0[object Object][object Object][object Object]

I only care about the last 3 objects being logged. The points of 10, 6, 10, which should give me 26.
dealerHand and playerHand are both arrays that have 2 cards pushed into them from the beginning. The dealerHand array will continue to "hit" or add cards if the total point value is less than 17.
After it adds a 3rd card, it logs the 0 and returns arrays of objects.
I believe the reduce method is a good way to get the total within an array, but I'm not sure what I'm missing.
///////////////////////////////////////////////
                CODE
///////////////////////////////////////////////
const dealRandomCard = () => {
     return deckOfCards.splice(Math.floor(Math.random() *
            deckOfCards.length), 1)[0];
}

// console.log(dealRandomCard());

//////////////////////////////////////////////////////////////
//                DEAL 2 CARDS TO EACH SIDE                 //
//////////////////////////////////////////////////////////////
  for (let i = 0; i < 2; i++) {
     playerHand.push(dealRandomCard());
     dealerHand.push(dealRandomCard());
  }

The dealRandomCard method is just returning one random card from the array that I have defined as deckOfCards with the appropriate suit, value, and points that can be added together to determine a winner.
let playerPoints = 0,
    dealerPoints = 0;

for (let { points } of playerHand) {
    playerPoints += points;
}

for (let { points } of dealerHand) {
    dealerPoints += points
}
    console.log(playerPoints);
    console.log(dealerPoints);

 /////////////////////////////////////////////////////////////

let totalPoints;

if (dealerPoints < 17) {
    dealerHand.push(dealRandomCard());

    totalPoints += points

} else {

    return

}

let totalDealerPoints = 0;

// for (let card of dealerHand) {

 totalDealerPoints += points;

 totalDealerPoints  = dealerHand.reduce((total , amount) => total +
 amount, 0);
 // }

// return totalDealerPoints
console.log(playerHand);
console.log(dealerHand);
console.log(totalDealerPoints);

///////// REVISED WITH CORRECT WORKING CODE /////////////
 let totalPoints = 0;

 if (dealerPoints < 17) {
    dealerHand.push(dealRandomCard());

   totalPoints += points

 } else {

  return

 }

 // for (let card of dealerHand) {

 totalPoints += points;

 totalPoints  = dealerHand.reduce((total , card) => total +
 card.points, 0);

Comment: What is `dealRandomCard`?
Comment: You are using a variable `points` in the second half of this that is not defined (you use a local version of `points` in the for loops).
Comment: edited for clarity, sorry about that
Answer: It seems like code is missing because in lines like this:
    dealerHand.push(dealRandomCard());
    totalPoints += points

points is not defined anywhere in the current scope and totalPoints was not initialized to zero. But since these values aren't really being used, I'm not sure what to say.
Regarding the reduce, you will get a card with each pass through, so you need to add the card.points:

let dealerHand = [
  { suit: '♥', value: 'K', points: 10 },
  { suit: '♣', value: 6, points: 6 },
  { suit: '♠', value: 'J', points: 10 } ]

let totalPoints = dealerHand.reduce((total, card) => total + card.points, 0)
console.log(totalPoints)
Comment: Appreciate it. My mistake as I had points defined globally, not shown in code. Also I have initialized totalPoints to 0 and added card.points to the arguments


Given $m$, find three numbers $a,b,c$ such that $c-b=m(b-a)$ and $a+b,a+c,b+c$ are all squares

Question: I've worked with the next problem

Given an integer $m$, find three integers $a,b,c$, with $b\neq a$, such that $c-b=m(b-a)$ and
$$a+b=x^2, \ \ a+c=y^2, \ \ b+c=z^2,$$
where $x,y, z \in \mathbb{Z}$.

I've not been able to give a result that guarantees the existence of solutions of this problem for some $m$ values.
Can you help me, please?
Comment: In that case $a=b=c=2$ works for every $m$.
Comment: Are $x,y,z$ given as part of the problem, or only $m$?
Comment: Possible duplicate of https://math.stackexchange.com/questions/2383893/find-three-numbers-such-that-the-sum-of-all-three-is-a-square-and-the-sum-of-any
Comment: Only $m$ is given
Comment: I forgot to say that $b$ should be different of $a$.
Comment: The condition requires $$y^2-x^2=m(z^2-y^2)$$ or $$x^2-(m+1)y^2=-mz^2.$$

You also require $x+y+z$ even, and then you get $$a=\frac{x^2+y^2-z^2}{2},b=\frac{x^2+z^2-y^2}{2},c=\frac{y^2+z^2-x^2}{2}.$$
Answer: The condition requires $$y^2-x^2=m(z^2-y^2)$$ or $$x^2-(m+1)y^2=-mz^2.$$
You also require $x+y+z$ even, and then you get $$a=\frac{x^2+y^2-z^2}{2},b=\frac{x^2+z^2-y^2}{2},c=\frac{y^2+z^2-x^2}{2}.$$
But there is a general approach to finding all rational solutions to:
$$aX^2+bY^2=c$$
if you have one rational solution.
Here, we have $(a,b,c)=(1,-(m+1),-m)$. and base solution $(X_0,Y_0)=(1,1)$.
Then if $p,q$ are integers, not both zero, then there is another rational solution $(X,Y)=(X_0+pt,Y_0+qt)$ with $t\neq 0$.
Solving, we get $$(1+pt)^2-(m+1)(1+qt)^2=-m\\
2pt + p^2t^2  -2(m+1)qt-(m+1)q^2t^2=0\\
2t\left[p-q(m+1)\right] + t^2\left[p^2-(m+1)q^2\right]=0$$
Assuming $t\neq 0$, you have:
$$t=\frac{2q(m+1)-2p}{p^2-(m+1)q^2}$$
This obviously has problems if $p^2-(m+1)q^2=0$, which can happen when $m+1$ is a perfect square.
Also, if $q=1,p=m+1$ then the numerator is zero, so doesn't give a new solution, but that's okay.
Now $$1+pt = \frac{(m+1)q(2p-q)-p^2}{p^2-(m+1)q^2}\\
1+qt=\frac{(m+1)q^2+p(p-2q)}{p^2-(m+1)q^2}
$$
Then any time $(m+1)q+p$ is even, and $p^2-(m+1)q^2\neq 0$ you get the solution:
$$(x,y,z)=\left((m+1)q(2p-q)-p^2,(m+1)q^2+p(p-2q),p^2-(m+1)q^2\right)$$
Trying $(p,q)=(4,2)$ you get:
$$(x,y,z)=(6m+2,2m+2,6-2m)\\(a,b,c)=(18m^2+4m-14,18m^2-28m+18,-14m^2+4m+18)$$
The general formula gives (I think, still needs checking):
$$a=2\left[(q-2p)^2q^2(m+1)^2-(4q^2-6qp+4p^2)pq(m+1)+p^2(p-2q)^2\right]\\
b=2\left[(q-2p)^2q^2(m+1)^2-(4p^2-2pq+4q^2)pq(m+1)+(p^2+4pq-4q^2)p^2\right]\\
c=2\left[(q^2+4pq-4p^2)q^2(m+1)^2+(4p^2+6pq+4q^2)pq(m+1)+p^2(p+2q)^2\right]
$$
Answer: Let
\begin{eqnarray*}
a&=&2((mp^2+2mpq-q^2)^2+(mp^2+q^2)^2-(-mp^2+2pq+q^2)^2) \\
b&=&2((mp^2+2mpq-q^2)^2-(mp^2+q^2)^2+(-mp^2+2pq+q^2)^2) \\
c&=&2(-(mp^2+2mpq-q^2)^2+(mp^2+q^2)^2+(-mp^2+2pq+q^2)^2) \\
\end{eqnarray*}
One can easily verify that
\begin{eqnarray*}
a+b&=& 4(mp^2+2mpq-q^2)^2 \\
b+c&=&4(-mp^2+2pq+q^2)^2 \\
c+a&=&4(mp^2+q^2)^2 \\
c-b&=&-16(pm-q)(p+q) pqm \\
b-a&=&-16(pm-q)(p+q) pq.
\end{eqnarray*}


Unknown column 'R.movie_name' in 'on clause' for Inner join with subquery

Question: I tried to rename the table using join, but I'm running into the Unknown column 'R.movie_name' in 'on clause'. I referenced this question to correct, but I'm still get the same error.
What am I doing wrong?
My SQL query
  SELECT R.movie_name, AVG(S.similarity*R.rating)
 FROM Ratings AS R, Similarity S
 INNER JOIN (
    SELECT DISTINCT R.movie_name
    FROM Ratings R, Users U
    WHERE U.name = 'Adam Brody' AND U.user_id != R.user_id
    ) AS MoviesAdamDidntWatch ON  R.movie_name = MoviesAdamDidntWatch.movie_name
 GROUP BY R.movie_name;

My Tables
CREATE TABLE Users (user_id INTEGER PRIMARY KEY,
                    name VARCHAR(100) NOT NULL);
CREATE TABLE Ratings (user_id INTEGER NOT NULL,
                      rating INTEGER NOT NULL,
                      movie_name varchar(100) NOT NULL,
                      PRIMARY KEY(user_id, movie_name),
                      FOREIGN KEY (user_id) REFERENCES Users(user_id));
CREATE TABLE Similarity (user1_id INTEGER NOT NULL,
                      user2_id INTEGER NOT NULL,
                      similarity FLOAT,
                      PRIMARY KEY (user1_id, user2_id),
                      FOREIGN KEY (user1_id) REFERENCES Users(user_id),
                      FOREIGN KEY (user2_id) REFERENCES Users(user_id));

Comment: Im not sure so I'm posting this as a comment. I think you should remove the `"AS"` in `FROM Ratings AS R, Similarity S`
Comment: `R` specified as an alias twice in query, one more issue how do you relate Similarity table with query, right now its doing cross product
Answer: You have used R twice as Alias in your query . You can fix it by replacing outer R with some other alias. like -
SELECT Rtg.movie_name, AVG(S.similarity*Rtg.rating)
 FROM Ratings AS Rtg, Similarity S
 INNER JOIN (
    SELECT DISTINCT R.movie_name
    FROM Ratings R, Users U
    WHERE U.name = 'Adam Brody' AND U.user_id != R.user_id
    ) AS MoviesAdamDidntWatch ON  Rtg.movie_name = MoviesAdamDidntWatch.movie_name
 GROUP BY Rtg.movie_name;

But your query is not optimised, Consider optimising it by removing redundant inner query and cross products.I may help you with it if you post your table structure.


Test if two measurements come from normal distributions with the same mean?

Question: I have two measurements $x_1\pm s_{x_1}$ and $x_2 \pm s_{x_2}$. The error intervals ($\pm$ one standard deviation) do not overlap. Does this necessarily mean that these are two samples from normal distributions with different means?
Or should I run a test to exclude (to some degree) the fact that they might still be from the same distribution?
Both means have an equal amount of measurements (about 2000). It is given that both are pulled from normal distributions.
Comment: The thread at http://stats.stackexchange.com/q/18215/ may shed some light on this question.
Answer:
There is no reason to suspect that the two samples are from normal distributions based on the information you have provided.
Even if the data are from normal distributions, the error intervals do not tell us useful information without knowing the number of samples you took. For example, if you took exactly one measurement for x1 and x2, then the standard deviations would be 0. In spite of this, there is no reason to suspect that x1 and x2 come from distributions with different means.

It sounds like want you want to build are confidence intervals. If you know how x1 and x2 are distributed, there are many formulas for building these. The wikipedia entry has examples for a normal distribution, and a good stats textbook will have many others. If you do not know the distribution, you can use bootstrapping techniques to determine it and create useful confidence intervals. If the confidence intervals do not overlap, then you have reason to believe that the data come from distributions with different means.
Comment: This reply does not appear to account for the supposition that $x_1$ and $x_2$ are accompanied with statements (or at least estimates--it's unclear which) about their errors.
Comment: I do not think you reply to the question.


Killing vector field and critical points

Question: In exercise 2, chapter 4, in do Carmo's Riemannian Geometry we have a exercise about Killing vector fields and in the final he says:"by Killing equation in p, $\nabla_{X}X(p) = 0$", where $p$ is a critical point of $f(q) = \langle X,X\rangle(q)$. But the only thing we can obtain from Killing equation is that $2\langle\nabla_{X}X,X\rangle = 0 \Rightarrow \langle\nabla_{X}X,X\rangle = 0 $. And: $df_{p}.v = 2\langle\nabla_{v}X,v\rangle $. What am i ignoring?
Thanks in advance.
Answer: Your problem is that you haven't correctly calculated the differential of $f$.
The compatibility with the metric equation is
$$ (d\langle X,Y\rangle) Z = Z\langle X,Y\rangle = \langle\nabla_Z X,Y\rangle + \langle X,\nabla_Z Y\rangle$$
see the definition at wiki.
Taking $X=Y$, and $d_p\langle X,X\rangle = 0$, we get the equation
$0 = 2\langle \nabla_Z X,X\rangle_p,$
or just
$\langle\nabla_Z X,X\rangle_p =0$.
Then the killing equation for $X$ is
$$\langle\nabla_Y X,Z\rangle + \langle Y,\nabla_Z X\rangle = 0$$
for all $Y$ and $Z$. When $Y=X$, we get
$$\langle \nabla_Z X,X\rangle = - \langle \nabla_X X, Z\rangle.$$
Then together with the first equation, we get
$$\langle \nabla_X X,Z\rangle_p = 0$$
for all $Z\in TM_p$. Taking $Z=(\nabla_X X)_p$, we get $(\nabla_X X)_p = 0$ as desired.
Answer: Recall the definition of Killing field $X$ : $ \langle
\nabla_YX,Z\rangle+\langle \nabla_ZX,Y\rangle =0$
Hence $Xf=2\langle \nabla_XX,X \rangle =0$. Hence $f$ is const along
flow of $X$.
When $q$ is a critical point of $f$ and $V\in T_qM$ is orthogonal to
$X$ so that $Vf=0$. That is $0=2 \langle
\nabla_VX,X\rangle=-2\langle \nabla_XX,V\rangle$. That is
$\nabla_XX=0$


How to override template file item-list.html.twig for field_slider_images in Drupal 8?

Question: I want to override the item listing template file core/themes/classy/templates/dataset/item-list.html.twig for listing the fields field_slider_images as well as field_blog_tags respectively  of their's multiple values of the field.
I have selected "Unordered List" in the view.
Please do check the attached image.

I have created following files :

item-list--field-blog-tags.html.twig
item-list--field-slider-images.html.twig

But, this is not rendered for the listing of the fields.
When I have created item-list.html.twig then only it will access.
However, both fields have different data to style and I am not able to get the current field name which is loading it's data in item-list.html.twig.
Answer: Had a brief look at this and it doesn't seem that 'item-list' to have suggestions, which is quite unfortunate.
In this situation there are two options:

Create your own suggestion which would accomplish exactly what you need.
You'll have to do something like this:

/
/*add new variable to theme with suggestion name*/
function hook_theme_registry_alter(&$theme_registry) {
  $theme_registry['item_list']['variables']['suggestion'] = '';
}

//send a value to newly added variable to use it build the suggestion
function hook_ENTITY_TYPE_view(array &$build, $entity, $display, $view_mode) {
    //add condition here if field exists or whatever, do the same for other field
    $build['field_slider_images']['#suggestion'] = 'field_slider_images';

}

//use newly added variable to build suggestion
function hook_theme_suggestions_THEME_HOOK(array $variables) {//THEME_HOOK=item_list

  $suggestions = array();
  if(isset($variables['suggestion'])){
    $suggestions[] = 'item_list__' . $variables['suggestion'];
  }

  return $suggestions;
}

Now you should be able to use item-list--field-slider-images.html.twig

Second option is to do what others in core did: use a new theme
function hook_ENTITY_TYPE_view(array &$build, $entity, $display, $view_mode) {
//add condition here if field exists or whatever, do the same for other field
$build['field_slider_images']['#theme'] = array(
  'item_list',
  'item_list__field_slider_images',
);

}
Comment: Thank you so muche. However, it is applying to all the fields of the node page. In this page, I have used field_slider_images as well as  field_blog_tags. If I apply  function hook_node_view(array &$build, $entity, $display, $view_mode) {
    //add condition here if field exists or whatever, do the same for other field
    $build['field_slider_images']['#suggestion'] = 'field_slider_images';

}
 then It is also applicable for both fields. For both fields, it have item-list--field_slider_images.tpl.php. Please help
Comment: I have created two blocks. One block is rendering field_slider_images and the other is rendering field_blog_tags. After that, I have attached that in block region of the node view. Please help how to create that item_list for these two fields with respect to two different blocks.
Comment: I don't see how
$build['field_slider_images']['#suggestion'] = 'field_slider_images';
applies for both fields
you just have to add next the suggestion for the other field like
$build['field_blog_tags']['#suggestion'] = 'field_blog_tags';
clear registry and item-list--field-slider-images.html.twig should be available
Comment: I am not able to get fields in $build of hook_ENTITY_TYPE_view.


Apresentar dados do Array na table Jquery

Question: Estou desenvolvendo uma aplicação em que calcula a média  em que faço a validação dos campos se estão devidamente preenchidos e se os campos  estiverem preenchidos e a soma das notas for menor que 10 ele passa os dados do inputText para funcão que faz o calculo da media e outra função que retorna o status do aluno se está aprovado,reprovado.Assim guardos os dados digitados em arrays e apresentando em uma table
Mas ao clicar no botão calcular ele apresenta essa mensagem.

HTML

<form action="" method="post" class="formcss" name="form1"  >

Dados do Aluno

        Por favor, preencha os campos solicitados.

RGM :

        <input id="rgm" type="text" name="rgm" placeholder="Digite seu RGM" class="entrada" />

Nome :

        <input id="nome" type="text" name="nome" placeholder="Nome completo" class="entrada" />

Nota parcial :

        <input type="text" id="notaparcial" name="notaparcial"
               placeholder="Digite aqui a nota parcial" class="entrada" />

Nota exercícios :

        <input type="text" id="notaexercicios" name="notaexercicios"
               placeholder="Digite aqui a nota dos exercícios" class="entrada" />

Nota projeto :

        <input type="text" id="notaprojeto" name="notaprojeto"
               placeholder="Digite aqui a nota no projeto" class="entrada" />

Nota regimental :

        <input type="text" id="notaregimental" name="notaregimental"
               placeholder="Digite aqui a nota regimental" class="entrada" />

        <input type="button" id="btncalcular" value="Calcular" class="botao" />
        <input type="button" id="btnlistar" value="Mostrar" class="botao" />

Resultado...

</form>

CSS

Funções e Jquery

Answer: Tens vários problemas no código:

situacao está definido duas vezes. Uma como função, outra como array
Usa Number() á volta dos numeros, para os converter de texto em numero
depois de if (validar) { dever ter os numeros pois vais compará-los no if seguinte, como tinhas estavam numa linha mais em baixo e por isso não tinham sido lidos ainda.

Sugestão:

function validar() {
  var nome = $("#nome").val();
  var rgm = $("#rgm").val();
  var parcial = Number($("#notaparcial").val());
  var exercicios = Number($("#notaexercicios").val());
  var projeto = Number($("#notaprojeto").val());
  var regimental = Number($("#notaregimental").val());

  if (nome == "") {
    alert('Preencha o campo com seu nome');
    form1.nome.focus();
  } else if (rgm == "") {
    alert('Preencha o campo com rgm');
    form1.rgm.focus();

  } else if (parcial == 0) {
    alert('Preencha o campo com a nota da parcial');
    form1.rgm.focus();

  } else if (exercicios == 0) {
    alert('Preencha o campo com a nota dos exe');
    form1.exercicios.focus();

  } else if (projeto == 0) {
    alert('Preencha o campo com a nota projeto');
    form1.projeto.focus();

  } else {
    alert('Preencha o campo com a nota regimental');
    form1.notaregimental.focus();
  }
}

function caculoMedia( /* n1, n2, n3, n4, etc */ ) {
  return [].reduce.call(arguments, function(sum, nr) {
    return sum + nr;
  }, 0) / (arguments.length);
}

function situacao(n1, n2, n3, n4) {
  var situacao = "";
  var media = caculoMedia(n1, n2, n3, n4);
  if (media >= 6) situacao += "Aprovado";
  else if (media < 6) situacao += "Exame";
  else situacao += "Reprovado";
  return situacao;
}

var nomes = [];
var indice = [];
var sit = [];
var media = [];

var i = 1;

window.onload = function() {
  var btn = document.getElementById("btncalcular");
  btn.onclick = function() {
    if (validar) {
      var parcial = Number($("#notaparcial").val());
      var exercicios = Number($("#notaexercicios").val());
      var projeto = Number($("#notaprojeto").val());
      var regimental = Number($("#notaregimental").val());
      console.log(parcial, exercicios, projeto, regimental);
      if (parcial + exercicios + projeto + regimental <= 10) {
        nomes[i] = $("#nome").val();

        var resp = caculoMedia(parcial, exercicios, projeto, regimental);
        media[i] = resp;
        var sit = situacao(parcial, exercicios, projeto, regimental);
        sit[i] = situacao;
      } else {
        alert("A soma das notas não podem ultrapassar 10");
      }
    }
  }
  document.getElementById("btnlistar").onclick = function() {
    listarAlunos();
  }
}

function listarAlunos() {
  var conteudo = "
";
  conteudo += "
";
  conteudo += "";
  conteudo += "

Aluno

";
  conteudo += "	";
  conteudo += "";
  conteudo += "

Media

";
  conteudo += "	";
  conteudo += "";
  conteudo += "

Situacao

";
  conteudo += "	";
  conteudo += "
";
  //pos contator
  for (var pos = 0; pos < nomes.length; pos++) {
    conteudo += "
";

    conteudo += "" + nomes[pos] + "	";
    conteudo += "" + media[pos] + "	";
    conteudo += "" + sit[pos] + "	";

    conteudo += "
";
  }
  conteudo += "
";
  document.getElementById("txtrelatorio").innerHTML = conteudo;
}
.formcss {
  width: 55%;
  background-color: #865027;
  padding: 20px 30px 20px 30px;
  font-size: 12px;
  font-family: verdana;
  color: #fff;
  text-shadow: 2px 2px 2px #000;
  border-radius: 25px;
  margin: 0 auto;
}

h1 {
  padding: 0px 0px 10px 0px;
  border-bottom: 3px solid #000;
  text-align: center;
}

.titulo {
  font-size: 11px;
}

div {
  margin: 0px 0px 20px;
}

.rotulos {
  float: left;
  width: 20%;
  text-align: right;
  padding-right: 10px;
  margin-top: 10px;
  font-weight: bold;
}

.rotuloretorno {
  float: left;
  width: 75%;
  font-size: 14px;
  font-family: verdana;
  text-align: left;
  padding-left: 200px;
  padding-right: 10px;
  margin-top: 10px;
  font-weight: bold;
}

.entrada {
  border: none;
  color: #525252;
  height: 30px;
  line-height: 15px;
  padding: 5px 0px 5px 5px;
  width: 70%;
  border-radius: 5px;
  box-shadow: 2px 2px 2px #000;
  background-color: #f5deb3;
}

.botao {
  background-color: #2e1707;
  border: none;
  padding: 10px 25px 10px 25px;
  color: #fff;
  border-radius: 4px;
  text-shadow: 1px 1px 1px #FFE477;
  font-weight: bold;
  box-shadow: 2px 2px 2px #3D3D3D;
}

.botao:hover {
  color: #dbd9d9;
  background-color: #030201;
}

<form action="" method="post" class="formcss" name="form1">

Dados do Aluno

    Por favor, preencha os campos solicitados.

RGM :

    <input id="rgm" type="text" name="rgm" placeholder="Digite seu RGM" class="entrada" />

Nome :

      <input id="nome" type="text" name="nome" placeholder="Nome completo" class="entrada" />

Nota parcial :

      <input type="text" id="notaparcial" name="notaparcial" placeholder="Digite aqui a nota parcial" class="entrada" />

Nota exercícios :

      <input type="text" id="notaexercicios" name="notaexercicios" placeholder="Digite aqui a nota dos exercícios" class="entrada" />

Nota projeto :

      <input type="text" id="notaprojeto" name="notaprojeto" placeholder="Digite aqui a nota no projeto" class="entrada" />

Nota regimental :

      <input type="text" id="notaregimental" name="notaregimental" placeholder="Digite aqui a nota regimental" class="entrada" />

      <input type="button" id="btncalcular" value="Calcular" class="botao" />
      <input type="button" id="btnlistar" value="Mostrar" class="botao" />

Resultado...

</form>