PHP Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE or '$'

Question: please I'm new to web developing and PHP programming as well, I've a PHP form code and a form but whenever i test it on a server this the error message I get:

FATAL ERROR syntax error, unexpected T_STRING, expecting T_VARIABLE or     '$' on line number 18

And the code follows:
<?php
/* Set e-mail recipient */
$myemail  = "email@example.com";
/* Check all form inputs using check_input
function */
$yourname = check_input($_POST['yourname'],
"Enter your name");
$subject  = check_input($_POST['subject'],
"Write a subject");
$email    = check_input($_POST['email']);
$website  = check_input($_POST['website']);
$likeit   = check_input($_POST['likeit']);
$how_find = check_input($_POST['how']);
$comments = check_input($_POST['comments'],
"Write your comments");
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $
email))
{
show_error("E-mail address not valid");
}
/* If URL is not valid set $website to empty */
if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/
i", $website))
{
$website = '';
}
/* Let's prepare the message for the e-mail */
$message = "Hello!
Your contact form has been submitted by:
Name: $yourname
E-mail: $email
URL: $website
Like the website? $likeit
How did he/she find it? $how_find
Comments:
$comments
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
    show_error($problem);
}
return $data;
}
function show_error($myError)
{

Please correct the following error:

 echo $myError;

exit();
}

Comment: on line 18 you got email, put in on the line before
Comment: Thanks a lot form working now, sad I missed that line though, should have used a programming IDE instead to bypass this blur. SALUTE !
Answer: You have a redundant (read: wrong) line-break between $ and email. Replace:
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $
email))

with:
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))

Comment: Thanks a lot ! buddy  , problem solved . Was utterly confused though.


How to bookmark/mark lines in Xcode 4?

Question: I work on a large project with lots of files. How can I bookmark or mark a specific file and a line within it?
Thanks.
Comment: See interesting solutions at http://stackoverflow.com/questions/5473207/how-to-bookmark-code-in-xcode-4
Answer: AFAIK - you can't. You can access any method quickly by assigning the keyboard shortcut to jump bar's method list.

How to bookmark/mark lines in Xcode 4?


Is there any special relation between squared root of sum of squares and sum of the values themselves?

Question: I mean, is there any relation between $a_1 + a_2 + a_3 + ... + a_n$ and $\sqrt{a_1^2 + a_2^2 + a_3^2 + ... + a_n^2}$ ? This relation can be of any kind or any use.
Thank you all in advance.
Comment: Welcome to MSE! I think you mean $\sqrt{a_1^2 + a_2^2 + a_3^2 + \ldots + a_n^2}$, right?
Comment: As it is currently written the root of squared sum, $\sqrt{(a_1 + a_2 + a_3 + ... + a_n)^2}$, is simply $|a_1 + a_2 +... a_n$
Note by convention a $\sqrt{}$  with no other notation is always positive or possibly zero..
Comment: @HaydnGwyn Yes, you're right. :) edited.
Answer: Assuming that all the $a_i \geqslant 0$ then it is true that the quadratic mean is greater than the arithmetic mean:
$$\left(\frac{1}{n}(a_1^2+a_2^2+\cdots+a_n^2)\right)^{\frac12} \geqslant \frac{1}{n}(a_1+a_2+\cdots+a_n)$$
or
$$n(a_1^2+a_2^2+\cdots+a_n^2) \geqslant (a_1+a_2+\cdots+a_n)^2$$
Comment: There was a mistake in my question. That was edited. Please, see it again if possible. Thank you.
Comment: @elyar - I think my answer still stands.
Comment: So, I have to thank you.


Alias de campo na cláusula where do oracle

Question: Tenho um Decode no meu select assim:
.....
DECODE(MAT.IND_TIPO_MAT_MED,
           '1', 'BRASINDICE',
           '2', 'SIMPRO',
           '9', 'TABELAPROPRIA') TIPOTABELA,
.....

Preciso passar esses valores na cláusula where, pois eles vêm por querystring, e na querystring eu pego esses valores: BRASINDICE,SIMPRO ou TABELAPROPRIA. Acontece, que como TIPOTABELA é uma alias, na cláusula Where en não consigo pegá-los. Se eu pegar pelo nome do campo real, eu não tenho esses valores, mas apenas: 1,2 ou 9, e na querystring são passados os valores representados e minha query não vai retornar nada. Preciso fazer uma inversão na query, ou seja, receber por querystring os valores e na hora de passar para a cláusula where, passar os valores reais. Como eu faço isso?
Obs: Via querystring eu recebo: BRASINDICE,SIMPRO ou TABELAPROPRIA e o campo aceita:1,2 ou 9. Há como fazer uma inversão?
Eu fiz um case e achei meio gambi. Fiz assim:
if(tipoTabela != string.Empty)
            {
                switch(tipoTabela)
                {
                    case "BRASINDICE":
                        tipoTabela = "1";
                        break;

                    case "SIMPRO":
                    tipoTabela = "2";
                    break;

                    case "TABELAPROPRIA":
                    tipoTabela = "9";
                    break;

                    default:
                    tipoTabela = string.Empty;
                    break;

                }

Comment: Esse segundo trecho da sua pergunta não corresponde mais ao assunto (Sql, Oracle). Convém neste caso fazer outra pergunta adicionando a tag adequada (c#, java, o que for). Blz?
Answer: O que você pode fazer é usar um sub-select e depois aplicar o filtro:
SELECT * FROM
(
    .....
    DECODE(MAT.IND_TIPO_MAT_MED,
               '1', 'BRASINDICE',
               '2', 'SIMPRO',
               '9', 'TABELAPROPRIA') TIPOTABELA,
    .....
) AS TBL_CONSULTA
WHERE TIPOTABELA LIKE 'SIMPRO'


"Pattern match" and recurse on types in closed type family for type equality proof

Question: Assume a situation like this:
data Foo a = Foo

type family AlwaysInt a where
  AlwaysInt (Foo a) = AlwaysInt a
  AlwaysInt _       = Int

I'd like to prove that AlwaysInt a is always Int.
import Data.Type.Equality

lemma :: AlwaysInt a :~: Int
lemma = undefined

How do I prove this? I'd like to "pattern match" on each type in the type family definition since I can prove the lemma for each case, but how do I do such a pattern match?
The ugly workaround is adding an a argument to lemma and leaving undefined there or putting an error message, but that's not great in real life situations.
EDIT: Forgot actual problem
Answer: You can't prove that.
type family Any where {}
type family ManyFoo where
  ManyFoo = Foo ManyFoo

What is AlwaysInt Any? Any is a stuck type, so GHC won't be able to reduce the type family application.
What is AlwaysInt ManyFoo? Well, ManyFoo is an infinite type,
ManyFoo = Foo (Foo (Foo ...))

so GHC will go into an infinite loop trying to calculate it or trying to calculate AlwaysInt ManyFoo.
Comment: Yes, but neither of these types is ever inhabited. Since I need to write `lemma :: a -> AlwaysInt a :~: Int` already to get rid of ambiguous types, can I prove that?
Comment: @Turion, you don't need an `a` to avoid ambiguous types; you just need a `Proxy a`. `ManyFoo` is not *obviously* uninhabited. If you add a `Typeable` constraint and determine that you definitely don't have an application of `Foo` (using `Type.Reflection`) then you can safely `unsafeCoerce` your way to an answer.
Answer: :~: is defined as a GADT which is inhabited when a is equal to b. When that is the case, the inhabitant is called Refl. GHC is smart enough to understand that the two types are equal in this case. This compiles
{-# LANGUAGE TypeFamilies, TypeOperators #-}

import Data.Type.Equality

data Foo = Foo

type family AlwaysInt a
  AlwaysInt Foo = Int
  AlwaysInt _   = Int

lemma :: AlwaysInt a :~: Int
lemma = Refl

If we change one of the Int to some other type, we'll get a type error since Refl is not a member of (something strange) :~: Int.
Comment: Oh yes, nice! It seems like I forgot to post the actual problem when shrinking my real world example to an MWE... how about the updated question now?


How to do social links with icons as a link field in a block?

Question: I have a footer that contains a simple contact information and underneath is a social follow set of links.
I created the block type, with the thought that the top part (Connect) is a WYSIWYG.
My second thought was to make the Follow Us just a link field with 5 values, but I want to add a little flexibility and for theming concerns, I need to know what link goes with which service.

Can I either do this with the link field, or can I reference a menu somehow and attach it to this block type? As a menu, I can rig up menu attributes. But if there is a more practical way, I would like to know how to do it.
I do not want to hard code it because they might change URLs or want to reorder the list of services at any time.
Answer: I had a similar task, for me was better creating a Custom Block Type, named 'Social networks' with one field of type 'Link'.
In this field you can configure how many links you can handle (remember once you create one block of this type, you'll cannot change this value).
Once this Custom Block Type was created you can configure 'Manage form display' and 'Manage display' if you need.
Now you'll be able to create a Custom Block of type 'Social Networks' that provide a couple of links that you can set/edit, rearrange and use proper template per block, and place where you want.
This was the solution found to not use any piece of code.


Sybase Anyware. SQL query to determine DB version

Question: What query or command to determine Sybase SQL Anyware version?
I use sqlsh + freetds as interactive client (in Emacs).
Comment: If you are using SQL Anywhere, you should probably use the [sqlanywhere] tag, and not the [sybase-asa] tag.
Answer: For databases, you can use the SYSHISTORY system view to find out what version the database was created at.
<code>select version from SYSHISTORY where object_id = OBJ_ID_OF_DB
</code>
If you databases were migrated from earlier installations, and don't show the version number you expect, you probably could just create a small database, and take a look at the version history information.
Comment: I issue `select version from SYSHISTORY;` as don't  know *OBJ_ID_OF_DB*. Great! +1
Comment: could not execute statement
column 'OBJ_ID_OF_DB' not found
sqlcode=143, odbc3 state=4252
Comment: t could not execute statement

select version from SYSHISTORY where object_id = OBJ_ID_OF_DB

column 'OBJ_ID_OF_DB' not found
sqlcode=143, odbc3 state=4252
for the statement
Actually all object_ID values for my database are 0(zero) for syshistory rows

However the next statement works
select version,* from SYSHISTORY where operation  in ('INIT', 'UPGRADE')


variable transformation in optimization

Question: I have an optimization problem with two sets of parameters, $x_i \in [0,1]$ and $y_k \in [-\frac{\pi}{2},\frac{\pi}{2}]$ where $i,k \in \{1...n\}$ are indices. One way to solve this problem is using constrained optimization by setting appropriate bounds on the parameters $x_i, y_k$.
I have a second idea, and that is to transform the variables using the following transformations. $$x_i = \frac{\left(1 + tanh\left(m_i\right)\right)}{2},\,\, y_i = tan^{-1}\left(n_i\right)$$ where $m_i,\, n_i$ are unconstrained parameters and $m_i,\, n_i \in [-\infty,\infty]$. I can now carry out the optimization wrt to $m_i,\, n_i$ and then re-transform the optimized parameters. Both these are 1-1 transformations.
Can someone point out the issues in variable transformation for optimization and what is the nature of functions that can be used. Also, if it leads to faster convergence?
Comment: If $y_k$ is close to $\pm \pi/2$, then $n_i$ will be very large in absolute value, and infinite if $y_k=\pm \pi/2$. Could you clarify why you want to transform the variables in the first place?
Comment: I want to use unconstrained optimization methods and compare how the constrained solution fares against unconstrained solution. My empirical experiment shows that unconstrained solution is much better than constrained solution
Answer: This kind of transformation is not a very good idea in general.  Problems with this approach are discussed in many textbooks on nonlinear optimization.  For example, there's a discussion of several issues with this approach in the textbook Practical Optimization by Gill, Murray, and Wright.
In your particular case, the problem will become very ill conditioned (with a "flat bottom" of solutions that are all very close to optimal) if the optimal value of $y_{k}$ is near $\pi/2$.
Optimization methods for bounds constrained problems are robust, fast, and widely available.  There's really no reason that you have to use such a transformation.
Comment: My empirical experiment shows that unconstrained solution is always better  than constrained solution with these transformations. Why would that be the case. Even when I approach the boundaries, the solution is not exact but still better than a constrained solution
Comment: Chances are that you're just using a bad solver for the bounds constrained problem....  You haven't told us what software you're using for the constrained solver, so it's hard to comment on that.
Comment: I am using R. I am using "L-BFGS-B". I have also tried nlminb
Comment: Also, if you are searching for solutions near the boundaries with parameters whose scale is unknown, there is not much one can do. I see that in this particular example with parameters in the following set {0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001}, the first two are estimated fine and the rest don't look good at all and similarly for the upper bound, but the solutions in the middle are very good. However, for the constrained case nothing is close.

variable transformation in optimization


How sizeof(std::cout) is 140 whereas sizeof(std::string) is only 4?

Question: Consider following program:
#include <iostream>
int main()
{
    std::cout<<sizeof(std::string)<<'\n';
    std::cout<<sizeof(std::ostream)<<'\n';
    std::cout<<sizeof(std::istream)<<'\n';
    std::cout<<sizeof(std::cout);
}

The output on my compiler(g++ 4.8.1) is
4

140

144

140

The output really confuses me. Why sizeof string class is only 4 bytes & for ostream & istream it gives 140 & 144 bytes respectively? The sizeof(std::cout)is 140 bytes that is same as sizeof(std::ostream). So, I think because cout object is of type ostream that's why I am getting output same here. right? Are these sizes compiler dependent?
Comment: Why do you expect any particular relationship between `sizeof(string)` and `sizeof(cout)`? What possible insight do you hope to gain by comparing the two?
Comment: As Igor points out, the question isn't very useful, hence downvotes.
Comment: @Downvoters: Why downvotes? What's wrong?
Comment: @PravasiMeet Because the question makes no sense. Your question boils down to "why is the size of A different from the size of an unrelated type B".
Answer: Basically it comes down to the fact that an iostream has quite a bit of state to store, but a string has very little.
Nonetheless, the idea of a string having a size of only 4 is a little surprising (at least to me). I'd normally expect something like 12 for a 32-bit implementation, or 24 for a 64-bit version.
In particular, a string will typically contain three things: a pointer to the actual buffer to hold the data (typically allocated on the free store), a size_t to contain the size of that buffer, and a size_t to contain the number of characters currently being stored. In a typical case, each of those will be 32-bits on a 32-bit implementation and 64-bits on a 64-bit implementation.
It's entirely possible to justify a string object that's somewhat larger than that as well--for example, it's fairly common to store the data for a small string directly in the string object itself ("short string optimization"). In this case, you might have space for (up to) something like 20 characters in the string object itself, which will typically increase its size still further.
Comment: The OP is using GCC 4.8, so this is the reference-counted copy-on-write implementation.
Comment: @Jerry Coffin: why sizeof std::cout,std::cin is compiler dependent? Do all the compilers implement stream objects differently?
Comment: @PravasiMeet: They don't have to, but they're free to do so.
Comment: @PravasiMeet: It means instead of the string object containing any information directly, each string object you create is just a pointer to the actual information. What it points at contains a count of the number of string objects referring to it, so it destroys itself when there are no more. When copy a string, it just increments the count and gives  back another pointer to the same data (and only copies the actual data when/if you modify it). This implementation was popular decades ago, but has lost popularity with multi-threading (and as of C++11 is no longer officially allowed).


syntax for nls model with breakpoint

Question: So the saga continues...
So I am trying to fit the model
$$Runoff = \begin{cases}
\beta_0 + \beta_1Pcp & \text{if $(Ant + Pcp) < Thold$;}\\
\beta_2 + \beta_3Pcp & \text{if $(Ant + Pcp) \geq Thold$;}
\end{cases}$$
Where $Pcp$ and $Ant$ are observed variables, and $Thold$ and the other parameters are estimated. I do not think I can do this with the segmented package, as the breakpoint is not in the predictor variables, but I think I should be able to do it fairly simply as a non-linear least-squares regression? I am not so good with the nls syntax, so any help would be appreciated
Comment: Because the two expressions on the right hand side are identical, the relationship between `Ant+Pcp` and `Thold` is irrelevant, leaving a standard linear model for `Runoff` in terms of `Pcp`. Most likely there is a typographical error: could you please fix it by editing the question? When you do so, consider giving information about the nature of the random component of `Runoff`, too, because that is crucial for applying any form of least-squares fitting.
Comment: I have updated the question - basically I expect a different linear  relationship depending on whether or not $Ant + Pcp$ reaches above an estimated threshold. For the initial pass assuming normal errors should be fine. Thanks. I think we have been around on a similar model before, I am obviously still struggling with my analysis.
Comment: you could try multivariate adaptive regression splines in `earth` package.
Comment: @forecaster Could you indicate how splines could be applied to this problem?  (It's not immediately evident how that would be done.)
Comment: Are you simply asking for R code / help w/ R code? Or are you asking if this type of thing can be done w/ NLS? Note that the former would be off-topic here, but the latter is on-topic. Please clarify your question.
Comment: Perhaps - for context - you could consider linking to your previous questions related to this data.
Comment: @Glen_b, [here](http://stats.stackexchange.com/questions/143394/help-constructing-a-simple-regression-model-with-a-breakpoint) is a link. Re: that post I re-thought my analysis and realized I could do without the parameter C, which I hoped would simplify things, but it appears the approach may be the same either way.
Comment: @IcebergSlim the link wasn't for my benefit; I found the previous questions before I asked. I was suggesting you put it into your question for the benefit of other people trying to follow your post. Giving interested readers more context helps.
Answer: In general this is such a nasty problem that we shouldn't apply automatic optimizers like nls in R.  However, it is easily solvable upon observing that the model is linear, and meets the assumptions of ordinary least squares (OLS) estimation, conditional upon the value of Thresh.  Therefore you can search for solutions reliably by systematically varying Thresh across a reasonable range of values.

To illustrate, I simulated some data of this form in R using the equivalent model
$$Y = \beta_0 + \beta_1 x_1 + \beta_2 I(x_2 \lt \tau) + \beta_3 x_1 I(x_2 \lt \tau) + \varepsilon$$
where $\beta_0, \ldots, \beta_3$ are the coefficients (but not the same as those in the question!), $I$ is the indicator function, $\tau$ is the threshold parameter, $x_1$ represents values of Pcp, $x_2$ represents values of Pcp + Ant, and $\varepsilon$ has a zero-mean Normal distribution of unknown variance $\sigma^2$.
Note that the (intercept, slope) parameters of the two lines are $(\beta_0, \beta_1)$ when $x_2\ge \tau$ and $(\beta_0+\beta_2, \beta_1+\beta_3)$ otherwise.
An estimate of $\tau$ is a value (which usually will not be unique) that minimizes the sum of squared OLS residuals.  This is equivalent to the maximum likelihood solution.  To show how challenging the problem of finding this estimate can be, I plotted the sum of squared residuals versus trial values of $\tau$.  The left-hand plot in the figure shows an example of this profile.  The optimal value of $\tau$ is marked with a vertical red dotted line.  Its jagged, locally-constant, non-differentiable pattern makes it almost impossible for nearly any general-purpose optimizer to find the minimum reliably.  (It could easily be caught in a local minimum far from the global minimum.  I applied optimize to this problem as a check, and in some examples that's exactly what happened to it.)
Given this estimate of $\tau$, the model is linear and can be fit via OLS.  This fit is shown in the right-hand plot.  The true model consists of two lines of slopes $\pm 1$ crossing at $(0,1)$ and the true threshold is $-1/3$.  In this dataset, $x_1$ and $x_2$ were nearly uncorrelated.  A strong correlation between them will make the estimates unreliable.

Orange squares and blue circles distinguish the cases $x_2 \lt \tau$ and $x_2 \ge \tau$, respectively.  The two subsets of data are separately fit with straight lines.
A full maximum likelihood solution can be obtained by replacing the sum of squared residuals by the negative log likelihood and applying standard MLE methods to obtain confidence regions for the parameters and to test hypotheses about them.

#
# Create a dataset with a specified model.
#
n <- 80
beta <- c(1,1,0,-2)
threshold <- -1/3
sigma <- 1
x1 <- seq(1-n,n-1,2)/n
set.seed(17)
x2 <- rnorm(n)
i <- x2 < threshold
x <- cbind(1, x1, i, x1*i)
y <- x %*% beta + rnorm(n, sd=sigma)
#
# Display the SSR profile for the threshold.
#
f <- function(threshold) lm(y ~ x1*I(x2 < threshold))
z <- seq(-1,1,0.5/n)*2*sd(x2)                   # Search range
w <- sapply(z, function(z) sum(resid(f(z))^2))  # Sum of squares of residuals

par(mfrow=c(1,2))
plot(z, w, lwd=2, type="l", xlab="Threshold", ylab="SSR",main="Profile")
t.opt <- (z[which.min(w)] + z[length(z)+1 - which.min(rev(w))])/2
abline(v=t.opt, lty=3, lwd=3, col="Red")
#
# Fit the model to the data.
#
fit <- f(t.opt)
#
# Report and display the fit.
#
summary(fit)
plot(x1, y, pch=ifelse(x2 < t.opt, 21, 22), bg=ifelse(x2 < t.opt, "Blue", "Orange"),
     main="Data and Fit")
b <- coef(fit)
abline(b[c(1,2)], col="Orange", lwd=3, lty=1)
abline(b[c(1,2)] + b[c(3,4)], col="Blue", lwd=3, lty=1)

Comment: @ whuber. Thank you, this will take me a bit to think about.
Comment: @ whuber. If I may, could you elaborate on the extension with MLE? I am in particular interested in confidence intervals around the threshold. Thanks for your time
Comment: The connection is this: whereas my code measures the goodness of fit in terms of $\sum_i(y_i-\hat{y}_i)^2$, the negative log likelihood is $\sum_i((y_i-\hat{y}_i)^2+\log(2\pi)+\log(\sigma^2))/2$: there is a multiplicative factor of $1/2$ as well as an additive factor that depends on the error variance $\sigma^2$. There are standard ways to translate changes in the log likelihood into confidence intervals or regions.
Comment: This is looking pretty good so far, thanks for the help

syntax for nls model with breakpoint


have I coded this incorrectly?

Question: I did some C programming couple decades ago.  I am trying to re-learn the language.  I wrote this.  I get something unexpected.  When I change the 'short int' to 'int', it seems to work.  Can anyone look at my code to see if anything is wrong with it or is this a compiler issue.  I am using gcc on Linux.
#include <stdio.h>

int main(void) {

    short int age = 0;
    short int num_1_yr_olds = 0;
    short int num_2_and_3_yr_olds = 0;
    short int num_above_3_yr_olds = 0;

    while(1) {

        printf ("Enter age: ");
        scanf ("%d", &age);

        if (age < 1) {
            break;
        }

        switch (age) {
            case 1:
                ++num_1_yr_olds;
                break;
            case 2:
            case 3:
                ++num_2_and_3_yr_olds;
                break;
            default:
                ++num_above_3_yr_olds;
                break;
        }
    }
    printf ("Number of 1 year olds = %d\n", num_1_yr_olds);
    printf ("Number of 2 and 3  year olds = %d\n", num_2_and_3_yr_olds);
    printf ("Number above 3 year olds = %d\n", num_above_3_yr_olds);
}

Input
Enter age: 1
Enter age: 1
Enter age: 1
Enter age: -1

Output
Number of 1 year olds = -1
Number of 2 and 3  year olds = 0
Number above 3 year olds = 0

num_1_yr_olds value is getting messed up.  I expected a 3, I get a -1.  The value of num_1_yr_olds  becomes a -1 regardless of input.
Answer: Your problem lies here:
short int age = 0;
:
scanf ("%d", &age);

You really need to ensure that your data types match your format string. The correct format specifier for a short int is %hd, not %d.
Some compilers will actually check this and warn you.
What's likely to be happening is that the misalignment of data and format string is causing the short int to become the "wrong" value hence the counts are being screwed up.

In more depth, for a two's complement, little-endian architecture like x86, scanning an int into a short may put the least significant half into age and the most significant half into num_1_year_olds (if it's adjacent to age in memory).
Graphically, it may be clearer to think of it like this:
                         shorts in memory
                     +-----------------------+
What scanf("%hd") =< |          age          | \
  will write to.     +-----------------------+  = What scanf("%d")
                     |    num_1_year_olds    | /    will write to.
                     +-----------------------+
                     | num_2_and_3_year_olds |
                     +-----------------------+
                     | num_above_3_year_olds |
                     +-----------------------+

So, when you enter 1, age becomes 1 and num_1_year_olds becomes 0.
Each time you do that, it increases num_1_year_olds because age is 1 but that will be overwritten by the scanf the next time you get input.
When you finally enter -1 (all 1 bits in two's complement), age becomes -1 and so does num_1_year_olds.
Then, because age is less than one, the loop breaks, and the values are what you see: {-1, 0, 0}.
Comment: That certainly worked.  I did realize it was memory issue, however not sure what caused it.  Has the %hd always been part of C?
Comment: @rpat: well, at least back to c89. It's even in my 2nd ed K&R (the ANSI one). Before that, well, I threw out those books a _long_ time ago.
Comment: Thank for sharing your wisdom.  I have a K&R dating back to 88.  I guess need to get rid of that.  Can you recommend a book?
Comment: @rpat, the book I use is the ISO standard, but that's because I know the simpler stuff, it's only the dark corners of the language I'd be looking up, and I've found the standard better for that stuff. I wouldn't recommend it to a beginner unless they were a serious masochist :-)
Comment: Having said that, I have an early edition of ABC at home which I remember being useful. See http://www.amazon.com/Book-Programming-4th-Edition/dp/0201183994 if you want to check it out.
Comment: @rpat Your K&R from 1988 is K&R 2nd edition; don't get rid of it, read it cover to cover.
Answer: Try
scanf ("%hd", &age);

Since age is of type short int.

have I coded this incorrectly?


JSTL c:set condition

Question: Need your help figuring this thing out.
Scenario:
On my JSP, I am trying to print
Season 1: ${season}

Season 2: ${season}

this prints fine the first time (Both seasons print as "winter" initially). Now I wanted to add an if condition to change season value like:
<c:if test="${temperature eq 'HOT' || 'VERYHOT'}">
       <c:set var="season" value="summer is here" />
 </c:if>

On executing this if condition, Season 1 changes to "summer is here" but Season 2 stays the same. Why it stays so?  Season 1 is part of page1.jsp and Season 2 is part of page2.jsp
  and they are included inside parentPage.jsp
Comment: What is the scope of `season`? Also, you change the `test` to be `${temperature eq 'HOT' || temperature eq 'VERYHOT'}`.
Comment: Is parentPage.jsp the one that contains the `` tag? How are you including page1 and page2?
Comment: Hi Matt, I kept it at default scope.
Comment: Mac, its page1.jsp that contain c:if
Answer: Two problems:
First, your comparison is not valid. The 2nd condition is always true. Fix it accordingly:
<c:if test="${temperature eq 'HOT' || temperature eq 'VERYHOT'}">

Second, you're storing the variable in the default page scope which is not shared among included JSP pages. Store it in request scope instead.
<c:set var="season" value="summer is here" scope="request" />

Update: as turns out per the comments, those JSPs do not participate in the same request. You should then grab the session scope (and be aware that this way the variable get exposed in all requests in all browser windows/tabs! this is not per-se desireable). You should only ensure that you're specifying the scope in every <c:set var="season">.
<c:set var="season" value="some value" scope="session" />

The EL expression ${season} will namely search for the first non-null attribtue in respectively the page, request, session and application scopes. So if you do a <c:set> without an explicit scope, then it will be stored in page scope and obtained in same page as such.
Comment: Thanks BalusC, I always wait for your reply as soon as I post a JSTL question ;) gonna give it a try
Comment: BalusC, still the same issue. going to try with session scope.
Comment: Should work fine. Perhaps your second include is physically included *before* the first include?
Comment: maybe I didnt explain well. This whole is not part of one request. Can I use session scope?
Comment: That was indeed not clear from the question. You told that the both JSPs are included in the same parent page. I updated the answer once again.
Comment: Thanks BalusC, I will accept your solution. I am going to post this same question for some modifications.

JSTL c:set condition


Spring 4 MVC @RequestMapping on URL with parameters

Question: I am trying to implement an inline search form (if that makes sense). Basically, I want two mappings for this page.
    @RequestMapping(value="/application", method=RequestMethod.GET)
    public ModelAndView view() {
        return new ModelAndView("application");
    }

    @RequestMapping(value="/application?search=t")
    public ModelAndView handleSearch() {
        CaseManager caseManager = new CaseManager();
        ModelAndView modelAndView = new ModelAndView("application");
        modelAndView.addObject("caseList", caseManager.getCaseList());

        return modelAndView;
    }

So, /application is the main page of the web app. It has a search bar where a user can enter a handful of search parameters. When they click on search, the table of results should get populated on the page. I went with this route with no luck. I end up getting a 404 on /application?search=t.
The button's href="WebappName/application?search=t"
Any assistance would be greatly appreciated! I am new to this whole web dev world and got kind of thrown into the fire.
Answer: You'll want to use the params argument to the @RequestMapping:
http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html?is-external=true
e.g.:
@RequestMapping(value="/application" params="search")

If you want to capture the param value and do something with it or
@RequestMapping(value="/application" params="search=t")

if you want to dispatch to a specific param/value combination (looks like the fit in this case).


Asynchronous update using MVVM?

Question: My model contains a large data object that I update from code-behind (currently this happens on the UI thread but I intend to do this in a worker later on). One of my windows has a viewmodel for this model and outputs this data object using an IValueConverter. The problem is that this conversion takes several seconds. Hence, I need my window to fetch this updated data asynchronously. How can this be done?
MyControl.xaml:
<UserControl.DataContext>
   <local:DataViewModel x:Name="dataViewModel"/>
</UserControl.DataContext>

Then in code:
// This triggers my value converter and blocks the UI for several seconds!
dataViewModel.HeavyObject = data;

Where should the multi-threading code go? Should it be part of the viewmodel or my value converter?
Answer: look at IsAsync="True" for your binding and also check PriorityBinding.
here you find more about PriorityBinding
Comment: Does this handle the case where the object is being updated twice in a row? I.e. the lengthy operation A starts, a new update triggers a new lengthy operation B, A finishes, B finishes. In this case A is not of interest!
Comment: I tried `IsAsync=True` and my converter seems to get a disposed value: [System.ObjectDisposedException] = {"Cannot access a disposed object."} ??
Comment: Can you tell us which object was disposed?
Comment: The value sent to the IValueConverter. I googled this and it seems converters should not perform lengthy operations. Instead, the conversion should take place in a worker thread issued by the viewmodel. Does this approach sound familiar? (Other than this, your hint of `IsAsync` suffices as answer.)
Comment: doin it at viewmodel is always better :)
Answer: Given a choice between your view-model and value converter, I'd vote for the view-model.  However, I'd much rather see your long-running operations in a repository or client-side service that are responsible for interacting with your data store.
Comment: It's common on a lot of the projects I work on :).  It puts the responsibility of data interaction into a dedicated local "service".  This service can be used by the entire app or it can be more granular: say, one per view-model.  If you're familar with MVC, it's a lot like a repository.  I don't know of any tutorials, but Dino Esposito uses this, so maybe a search will yield some good results.
Comment: Client-side service? Is this a common pattern? Do you know of some good tutorials on this?

Asynchronous update using MVVM?


Remote Desktop to a specific server works on one computer but not on another

Question: (Also posted on StackOverflow and SuperUser)
I am finally switching from a desktop to a laptop at work.
I use Remote Desktop quite a bit to access our server (Windows Server 2008 R2 Standard).
I can access the server from the desktop (Windows 7 Enterprise, 32 bit), but when I try from the new laptop (Windows 7 Enterprise, 64 bit), I get past the login screen and then I keep seeing the Configuring remote session... message continuously and the Remote Desktop session never starts.
I have admin access on all devices so that's not the issue.
I don't have problems with the firewall when using other computers with my account.
I did a little research but nothing I've read seems to relate to my situation. I have tried the following:

Renaming %windir%\system32\mstsc.exe to mstsc.OLD and running the 32 bit mstsc from %windir%\SysWOW64\mstsc.exe but didn't have any luck.
Connecting FROM the server TO the laptop works fine.
Created a batch file with the following and still no luck:
@echo off
set WinDir=
start C:WindowsSysWow64mstsc.exe

Comment: Can you connect via RDP to another server instead of that one?
Comment: What about trying the version under C:\windows\system32\mstsc.exe instead of Syswow folder?
Comment: The version in system32 is actually the 64 bit version.  The one in SysWOW64 is the 32 bit version.  Counterintuitive, but that's the way Microsoft set it up.
Comment: Yep.. did you try it?
Comment: No...when you run the 32 bit (without renaming the 64 bit), it actually closes and runs the 64 bit by default.  But I'll give it a shot anyway.
Comment: @BobStout aah .. didn't know that bit :)
Comment: @Aaron:  The laptop does have SP1.  Didn't see that until you asked.
Comment: @esserafael:  No.  Can't connect to the desktop that I was using before the laptop, anyway.
Comment: @Aceth:  No joy on using the mstsc in /windows/system32, either.
Comment: Any local firewall's on the laptop? e.g. mcafee (I HATE that thing)?
Comment: @Aceth:  Not that I'm aware of.  Regardless, the firewall settings are controlled via group policy and it should be the same policy on the laptop as is on the desktop (that I can connect with).
Comment: Is your DNS server set correctly?
Can you ping those servers from your laptop?
If your firewall is controlled via GPO, verify if isn't something different there..
Try disabling all local resources when connecting with mstsc
Comment: I believe so, since I can connect via the desktop, and connect TO the laptop from both the server and the desktop.
Comment: I mean the DNS servers configured on your laptop, checking if it is getting the right addresses..
Comment: @esserafael:  Doing IPCONFIG, it looks the same as the desktop.  However, when one of our network guys comes back from lunch, I'll confirm that the DNS servers are configured correctly with him.
Comment: @esserafael:  We use DHCP instead of DNS, according to our tech.  So, according to him, it's not a factor in the problem.
Comment: Is NLA required on the server? Is your new laptop set to RDP using NLA? If you don't/can't answer that, then I suggest you contact your IT guy.
Comment: A little tangent - what do you mean by "DHCP instead of DNS" - they aren't comparable :\
Comment: But DHCP and DNS are two different things, maybe your tech meant that the DHCP automatically configures DNS settings on your laptop.
Comment: @out-null:  No, NLA is not required.
Comment: @esserafael:  Exactly what he meant.
Comment: None of the Questions here would have anything to do with a connection freezing after login. Did you guys read the Question? Bob, is your Laptop upgraded to the latest [RDP Client](http://support.microsoft.com/kb/2592687) and are all Windows Updates installed (check in the control panel)?
Comment: Yes I read, now I realized the "Configuring remote session" part is after the credentials, in my mind I was thinking about it before, so it could be connection/name resolution problem.

In the mstsc, try unchecking everything in Local Resources tab, like printers, drivers, etc. And in Remote Audio Settings select "Do not play" and "Do not record". Then test what happens.
Comment: @ChrisS:  I'm missing one update (per our techs, no biggie, doesn't involve RDP).  Also have the latest RDP Client.
Comment: Did you get any further with this?
Comment: @Aceth:  No, I haven't.  Quite frustrating.
Answer: Turns out it was the audio driver that was causing the problem.  I deleted the RealTek driver that was being used and used the generic windows one, and was able to connect with Remote Desktop with no issues.
Comment: On which machine? The client or the server?
Comment: On the client machine.


How to hide empty 'Content Zone' div in Omega?

Question: I'm using Omega and I have "Force this zone to be rendered" unchecked in the Content Zone settings, and "Force this region to be rendered" unchecked in the Regions settings.
Any idea what would force this zone to be rendered even if there's no content? The zone is outputting this:

Answer: Probably because you have the debug placeholders blocks activated?
There is a checkbox "Enable the debugging (placeholder) blocks" in Appereance > subtheme > settings > debugging tab.
The zones are rendered even if empty.
I suggest you try with this option turned off.


Node creation fields in blocks

Question: I am using Display Suite for node creation, but would like to extend this by also using blocks provided by theme to put several fields inside them too (sidebar left and right).
How to accomplish this ?
Answer: You may need to enable the Display Suite Extras module. (comes with display suite)
Go to manage display, scroll all the way down. Click on custom fields, add a block field.
Comment: That is for display. I am looking for node creation solution.

Node creation fields in blocks


indexing past the end of C arrays

Question: I wrote a short program in C just to see what happens when you index past the end of an array.
I found that it mostly produces random values (I know they are not actually random) up until a point (52 indexes past the end in this case) where it produced 0 every single time. Every value past this point and the program crashes. Why is this? is it the end of the programs allocated memory space?
main()
{
    int ar[4];
    ar[0] = 99;
    ar[1] = 45;
    printf("array: %d, %d   random value: %d", ar[0], ar[1], ar[55]);
}

Edit: I also found that if I alter this value that always ends up being 0 (i.e. ar[55] = 1000) then the return code for the program goes up.
Comment: That's undefined behavior!!! The C language standard does not dictate the behavior of your program following this operation (in oppose to Java `IndexOutOfBound` exception, for example).
Comment: http://stackoverflow.com/questions/15646973/how-dangerous-is-it-to-access-an-array-out-of-bounds
Comment: It fall out the stack, crashes. If you try to read an existent address crashes. If it fall out the heap crashes. If try to write out the bondaryes, damages the memory handler
Answer:
... just to see what happens when you index past the end of an array

Trying to access out of bound memory, invokes undefined behavior. Anything can happen, just anything.
In your case, for some reason, the memory address for upto index 52 is accessible from the process, so it allows the access. Index past 52 points to a memory region not allocated to your process address space and thus, raises the access violation leading to segfault. This is not a deterministic behaviour, at all and there's no way you can rely on the output of a program invoking UB.
Comment: @b9703 read this well: http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html
Comment: So is it certain that this 0 value is unrelated to the program e.g. some quirk of the operating system or compiler
Answer: Accessing array elements beyond array boundaries (before 0 or from its size up) is undefined behavior. It may or may not produce values, it may cause the program to end abruptly, it may cause your system to stop, restart or catch fire...
Modern systems try to confine undefined behavior within reasonable limits via memory protection, user space limitations etc. but even user space code errors can have dire consequences:

pacemaker messing with its timing values can cause premature death ;
banking software overflowing array boundaries can overwrite account balance information crediting some random account with untold amounts of dollars.
your self driving car could behave worse than drunk drivers...
think of nuclear power-plant control software, airplane instruments, military stuff...

There is no question undefined behavior should be avoided.
Regarding the exit status, your program uses an obsolete syntax for the definition of main(), implicit return type, which is no longer supported in C99 and later, but does not return anything, which means its return value can be any random value, including a different value for every execution. C99 specified a kludge for the main() function and forces an implicit return 0; at the end of main(), but relying on it is bad style.
Similarly, invoking printf() without a proper prototype is undefined behavior. You should include <stdio.h> before the definition of function main().
Lastly, ar[0] and ar[1] are initialized in main(), but ar[2] and ar[3] are not. Be aware that accessing uninitialized values also has undefined behavior. The values can be anything at all, what you describe as random values, but on some systems, they could be trap values, causing undefined behavior by just reading them.
Some very handy tools are available to track this kind of problems in simple and complex programs, most notably valgrind. If you are curious about this subject, You should definitely look at it.

indexing past the end of C arrays


regex replace '...' at the end of the string

Question: I have a string like:
text1 = 'python...is...fun...'

I want to replace the multiple '.'s to one '.' only when they are at the end of the string, i want the output to be:
python...is...fun.

So when there is only one '.' at the end of the string, then it won't be replaced
text2 = 'python...is...fun.'

and the output is just the same as text2
My regex is like this:
text = re.sub(r'(.*)\.{2,}$', r'\1.', text)

which i want to match any string then {2 to n} of '.' at the end of the string, but the output is:
python...is...fun..

any ideas how to do this?
Thx in advance!
Answer: You are making it a bit complex, you can easily do it by using regex as \.+$ and replace the regex pattern with single . character.
>>> text1 = 'python...is...fun...'
>>> new_text = re.sub(r"\.+$", ".", text1)
>>> 'python...is...fun.'

You may extend this regex further to handle the cases with input such as ... only, etc but the main concept was that there is no need to counting the number of ., as you have done in your answer.
Answer: Just look for the string ending with three periods, and replace them with a single one.
import re
x = "foo...bar...quux..."
print(re.sub('\.{2,}$', '.', x))
// foo...bar...quux.

Comment: This will only replace exactly three .'s.
Comment: Updated to replace 2 or more .'s with a single one.
Answer: import re
print(re.sub(r'\.{2,}$', '.', 'I...love...python...'))

As simple as that. Note that you need to escape the . because otherwise, it means whichever char
except \n.
Answer:
I want to replace the multiple '.'s to one '.' only when they are at
  the end of the string

For such simple case it's easier to substitute without importing re module, checking the value of the last 3 characters:
text1 = 'python...is...fun...'
text1 = text1[:-2] if text1[-3:] == '...' else text1

print(text1)

The output:
python...is...fun.


If all pairs of addends that sum up to $N$ are coprime, then $N$ is prime.

Question: I think this must be a known theorem, but I've tried searching for it on google without much luck.  I would state it as follows:
If for all possible pairs of addends that sum to the same number N each of those pairs is comprised of two numbers that are coprime, then N is prime.
It is the inverse of that which was discussed/proved here:
If the sum of positive integers $a$ and $b$ is a prime, their gcd is $1$. Proof?  Instead of starting with a prime number and wanting to prove that any two numbers summing to it are coprime, in this case I'm starting with a set of addend pairs that sum to the same number, noticing that those addend pairs are always coprimes, and wanting to come to the conclusion that the common sum must be a prime.
I would also like to know what this theorem is called if it is indeed a known theorem.
Comment: Thanks for the proofs below, but it's more that I'm looking for someone to attribute/cite.
Comment: What do you mean? If you must, you can cite us. It's a two-line proof.
Answer: I do not think it has a name, but we can prove it right now. We will prove it by proving the contrapositive:

If $N$ is not prime, then there exists a pair of addends $X,Y$ summing to $N$ such that $X$ and $Y$ are not coprime.

Proof:
Let $N = ab$ where $a, b> 1$ (since $N$ is composite). Then we can take $X = a(b-1)$ and $Y = a$, so that $X + Y = ab = N$ and $\gcd(X,Y) = a > 1$. This completes the proof. $\diamondsuit$
Answer: Hint: If a number is not prime, say $n = ab$ where $a,b > 1$, what can you say about $b$ and $(a-1)b$?


Localization - Hello World Example

Question: I am extremely tired right now and don't have time to read through verbose drupal 7 documentation.  Can someone just show me a quick Hello World example that will do the following in drupal 7?
I have a template file /sites/all/themes/mytheme/page.tpl.php and in it I have
<?php echo "Hello World"; ?>

When a person comes to the page in English, it should show "Hello world".  When the person comes to the page in French, it should show "Bonjour tout le monde".  How do I augment the command echo "Hello World" to do such a thing?  If language files are needed, show me how to structure them.
Thanks
Answer: Instead of "Hello World", use t("Hello World").
Using the Localization client module, you can add the translation of that string in any language you want.

This module helps you fix translations on your site as you see the issues. Just by navigating around your pages, you'll be able to fix translations and fill in missing ones using the on-page translation editor. At the same time, if configured properly, the module also submits your translations back to the community, to localize.drupal.org or any other localization server.
Comment: You don't need a third party module to change localised string. Drupal core has this built-in: you can either change a few strings in settings.php or enable the core translate-interface module.
Comment: I see that I already have the t() function available..but where do i find the data file that houses all my translations?  LIke some kind of xml dictionary look up for each language equivalent word or something?

Localization - Hello World Example


Negative Offset in Rate (Poisson or Negative Binomial) models

Question: I have a dataset that contains:

the counts of successes, $Y_i$
the length of observation, $\text{length}_i$
few predictors, $X_1, X_2, \text{etc}$

Since the counts are observed at different lengths I need a rate model. For the Poisson regression we achieve this by writing:
$\log(\mu_i /\text{length}_i) = \beta_0 + \beta_1 X_1 +\beta_2X_2$
which is then rewritten as:
$\log(\mu_i) = \beta_0 + \beta_1 X_1 +\beta_2X_2 + \log(\text{length}_i)$
The $\text{length}_i$ is the offset and it has a fixed coefficient of 1. In R we specify it using the offset method. Something like this:
model <- glm(Y ~ offset(log(LENGTH)) + x1 + x2, data = data, family = "poisson")
However, I get better prediction results when I specify the offset as having a coefficient -0.5. That is:
model <- glm(Y ~ offset(-0.5 * log(LENGTH)) + x1 + x2, data = data, family = "poisson")
This would mean that the mean is related to the predictor variables like:
$\log(\mu_i * \sqrt{\text{length}_i}) = \beta_0 + \beta_1 X_1 +\beta_2X_2$
I have a few questions:

Why am I getting better results using negative coefficient?
What are the possible theoretical explanation for a negative offset?
Should I try some other model?
Comment: I have a question for you. You said that you are getting "better prediction results". So you are comparing these two models. But this means that you are fitting your Poisson-regression model into two different response variables. One is $log(Y/L)$ and the other one is $log(Y\times\sqrt{L})$. In other words, your data-sets are not the same. So I think, it does not make any sense to compare like that.
Comment: The prediction results are better no mater the dataset. I tried predicting on 4 different dataset (including the original dataset) and in all cases the results are better. It seems that $log(Y*\sqrt{L})$ is a better response variable but it is difficult to explain why this is the case.
Answer: Unfortunately, you've gotten the model itself wrong.  With general linear models, you're modeling the mean demand, not the variate itself; the link between the two is the assumed probability distribution of the variate given the mean demand.  Hence, defining $\mu_i = \mathbb{E}Y_i$, the model would be:
$\log \mu_i - \log \text{length}_i = \beta_0 + \beta_1X_1 + \beta_2X_2$
If you run the glm with length as a right-hand-side variable, instead of an offset, you can test to see if the coefficient is significantly different than -1.  If it isn't, then you don't have a problem.  If it is, then you may have just gotten unlucky with your data set, or your model may be misspecified in such a way that the coefficient contains information, or there's overdispersion, in which case the standard errors of your parameter estimates are biased.  You can usually capture some, if not all, of this effect by running a negative binomial regression instead.  That won't change the parameter estimates, but it will change their standard errors, perhaps enough so that the coefficient of length is no longer significantly different than -1.
If the coefficient remains significantly different than -1, you'll have to think carefully about what is actually being modeled, and how the data is being recorded.  There are too many possible causes to list without that knowledge (which I don't have.)
Comment: You are right about the model. I did more reading and corrected the equations.
I also tried using the negative binomial regression and the results are the same. I always get better prediction when I set the coefficient for $length$ to be -0.5. If I allow the model to estimate it estimates it to be 0.36.
Comment: What are you modeling?  It might help my speculation as to why this would be if I knew that...
Answer: In general if you're interested in predicting a count then there's nothing problematic about having log(exposure) as just another covariate and allowing its coefficient to be estimated from the data.  Although it's probably clearer to just drop to say
 model <- glm(Y ~ log(LENGTH) + x1 + x2, data = data, family = "poisson")

A simple case where this would be the right thing to do is when the underlying rate is not constant over exposure.
Also, you don't say what your measure of predictive success is.  I'm wondering if the counts that you are predicting are relatively low and your success measure is something symmetrical, like MSE.  In that situation, prediction may be better according to the criterion if the model generates forecasts that are actually biased.
I'd guess the things to do is to check that the the curious 0.5 business is still preferred if the criterion is probability of the data, or some non-symmetrical measure.
Finally (and assuming when you say predict you are doing out-of-sample prediction) it's possible that you are overfitting on the training data and would predict better if you had managed not to.
Comment: I did try adding the `log(LENGTH)` but the estimated coefficient is about +0.36.

The data is very messy and large dataset (30,000 points).

Both the counts and the length are very skewed distributions. The counts has a very large amount of excess of zeroes:
` Min.  1st Qu.   Median     Mean  3rd Qu.     Max. `
` 0.0000   0.0000   0.0000   0.5059   1.0000 131.0000`
Comment: Also, I am doing out of sample prediction that is I fit the model on one dataset and use it to predict on three other datasets. I also checked the predictions on the same dataset on which the model was fit and the results are consistently better with a negative coefficient.

Can you tell me more about forecasts that are biased. What is it and how can I incorporate it.

Unfortunately, I can't disclose the dataset but I can give an example that might help. Let's say the LENGTH is number of words in a file and the count is number of curse words.
Comment: My measure of better prediction would be to rank the files so that we can find the highest number of obscene words by examining as little words as possible. In other words, I am more interested in files with high density of obscene words.
Comment: You haven't yet said what doing better means.  You fit the model to one set of data, then you apply the model to new covariates, get the expected count and compare it to the observed count... how?


org.scala-sbt#sbt;${{sbt.version}}: not found on existing project

Question: I've copied a Play framework Scala project from git and when I launch the command $Play, I got this error:
Getting org.scala-sbt sbt ${{sbt.version}} ...
:: problems summary ::
:::: WARNINGS
            module not found: org.scala-sbt#sbt;${{sbt.version}}

    ==== local: tried

      D:\play-2.1.0\repository\local\org.scala-sbt\sbt\${{sbt.version}}\ivys\ivy.xml

    ==== Maven2 Local: tried

      file://C:\Users\mghesmoune.stage/.m2/repository/org/scala-sbt/sbt/${{sbt.version}}/sbt-${{sbt.version}}.pom

    ==== typesafe-ivy-releases: tried

      http://repo.typesafe.com/typesafe/ivy-releases/org.scala-sbt/sbt/${{sbt.version}}/ivys/ivy.xml

    ==== Maven Central: tried

      http://repo1.maven.org/maven2/org/scala-sbt/sbt/${{sbt.version}}/sbt-${{sbt.version}}.pom

            ::::::::::::::::::::::::::::::::::::::::::::::

            ::          UNRESOLVED DEPENDENCIES         ::

            ::::::::::::::::::::::::::::::::::::::::::::::

            :: org.scala-sbt#sbt;${{sbt.version}}: not found

            ::::::::::::::::::::::::::::::::::::::::::::::

:: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS
unresolved dependency: org.scala-sbt#sbt;${{sbt.version}}: not found
Error during sbt execution: Error retrieving required libraries
(see D:\play-2.1.0\framework\.\sbt\boot\update.log for complete log)
Error: Could not retrieve sbt ${{sbt.version}}

I'm using Play-2.1.0, sbt launcher version 0.12.2 (and Windows OS)
How to fix this problem ?
Comment: .. Or checked this thread? http://stackoverflow.com/questions/16327123/error-module-not-found-org-scala-sbtsbtsbt-version
Comment: Have you tried to run sbt standalone? It might look like sbt is not properly resolved.
Comment: I had this problem. I had accidentally added `project/` to `.gitingore`. After cloning the `project` directory was omitted, and this error was being thrown.
Answer: This can happen if you run the play command from a directory that contains an project directory with some SBT settings in it.  Try to either remove the project directory (but not the one in your app), or move to another directory to run the command.
Comment: Thanks, this worked for me!  Had an empty project directory in my current directory.
Comment: from james ward - typesafe developer advocate.
Answer: There is an answer here: Error: module not found: org.scala-sbt#sbt;${{sbt.version}}
Basically, create a project/build.properties file if one doesn't exist with the following content:
sbt.version=0.12.2


Fourier transform of double exponential function

Question: As the title states, I'm currently trying to compute (or "prove") the Fourier transform of the double exponential function (or Laplace function), that is
$$\int_{-\infty}^{\infty}e^{i\xi x}e^{-\lambda|x|}\,dx = \int_{-\infty}^{0}e^{i\xi x}e^{\lambda x}\,dx+\int_{0}^{\infty}e^{i\xi x}e^{-\lambda x}\,dx$$
which clearly leads to the following result after a few simple integration rules:
$$\left[\frac{e^{i\xi x}e^{\lambda x}}{i\xi+\lambda}\right]_{-\infty}^{0}+\left[\frac{e^{i\xi x}e^{-\lambda x}}{i\xi-\lambda}\right]_{0}^{\infty}=\left(\frac{1}{i\xi+\lambda}-\frac{\lim_{x\to-\infty}e^{i\xi x}e^{\lambda x}}{i\xi+\lambda}\right)+\left(\frac{\lim_{x\to\infty} e^{i\xi x}e^{-\lambda x}}{i\xi-\lambda}-\frac{1}{i\xi-\lambda}\right).$$
Now, it's quite obvious that
$$\lim_{x\to-\infty}e^{\lambda x}\to 0\quad \text{and} \quad \lim_{x\to\infty} e^{-\lambda x}\to 0.$$
However, I'm struggling with interpreting what
$$\lim_{x\to-\infty}e^{i\xi x}\quad \text{and}\quad \lim_{x\to\infty}e^{i\xi x}$$
lead to since the textbook that I'm using seems to neglect this detail and simply reaches the result of
$$\frac{2\lambda}{\lambda^{2}+\xi^{2}},$$
which is naturally a Cauchy function.
Therefore, what would I do with $e^{i\xi x}$ when computing the two respective limits shown above for the definite integral? Any kind of help would be highly appreciated.
Answer: While you didn't write this, it is important to note that $\lambda$ is a non-negative real number.
The term $e^{i\xi x}$ is a purely imaginary exponential, and as such lies on the unit circle in the complex plane (by Euler's famous formula). In particular, it is bounded in absolute value. Combined with your observations, it follows that the limits at infinity vanish (because the rest of the factors being multiplied decay to zero).
As I am sure you are aware, it is the endpoints at $0$ that are more interesting (and yield the formula you seek).
Comment: I didn't interpret it as a unit circle initially, but what you say makes complete sense, thank you!
Answer: There is no $\lim_{x\to\infty}e^{i\xi x}$. But that doesn't matter. The function $x\mapsto e^{i\xi x}$ is bounded, so since $\lim_{x\to\infty}e^{-\lambda x}=0$ then also $\lim_{x\to\infty} e^{i\xi x}e^{-\lambda x}=0$.
The general principle is that if $\lim_{x\to a}f(x)=0$ and $g(x)$ is bounded as $x\to a$, then $\lim_{x\to a}f(x)g(x)=0$.
Comment: Thanks a lot! Does this property have any specific name? I'd like to do a bit more research on it.
Comment: (Off topic) Please reconsider the deletion of your answer to another question ( https://math.stackexchange.com/q/3417450). It's a good answer, and the accepted answer to the question is wrong.
Answer: To be a little more precise than previous answers, you have the following:
$$0 \le |e^{i\xi x}e^{\lambda x}| \le e^{\lambda x}$$
since $|e^{i\xi x}| = 1$, so if $e^{\lambda x}\to 0$, then $e^{i\xi x}e^{\lambda x} \to 0$ by the squeeze theorem. Particularly, assume that $\lambda < 0$, then
$$ 0 = \lim_{x\to\infty} 0\le \lim_{x\to\infty} |e^{i\xi x}e^{\lambda x}| \le \lim_{x\to\infty} e^{\lambda x} = 0.$$
Since $0 \le \lim_{x\to\infty} |e^{i\xi x}e^{\lambda x}| \le 0$, you have that $|e^{i\xi x}e^{\lambda x}|\to 0$ and so $e^{i\xi x}e^{\lambda x}\to 0$.
Comment: That's a really intuitive way of perceiving this problem - I would have never thought of applying the squeeze theorem to solve it, thank you!


How to reload code in Julia 1.5 when using the REPL?

Question: Sorry for the basic beginner question but I'm really struggling with a problem concerning Julia and it's REPL.
I want to use the "MATLAB like" workflow of trying and coding at the same time. I just want to split code/functions among multiple files and combine them in a script:
include("file1.jl") # defines Module1
include("file2.jl") # defines Module2

using .Module1
using .Module2

But somehow it seems to be impossible to reload code defined in those modules without restarting the REPL. I tried using Revise.jl and the "tracking include" includet but it doesn't work for me.
Does someone had a similar problem and found a working solution?
This problems seems to occur frequently (e.g. here) and it's annoyance is amplified by the slow startup time / recompilation time of Julia.
Update
Ok, maybe I was a bit quick with my post on Stackoverflow. I made some experiments and now for me I discovered:

If the using is avoided it works much more reliable.
Then includet as well as include works
Especially constants are a problem and cannot be redefined once in global namespace (?)
Comment: Can you specify, what exactly didn't work when you were using `includet`? Also, what do you mean by "it seems impossible to reload code without restarting the REPL"? What is happening, when you are changing contents of `file1.jl` and execute `include("file1.jl")` again?
Answer: Tasos Papastylianou's answer works.
If you have a module say, called Mymod, file name is Mymod.jl.
At first you do a
include("Mymod.jl")
using Mymod

Then you changed Mymod.jl a little, to reload Mymod to reflect the changes, you simply do the include("Mymod.jl") and using Mymod again, I mean just repeat
include("Mymod.jl")
using Mymod

This time the Mymod is reloaded, and you will see the changes you made.
At least it works for Julia 1.6.1. You do not have to use packages like "Revise".
Answer: If you just keep function definitions in your files, then these should get overwritten / redefined when you include the file again.
If your files are modules, you don't need to do using to use it. When you include the file, the module will get "defined" locally as if you had typed it in your REPL. Just use its functionality with the module name as an identifier. If you change the module in your file and 'include' it again, julia will warn you that it's replacing the module with a new one of the same name, and that's that.
There are a couple of things to note regarding the use of 'include' within scripts, to do with World Number etc ... but in the context that you are talking about, which is replicating matlab/octave workflow in the REPL, this should not be a problem.


Breakpoint not being hit while debugging WCF application

Question: I have a WCF application and a console application.
I published WCF application in a separate folder. Added a Virtual Application in IIS.
In console application, I added a Service Reference to the site added in IIS.
With this, I am unable to debug WCF application and the breakpoint is not hitting.
I opened two instances of VS. In once instance, I executed WCF application and in the other, the console application.
Why the WCF breakpoints not hitting?
Comment: Yes, the same address needs to be used. Otherwise it is not the service you can/want to debug with VS. I will post an answer for this. With and without using service references.
Comment: Why did you publish the WCF application to IIS? For me it is not clear why you are having this step at least for the development. It is enough to start the WCF application through VS. Then use this address for your console client application.
Comment: @Marc Which address ? The localhost address the WCF application shows in browser? The same has to be added as Service Reference ?
Comment: @Marc The WCF application, opens with the address: http://localhost:52099/. I tried to add this as the Service Reference in console application, but the reference is not found.
Answer: There is no need to publish the WCF application manually to an IIS for development/debugging purposes. The hosting part is already built-in into Visual Studio.
If you want to connect a client application to a WCF Service, there are two ways I can think of:
Method 1: Use a Service Reference
That is the quickest approach and works in most cases out of the box (You have chosen this one).
You need to have a solution file with client and server projects similar to this one:

In the "Add Service Reference" Dialog, click "Discover". This will look for WCF services in your solution (this services don't need to be started).
Side note: If you click on "Go", only a started service can be found.

You should see your service in the "Services" section and the Address Field is automatically filled out for you with the address Visual Studio will use for local debugging.

Continue adding the service as you always do...
Visual Studio will automatically update the client's app.config file.
If you start the console application only, Visual Studio will also start the service in background for you. You are able to step into the service operation by hitting F11 without explicit setting a breakpoint.
Method 2: Without using service references
Clicking on "Add service Reference" will generate code based on the current data contracts. If you change that definition (types, operations, etc.), you have to generate it again.
If you are the owner of both, client and service, then you can create a dynamic proxy at runtime using WCF Channelfactory.
You have to extract the Service contract and Data contracts only to a new assembly and share it with client and server.
There is no code generation necessary and this way you will always be safe at compile time.
See here for more information.
Because VS is not aware of any service references, you have to start both projects by yourself. Just set multiple startup projects in your solution and press F5.
But in this case, you have to set a breakpoint in your service application.
Comment: I tried the first approach. Added WCF to the same solution and added service reference.

I am getting error: Method 'GetOrders' in type 'SMService.ServiceImplementation.SMTransactionService' from assembly 'SMService.ServiceImplementation, Version=220.127.116.11, Culture=neutral, PublicKeyToken=null' does not have an implementation.

I am unable to find the Interface in all the projects which does not have an implementation.


Can someone explain this cartoon?

Question:
I ran 160 regressions on various combinations of data sets, predictors, and dependent variables. I am now trying to sift through the results and separate good models which are "real" versus those which are due to random chance. My professor sent me this cartoon. It seems to be implying that by using $\alpha = 0.05$, you are highly likely to get significance in 20 data sets.
Questions:

Does random data have a 0.05 probability of being significant at $\alpha = 0.05$?
In other words:

$$\Pr(sig>0.05|n=20) = 1 -(1-0.05)^{20} = 0.6415$$
Not exactly a guarantee as suggested by the cartoon.
Is the above calculation true for regressions?

Is there a word for this "random correlation" so I can do further research?
Comment: **Your professor is using a humorous cartoon to warn you about the trap you have stepped into. Don't try to argue with the cartoon instead of heading the warning. You're right to want to learn more about the problem: http://semanticommunity.info/@api/deki/files/30744/Elder_Target_Shuffling_Sept.2014.pdf **
Comment: 1. Yes, or more generally "if the null hypothesis is true." Random data do not always mean zero difference or zero correlation (aka you can have randomly generated data that are correlated at r = 0.8); 2. Why are you computing them as if they are dependent events? In the cartoon all 20 tests are independent events. 3. Usually it's called "Type I error" or "false positive."
Comment: Thanks @Wayne, that presentation is extremely clarifying.
Comment: Argh, I though it was a paper, but it's a slide deck. Should've looked closer. I hope you did get something out of it, since a lot of detail is left out of the slides to give the speaker room to talk. Bottom line is, even with the binomial math you did -- which isn't quite what you think it is -- the odds are almost 2:1 (0.6415 v 0.3585) that you have a problem. Would you listen to a lecture where someone started with, "the odds are 1 out of 3 that what I found might be real!" (Apply your math to your 160 regressions and the odds explode.)
Comment: @Wayne ,you hinted that the binomial math I did is not right. Why? Is is because the trials are not independent? I can see how a regression of X1 vs Y1 would not be independent of a regression of X1 vs Y2. If this is the issue, is there a way quantify the probability of getting a Type I error in n trials?
Comment: You are calculating the probability of exactly one occurrence, rather than the probability of one or more occurrences. And it's more subtle than that because we're dealing with a frequentist concept here and $\alpha=0.05$ does not mean what we might want it to mean. The cartoon's point is that, in layman's terms, if you allow that your significance test can be wrong as often as 5% of the time, you shouldn't be surprised when it is wrong 5% of the time (i.e. 1 of 20). Again, frequentist concepts are tricky so _technically_ the previous sentence may be a mis-statement, but as a concept it's fine
Answer: Your calculation is right assuming the p-values arise from data that are independent and arise from sufficiently large datasets (so that the p-values are really approximately uniformly distributed under the null hypothesis). If the data are not independent (e.g. when all people who were randomly assigned to eat a certain color of jelly bean are compared to a single group of people assigned to eat no jelly beans, or if people that ate red jelly beans are compared to people that did not eat jelly beans both in terms of occurrence of acne, cancer or death), things are also more complicated.
Thus, you are right that there is no guarantee that amongst 20 comparisons conducted under the null hypothesis there would be at least one type I error and the familywise type I error rate you calculated is exactly right. However, in case of 160 comparisons the familywise type I error rate should be very close to 100%. There are a number of possible ways to deal with this type of multiplicity. These include testing procedures that control the familywise type I error rate (e.g. the Bonferroni-Holm procedure) or the false discovery rate. I have also seen some Bayesians argue for (implicit) shrinkage approaches using some kind of hierarchical Bayesian model and there are almost certainly further things one could do.

Can someone explain this cartoon?


how to prevent navigation to previous screen and show exit confirm message on back button tap

Question: i am creating a quiz app in witch: when use choose an answer user will be navigate to next screen.
what i want begins here:
i want to prevent user to go back to previous screen,
if user try to go back to previous screen by taping back button, a exit confirm message should appear.
if user choose "OK" the app should close and if user choose "CANCEL / (Continue Quiz)" the app should continue from current screen.
Answer: You need to override in your activity onBackPressed in this way
    @Override
public void onBackPressed() {
    AlertDialog dlg = new AlertDialog.Builder(YourActivity.this).create();
    dlg.setCancelable(false);
    dlg.setTitle("CLOSE");
    dlg.setMessage("Are you sure?");
    dlg.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    dlg.setButton(DialogInterface.BUTTON_POSITIVE, "CLOSE APP", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            YourActivity.super.onBackPressed();
        }
    });

    dlg.show();
}

Comment: I would recommend using `ActivityName.super.onBackPressed()` instead of `finish()` in the onClick for the positive button.
Answer: You can override the onBackPressed() function in your Activity.
@Override
public void onBackPressed() {
    // code for displaying confirm message here
}

This answer has sample code for creating a confirmation dialog box: https://stackoverflow.com/a/6413736/379245


What is the interpretation of a "collider" within graphical causal inference, in the potential outcomes framework?

Question: I have recently been reading more on graphical causal models and the term collider often comes up. I am wondering if there exists an interpretation for what it is in the potential outcomes framework.
Answer: I find the definition in Hernan & Robins's forthcoming book (Causal Inference pg 101) to be useful

[Colliders are] a common effect of two other variables in the diagram ... We will use the term selection bias to refer to all biases that arise from conditioning on a common effect of two variables, one of which is either the treatment or a cause of treatment, and the other is either the outcome or a cause of the outcome.

There several example causal diagrams show how it is easier to approach "colliders" from a graphical persepective. You can also frame colliders in terms of single-world intervention graphs (SWIG) which explicitly links the causal diagram and potential outcome approach.
Let $A$ be the treatment of interest and $Y(a)$ be the potential outcome $Y$ under treatment $A=a$. Therefore, a collider would be $C$ would be written in a SWIG as $C(a, Y(a))$, which indicates it caused by $A$ and $Y(a)$ (i.e. a descendant of both $A$ and $Y(a)$). Conditioning on the collider $C$ in the analysis introduces selection bias, as defined by Hernan and Robins
Comment: Are you aware of any terms used in the Rubin potential outcomes framework that is equivalent to a collider? It seems it doesn't exist in the Rubin framework. thanks.
Comment: I'm unaware of any discussion outside some mentions of M-bias (a particular example structure of colliders). This blog post (and the link in it) may have some useful discussion https://statmodeling.stat.columbia.edu/2009/07/05/disputes_about/


How to display different decimal places for N and R-Squared using esttab?

Question: I use esttab to generate regression tables. Please see sample code below.
eststo clear
eststo: reghdfe y x1      , absorb(year state) cluster(year state)
        estadd local FE       "Yes"
        estadd local Controls "No"
eststo: reghdfe y x1 x2 x3, absorb(year state) cluster(year state)
        estadd local FE       "Yes"
        estadd local Controls "Yes"
esttab ,star(* 0.10 ** 0.05 *** 0.01) b(3) t(2) r2 replace label drop(_cons)   stats(FE Conrols N r2,fmt(%9.0fc) labels("Fixed Effects" "Controls" "Obserations" "R-Squared"))

Because my dataset is large, I use fmt(%9.0fc) to add commas to my number of observations. However, this option rounds my R-Squared to 0. How can I have integers (with commas) for observations and three decimal places for R-squared?
Also, is there a way to display adjusted R-squared? The user manual suggests that stats disables ar2 but I struggle to find a fix.
Answer: esttab is part of estout by Ben Jann, see the online documentation for installation and further information.
Here is a minimal working example using esttab's default formats.
eststo clear
sysuse auto

eststo: quietly regress price weight mpg
eststo: quietly regress price weight mpg foreign

esttab ,star(* 0.10 ** 0.05 *** 0.01) ///
    b(3) t(2) ar2

Note that ar2 calls adjusted R^2. However, if you are going to use the stats() option to format the number of obs the syntax changes:
esttab ,star(* 0.10 ** 0.05 *** 0.01) ///
    b(3) t(2) ///
    stats(N r2_a)

To apply formats you add a term for each stat, and if you supply fewer terms than stats esttab applies the last one to the remaining stats. This is why your R^2 is rounding to zero. Try the following:
esttab ,star(* 0.10 ** 0.05 *** 0.01) ///
    b(3) t(2) ///
    stats(N r2_a, fmt(%9.0fc %9.2fc)

So I would edit your esttab line as follows:
esttab ,star(* 0.10 ** 0.05 *** 0.01) ///
    b(3) t(2) /// no 'ar2' here
    label /// note you only need 'replace' if you are generating a file
    nocons /// 'reghdfe' has an option to 'drop(_cons)'
    stats(FE Controls N r2_a, /// 'Controls' not 'Conrols'
    fmt(%9.0fc %9.0fc %9.0fc %9.2fc) /// it seems you need place holders for the string stats
    labels("Fixed Effects" "Controls" "Obserations" "R-Squared"))


Token inválido JS

Question: Estou tendo problemas com um projeto de calculadora feito em JS.
Em uma linha específica diz que foi encontrado um token inesperado. Já fui no Github do curso e verifiquei o arquivo final deles, e na linha onde no meu programa(uso o VisualCodeEstudio) aparece o erro, no outro programa que abri(Sublime) o código deles, tá sem erro algum..
Grato desde já!
class CalcController {

constructor(){
this._locale = 'pt-BR';
this._displayCalcEl = document.querySelector("#display");
this._dateEl = document.querySelector("#data");
this._timeEl = document.querySelector("#hora");
this._currentDate;
this.initialize();
this.initButtonsEvents();

}

initialize(){

this.setDisplayDateTime();

setInterval(()=>{

    this.setDisplayDateTime();

}, 1000);

addEventListenerAll(element, events, fn){

        events.split(' ').forEach(event => {

            element.addEventListener(event, fn, false);

        });

}

}

initButtonsEvents(){

    let buttons = document.querySelectorAll("#buttons > g, #parts > g")

        buttons.forEach((btn, index)=>{

            this.addEventListenerAll(btn, "click drag", e=>{

                let textBtn = btn.className.baseVal.replace("btn-",""));

            });

            this.addEventListenerAll(btn, "mouseover mouseup mousedown", e=>{

                btn.style.cursor = "pointer";

            });

        });

}

setDisplayDateTime() {

    this.displayDate = this.currentDate.toLocaleDateString(this._locale,{
        day:"2-digit",
        month: "long",
        year:"numeric"

    });
    this.displayTime = this.currentDate.toLocaleTimeString(this._locale);

}

get displayTime(){
return this._timeEl.innerHTML;

}

set displayTime(valor){
    return this._timeEl.innerHTML = valor;
}

get displayDate(){
return this._dateEl.innerHTML;

}

set displayDate(valor){
    return this._dateEl.innerHTML = valor;
}

get displayCalc(){
    return this._displayCalcEl.innerHTML;
}

set displayCalc(valor){
    this._displayCalcEl.innerHTML = valor;
}

get currentDate(){
    return new Date();
}

set currentDate(valor){
    this._currentDate = valor;
}

}

Answer: Você recebe esse erro apenas no VsCode porque ele deve estar configurado com EsLint, que te ajuda na indentificação de erros no código. O seu erro é de formatação e de sintaxe do JS, por isso o erro de token inválido.
class CalcController {
  constructor() {
    this._locale = "pt-BR";
    this._displayCalcEl = document.querySelector("#display");
    this._dateEl = document.querySelector("#data");
    this._timeEl = document.querySelector("#hora");
    this._currentDate;
    this.initialize();
    this.initButtonsEvents();
  }

  initialize() {
    this.setDisplayDateTime();

    setInterval(() => {
      this.setDisplayDateTime();
    }, 1000);
  }

  addEventListenerAll(element, events, fn) {
    events.split(" ").forEach(event => {
      element.addEventListener(event, fn, false);
    });
  }

  initButtonsEvents() {
    let buttons = document.querySelectorAll("#buttons > g, #parts > g");

    buttons.forEach((btn, index) => {
      this.addEventListenerAll(btn, "click drag", e => {
        let textBtn = btn.className.baseVal.replace("btn-", "");
      });

      this.addEventListenerAll(btn, "mouseover mouseup mousedown", e => {
        btn.style.cursor = "pointer";
      });
    });
  }

  setDisplayDateTime() {
    this.displayDate = this.currentDate.toLocaleDateString(this._locale, {
      day: "2-digit",
      month: "long",
      year: "numeric"
    });
    this.displayTime = this.currentDate.toLocaleTimeString(this._locale);
  }

  get displayTime() {
    return this._timeEl.innerHTML;
  }

  set displayTime(valor) {
    return (this._timeEl.innerHTML = valor);
  }

  get displayDate() {
    return this._dateEl.innerHTML;
  }

  set displayDate(valor) {
    return (this._dateEl.innerHTML = valor);
  }

  get displayCalc() {
    return this._displayCalcEl.innerHTML;
  }

  set displayCalc(valor) {
    this._displayCalcEl.innerHTML = valor;
  }

  get currentDate() {
    return new Date();
  }

  set currentDate(valor) {
    this._currentDate = valor;
  }
}

Sempre que receber esse erro de token inválido se atente a sintaxe da escrita do seu código e use os logs do eslint ao seu favor
Comment: Certo, eu refiz o código com base no que você me passou, e agora o erro mudou xD
No console do Chrome, aparece "Uncaught TypeError: this.addEventListenerAll is not a function at CalcController.js:30" , ou seja, o 'this.addeventlistener' diz que não é função..kkkkk
Comment: Eu editei o código, vê se funciona agora
Comment: Coloquei o seu código e milagrosamente funcionou! o/
Poderia me explicar o que estava errado desta outra vez? grato!
Comment: Faltavam ou sobravam alguns caracteres, como `}` e `)`. Coloque os dois códigos em paralelo e compare, você vai perceber

Token inválido JS


Why does Larry Carlton think Dmajor scale when some plays Gmajor7 chord?

Question: In this video at 5:25 Larry says when someone played a Gmajor7 chord he thinks to play a Dmajor scale as those are the money notes.
What is the theory behind that thinking?
Comment: I think he means the D major _chord_, not scale. At what exact minute:second time position does he say he means the _scale_? I watched through this video too because it was suggested by Youtube.
Comment: @RandyZeitman at 5:28 he outlines a D major chord. He does not play randomly selected notes from the D major scale. From the D major scale, he could also have selected all of the notes that are in a Gmaj7 chord, - or he could have outlined an even more colorful A major chord, but the_point, _color notes to play on a written Gmaj7_ is to outline a D major chord. Thinking about an entire _scale_ is not helpful in pop songs, if you want to add "money notes" to a solo. What do you do with an entire scale - select notes from it randomly, and every note in the scale will be a color note?
Comment: The GMaj7 is the IV chord of DMaj7, but so what.  What this amounts to is using G Lydian over the Gmaj7 chord which adds a sharp 4th.  This creates more tension and produces a darker sound in the melodic theme.
Comment: At 5:35 ... "these are the color notes ... the money notes".
Comment: He plays eight notes. Are they arpeggios of D or a scale? I don't see any mention of random.
Comment: @RandyZeitman He outlines a D major chord and then a couple more notes, because he can't resist making it sound like an actual line from somewhere. Think about it. "What are the color notes to play on a Gmaj7 in Larry Carlton's style?" - _"Any notes from the D major scale"?_ That would be completely absurd. He does not arpeggiate an Em chord, not an A major chord, not a Bm chord, not a G major chord, not a Gmaj7 chord, none of the other stuff that could be done with notes from the D major scale. He plays a D major chord. Those are the color notes, the money notes to play on a written Gmaj7. :)
Comment: A couple more notes ... of what?  I've no idea why 'Any notes from the D major scale' would be absurd - I'm a novice. Why not just state the notes he plays so we all have our answer?
Comment: @RandyZeitman Don't you know what's the difference between playing just any notes from a major scale vs. playing tonic/subdominant/dominant chords using notes from the scale? Can you accompany Happy Birthday with just any combination of notes in any order as long as they're from the major scale? Everything works the same, same feeling and color, no matter which combination of notes you select? Btw, Rick Beato's newest video says something about the Larry Carlton thing https://www.youtube.com/watch?v=pH0S4MRbw74&t=10m15s   If you need further "proof", he mentions "upper structure triads". :)
Comment: @piiperi  ???... yes, I think everyone would understand that playing different notes results in different music. My statement isn't in relation to a song, it's in relation to him strumming a single chord.  Could you please list the notes he's playing in his phrase against the chord?
Comment: @RandyZeitman I think you'll find out what the notes are just fine without external help. If you're happy with the explanation that anything pulled from the D major scale like it was G lydian works as color notes for emphasizing a Gmaj7 chord, and that's what Larry Carlton did in his recording sessions, then that's perfectly OK. I just wonder if you've actually tried out any of this stuff on songs that have maj7 chords. Excellent song choices to try it on are What's Going On by Marvin Gaye and Imagine by John Lennon. I hope you'll realize how unsuitable Lydian mode is for the songs. ;)
Comment: @piiperi  Why wouldn't anyone be happy with that explanation. Yet a third time ... I am a novice ... I can't possibly know if someone's explanation is right or wrong. Is there some reason you're not asking that person? "I just wonder if you've actually tried out any of this stuff on songs that have maj7 chords." No! (... as above ... novice...) I said nothing about lydian mode ... ggcg did.
Comment: @DavidBowling Lydian gives a nice jazzy sound in its own right and you can get Lydian by overlaying a D major scale on a G chord, nothing wrong with that. But Lydian is not what Larry Carlton's maj7 coloring trick is about at all, it's about the triad as you say. It seems that the problem with many guitarists is, they're not fluent with the components of traditional functional harmony and they want to see everything as a scale or a mode. So "D major" must mean the D major _scale_, unless explicitly stated otherwise. What can you do? It's not a bigger deal than that, just talking about music.
Comment: @RandyZeitman why you shouldn't be happy with the explanation: because you _try_ it on actual songs and you hear what Lydian does to the chords. And then you try the upper structure triads, playing a major triad rooted on the fifth of any maj7 chord, in actual songs. It's simple and works on any maj7 chord without even knowing what the scale is. Don't get stuck in scale/mode thinking. In the history of jazz, modal playing came _after_ the more traditional and basic chord playing, and beginners should learn basics first. :) Also, watch the next video https://www.youtube.com/watch?v=pH0S4MRbw74
Comment: I found this other example which may be speaking about the same, or similar topic.
Triadic Soloing by Larry Carlton
https://www.youtube.com/watch?v=5s2V6KRQVFw
Comment: @piiperi I'm happy with the explanation because I understand it, not because I think it's the best explanation ... yet still again ... third time now ... I ... am ...a ... novice.
Comment: Do you understand this: when you see "Gmaj7", you play the notes D - F# - A. When you see "Cmaj7", you play the notes G - B - D. When you see "Fmaj7", you play C - E - G. For Dmaj7: A - C# - E. For Emaj7: B - D# - F#. For Abmaj7: Eb - G - Bb. For Ebmaj7: Bb - D - F. Etc. You take the _fifth_ of the chord and play the notes of a simple major triad chord rooted on that fifth. In Gmaj7 the fifth is D. So, D - F# - A.
Answer: Playing D major over Gmaj7 creates the sound of the Lydian mode. These days, most jazz players prefer to use Lydian instead over the major scale (Ionian) - it's part of the sound of jazz since about the 1970s.
The only difference between the major scale and the Lydian mode is that major has a natural 4, while Lydian has a #4. This #4 (also a #11) is considered to be more colorful than the natural. The natural 4 is often referred to as an "avoid note," but the #4 blends more easily with the major 7th chord quality.
I think there is even more insight buried in this quote. He doesn't say, "I play the Lydian mode," he says he plays D major, and that's what has the "money notes."
As players, it is natural for us to start our scales on the root note, but when we improvise, constantly starting on the root of the chord can sound cheesy. By thinking of the scale as D major, he is more likely to start on the D, which is the 5th of G. This has some melodic advantages because when you play the scale ascending in eighth notes, the 7, 9, and #11 notes will land on the downbeats. Conversely, starting a run on the root, will lead to the blander root, 3, 5, 7 notes being emphasized. So by thinking about the scale as having a different root from the accompaniment, he is setting himself up to play more interesting lines.
Comment: Odd notes on even beats is a simple, powerful, insightful statement!
Comment: 'If he's thinking D major, he's more likely to start on D'...When you get to where Larry is, there's probably a bit more (or quite possibly a lot less!) thinking going on. He's most likely past that stage; he was at that point 50 yrs ago!
Comment: The D major scale happens to have all the notes of a Gmaj7 chord, so why doesn't he play _those_ money notes? Is there some fake money in the scale too? If only some notes of the scale are the real money notes, then wouldn't it be more helpful to think in terms of reduced note sets that contain only the actual money notes, and none of the wrong ones. We could call those reduced sets like ... _chords_ or something.
Comment: "he is more likely to start on the D" -- somehow I doubt that Larry Carlton has any difficulties starting on whatever note he wants to....
Comment: @DavidBowling Fair enough, but in the context of the video, he is talking about things he played when he started out and didn't know any theory.
Comment: The question is based on a false premise, and the answer getting upvoted and accepted... it makes me sad. Are guitarists really that hopeless. Lydian mode? Searching for starting points for scale runs, because guitar solos are made of scale runs? "Odd notes on even beats"... what? That way you will never understand what Larry Carlton is doing. :) There's a whole world of things built from the notes of a major scale, and you can use the same notes to e.g. make it feel like the harmony is at rest/tonic, or leaning to subdominant or dominant side. Same scale, but completely different feelings. :)
Comment: "Odd notes on even beats"... what? ... refers to Peter's insight. The question is based on a false premise? ... all I did was ask what he meant.
Answer: He means the chord. "D major over G." D major chord over G. Chord symbol: D/G. You can play that in place of Gmaj7, and it will do the "maj7" thing, but in a more colorful way. It's almost Gmaj9, but leaving out the usual G and B notes of a regular G major chord, assuming a bass player plays the G. You can play a maj9 chord almost always if there's a written "maj7", and if you want it to emphasize the chord's "maj7" color, you play only those notes. D/G is kind of like "more strongly maj7 than maj7 itself", playing V chord while keeping bass at tonic.
The thing that happens when you choose to make a regular major chord a maj7 by adding a major seventh note is, it says that it's not a dominant seventh chord. It's like reminding the listener where the harmony is leaning. If you play a V triad while keeping the bass at I, it emphasizes the major seventh note even more.
If you want to do a similar thing with a dominant seventh chord, you play a minor chord. For example if you see a G7 chord symbol, and want to do a similar thing as Larry Carlton's "color notes, money notes", you outline a Dm chord in your solo, so Dm/G. It highlights the dominant seventh note even more than a regular G7. (In addition to that there are other "color notes" chords for a G dominant like Ddim, Ddim7, or "Fm7-5")
By the way, a D/G is sometimes called a "Steely Dan chord", because many Steely Dan songs have that type of chord in many places. For example "Don't take me alive", on the lyrics line "With rage in your eyes and your megaphones", the chords are: Bb/Eb -  C/F - D/G. (And then it continues with even more of the same chord type)
Comment: Well he says "scale" so why do you say he means chord?
Comment: No mention of either scale or chord at that point. But playing the notes from D major *chord* will be 2/3 of Gmaj7 anyway - all he's adding is 9, making Gmaj9. A very common occurrence in jazz.
Comment: @Tim Exactly. But pay attention to which notes of Gmaj9 he's _not_ playing... particularly, he leaves out the B note, and that's how you get the Steely Dan chord. :)
Comment: You're forgetting that the accompaniment is still playing the chord Gmaj7, so the B is still present - Carlton is soloing on the chord extensions. The overall harmony still contains the major 3rd (B), so it's a Gmaj9 not D/G, which is a type of suspended chord.
Comment: @Peter I'm not forgetting anything. It's about emphasizing colors when soloing. Try it yourself, it's not hard, you just need to know which notes are relevant and characteristic for each moment of the harmony progression, keep track of where they are, and emphasize each case by playing color tones. For example, on a written dominant seventh chord: play a minor, diminished or dim7 chord rooted on the fifth of the original chord. Or in this particular case, on a written maj7 chord: play a major chord rooted on the fifth of the original chord. You don't even need scales or modes to do this. :)