How do I turn off clean URLs only for logged-in users?

Question: The end-goal is to use filters to support AWS' new CDN dynamic content feature.
Answer: This isn't possible in Drupal core because the clean url check occurs so early in the bootstrap phase, i.e. before you would be checking for permissions, settings, etc. One hacky possibility is to try and determine in your settings.php file if a session is open and then enable the clean_url settings dynamically:
<code>$conf['clean_url'] = 0;
</code>
But even that would probably be swamped by your htaccess settings and mod_rewrite.


Create a vector in R from a list with different column lengths

Question: The question says to "Save the weights of the chicks on day 4 from diet 1 as a vector x. Save the weights of the chicks on day 4 from diet 4 as a vector y"
My code:
data("ChickWeight")
plot(ChickWeight$Time, ChickWeight$weight, col=ChickWeight$Diet)
head(ChickWeight)
chick <- reshape(ChickWeight, idvar=c("Chick","Diet"), timevar="Time",direction="wide")
head(chick)
chick <- na.omit(chick)

#Exercise1
library(dplyr)
x <- filter(chick,Diet=="1")%>%select(chick$weight.4)%>%unlist
y <- filter(chick,Diet=="4")%>%select(chick$weight.4)%>%unlist

The error displayed
The error in code:
Error: Can't subset columns that don't exist.
x Locations 59, 58, 55, 56, 48, etc. don't exist.
i There are only 14 columns.

Not sure why this error occurs since I'm converting it to a vector. Can someone please inform me on the solution to this? Thank you..
Answer: We don't the chick$ in select - just use the unquoted column name
library(dplyr)
filter(chick, Diet == "1")%>%
   select(weight.4) %>%
   pull(1)

Comment: What does pull(1) do?
Comment: Can you help https://stackoverflow.com/questions/65362597/how-to-sort-multiple-columns it is not a duplicate question
Comment: @user330 sure, will cheeck out
Answer: Okay I actually immediately fixed it lol. Noob mistake, but if anybody comes across this error in their starting of R, the solution is to remove the list name, instead of chick$weight.4 just put weight.4 :)


SQL mostrando registros se apenas atenderem condições diferentes do usual

Question: Tenho uma situação um pouco diferente, tentei diferentes condições mas nenhum trouxe o resultado desejado.
Minha necessidade é a seguinte:
Tenho uma base contendo autores de livros e suas respectivas obras.
Preciso criar uma consulta que traga apenas os autores que tiveram o primeiro livro publicado a partir de 1919.
Segue script para criação das tabelas:
CREATE TABLE AUTOR (
    ID INT,
    NOME VARCHAR(255),
    PRIMARY KEY (ID)
);

CREATE TABLE LIVROS (
    ID INT,
    ID_AUTOR INT,
    TITULO VARCHAR(255),
    ANO INT,
    PRIMARY KEY (ID),
    FOREIGN KEY (ID_AUTOR) REFERENCES AUTOR (ID)
);

Segue script para inserção dos dados amostragem:
INSERT INTO AUTOR (ID, NOME) VALUES (1, 'MACHADO DE ASSIS');
INSERT INTO AUTOR (ID, NOME) VALUES (2, 'EUCLIDES DA CUNHA');
INSERT INTO AUTOR (ID, NOME) VALUES (3, 'CLARICE LISPECTOR');
INSERT INTO AUTOR (ID, NOME) VALUES (4, 'JOSÉ DE ALENCAR');
INSERT INTO AUTOR (ID, NOME) VALUES (5, 'MONTEIRO LOBATO');
INSERT INTO AUTOR (ID, NOME) VALUES (6, 'CECÍLIA MEIRELES');

INSERT INTO LIVROS (ID, ID_AUTOR, TITULO, ANO) VALUES (1, 5, 'O Saci-Pererê: resultado de um inquérito', 1918);
INSERT INTO LIVROS (ID, ID_AUTOR, TITULO, ANO) VALUES (2, 5, 'O Picapau Amarelo', 1939);
INSERT INTO LIVROS (ID, ID_AUTOR, TITULO, ANO) VALUES (3, 6, 'Espectros', 1919);
INSERT INTO LIVROS (ID, ID_AUTOR, TITULO, ANO) VALUES (4, 3, 'Perto do Coração Selvagem', 1944);

A consulta correta deve trazer o seguinte resultado:
Result
| id(autor) |       nome(autor)      |
|------------------------------------|
|    6      |    CECÍLIA MEIRELES    |
|    3      |    CLARICE LISPECTOR   |

Monteiro Lobato não virá na consulta pois tem uma publicação anterior ao ano de 1919.
Comment: `SELECT * FROM table_livros WHERE ano >= 1919` Isso já irá te trazer todos os livros de 1919 pra cima, se precisar APENAS que sejam de 1919 mude a condição `>=` para `==`
Comment: Pesquise por NOT EXISTS
Answer: Utilizando a cláusula IN:
SELECT * FROM AUTOR WHERE ID IN (SELECT ID_AUTOR FROM LIVROS GROUP BY ID_AUTOR HAVING MIN(ANO) >= 1919);

Answer: Para entender mais sobre JOINS, você pode ler Cláusulas INNER JOIN, LEFT JOIN e RIGHT JOIN no SQL Server ou JOINS em SQL.
Recomendo ler também: MIN(Transact-SQL) e SELECT – GROUP BY – Transact-SQL.
No seu caso, a QUERY(Select) ficaria assim:
SELECT AUTOR.ID,AUTOR.NOME FROM AUTOR
INNER JOIN LIVROS ON
AUTOR.ID=LIVROS.ID_AUTOR
GROUP BY AUTOR.NOME,AUTOR.ID
HAVING MIN(LIVROS.ANO)>=1919;


Figuring out a digit knowing that the number is a multiple of 9

Question: I am trying to help my kid with a homework problem, and he's insisting that the only way to solve is trial and error. I want to know if there is a more systematic way - it sounds as though the teacher may have taught them to do it by guessing and verifying, but it has stoked my curiosity.

The cost of each item is 9 dollars. We know that some customer paid $18C43$,
  but the figure C is blurred out. How much did we pay? and How many
  items were purchased?

We can unfold $18C43 = 18043 + 100C$. And we know that $9n = 18043 + 100C$. But we end with have two unknowns in one equation. Of course we know that both C and n are natural numbers.
Comment: To followup on your approach: $9n = 9 \cdot(2004 + 11 C) + 7 + C$.
Comment: [divisibility rules](http://r.search.yahoo.com/_ylt=A0LEV7n_LCFYzGMAaiYnnIlQ;_ylu=X3oDMTEydHJwbzlsBGNvbG8DYmYxBHBvcwM0BHZ0aWQDQjI2OTFfMQRzZWMDc3I-/RV=2/RE=1478598016/RO=10/RU=https%3a%2f%2fen.wikipedia.org%2fwiki%2fDivisibility_rule/RK=0/RS=ffdwK4oumIjtoTuIMcP2AJZ0sJ0-)
Comment: $0 \le C \le 9$.
Answer: Hint: The amount paid is a multiple of $9$. Recall casting out nines...
Solution:
Casting out nines in $18C43$ leaves $C+7$. This must be a multiple of $9$. Since $0 \le C \le 9$, we have $2 \le C+7 \le 16$, and so the only solution is $C+7=9$, that is, $C=2$.
Comment: I know the answer, and I understand that it is a multiple of nine. The issue is how structured the procedure to finding out the answer has or can be.
Comment: @Butternut Basically, you would like an explanation of the problem that can be used for kids, right?
Comment: @астонвіллаолофмэллбэрг Yes, exactly.
Answer: $9n=18043+100C$
divide through by $9.$
We really only care about the remainders.
$18043/9 = (2004) r 7$
$100/ 9 = (11) r 1$
9 must divide $(7 + C)$
This approach will work for any divisor.  But 9's are special.
If the sum of the digits is divisible by 9, then the number is divisible by 9.
Answer: keep casting out nines until you can't any more...
$18C43 \to 1+8+C+4+3 \to 16+C \to 7+C$
Then you need to have $7+C = 9$.
So $C = 2$
Why does this work?
$$18C43 =
\left\{ \begin{array}{rlo}
   10000 &= 1 + 1 \cdot 9999\\
   +8000 &= 8 + 8 \cdot 999\\
    +C00 &= C + C \cdot 99 \\
     +40 &= 4 + 4 \cdot 9 \\
      +3 &= 3
\end{array} \right.
$$
 If you examine this, you see that
\begin{align}
    18C43
    &= 1+8+C+4+3 + (\text{a multiple of 9}) \\
    &= 16+C + (\text{a multiple of 9}) \\
    &= 1+6+C + (\text{another multiple of 9}) \\
    &= 7+C + (\text{another multiple of 9}) \\
\end{align}
So, if $18C43 $ has to be a multiple of $9$, then $7+C$ has to be a multiple of $9$.
The only choice you have is $7 + C = 9$
Answer: $9n =18043 + 99C +C $
$n=2004 \frac 79 + 11C + \frac C9$
So $\frac 79+\frac C9=\frac {7+C}9$ is a whole number.  $C = 0....9$ so $C+7=7,....16$.  So the only possible answer is $C+7= 9$ and $C=2$
So $9n=18243$
$n=2027$
(And $2027 =2004 \frac 79+22+\frac 29$)
===
But there's also $18C43\implies 1+8+C+4+3=16+C\implies 1+6+C=7+C\implies 7+C=9$ so $C=2$ because, as everyone knows, "a number is divisible by 9 if and only if the sum of ots digits are divisible by 9".
But I have mixed feelings about teaching that to kids.  It'It's trick that kids like.  And a really useful one.  But I don't like teaching "magic".


Bayesian Regression: Loss Function Explained

Question: Considering a simple linear regression model e.g. $y_i = \alpha + \beta x_i + \epsilon $ , in probabilistic terms:
$$ \mu_i = \alpha + \beta x_i  $$
$$ y_i \sim \mathcal{N}(\mu_i, \sigma) $$
We assume prior distributions on the parameters $\alpha, \beta, \sigma$ and apply Bayes theorem (posterior $\propto$ likelihood x prior) i.e.:
$$f(\alpha, \beta, \sigma | Y, X) \propto  \prod_{i=1}^{n} \mathcal{N}(y_i; \alpha + \beta x_i, \sigma)  f_\alpha(\alpha)f_\beta(\beta) f_\sigma (\sigma)$$
With priors and data, we then perform Markov Chain Monte Carlo method for sampling from this posterior distribution.
My question is:

How do loss functions or different loss functions fit into this picture? How do loss functions come into the next stage of taking a decision based on the posterior distrubtion?
Comment: Loss functions come into the next stage, where you take a decision based on the posterior distribution, using the loss function to help decide which decision is optimal.
Comment: That is useful thanks @Henry
Answer:
How do loss functions or different loss functions fit into this picture? Do different loss functions result in a different mechanism for calculating likelihood?

This is how I read your question: we could fit regression by minimizing different loss functions, how they can be applied to Bayesian regression?
Regression, in non-Bayesian setting, can be fitted by minimizing loss or maximizing the likelihood. Both approaches are equivalent, for example, minimizing squared loss is equivalent to maximizing Gaussian likelihood, absolute loss is equivalent to using Laplace distribution for likelihood, etc. Same in Bayesian regression, you are not minimizing the loss to fit the model, but the choice of likelihood function plays a similar role.
Same applies to using regularization. In Bayesian setting, regularization is dealt by choosing appropriate priors. For example, $\ell_2$ penalty is equivalent to using Gaussian priors for the parameters.


{"id"=>"#"}

Question: comment controller:
def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.create(params[:comment].permit(:comment))

  if @comment.save
    redirect_to post_path(@post)
  else
    render 'new'
  end
end

index.html.haml:
#post
  = @posts.each do |post|
    .post
      %p= link_to post.content, post_path(@posts)
      .date
        %p
        published
        = time_ago_in_words(post.created_at)

show.html.haml:
.show
  %p= @post.content
    .comments
      %h2= @post.comments.count
      = render @post.comments

      %h3= comment to post
      = render 'comment/form'

  = link_to "edit", edit_post_path(@post)
  = link_to "delete", post_path(@post), method: :delete, data: {confirm: "Are you sure?"}
  = link_to "home", root_path

Comment: Please clearly define what your question is and change your title to reflect that. Simply posting code isn't sufficient.
Comment: i am trying to add a commenting fucntionality, and when i go to the Post show page i get the error.
Comment: From the guidelines: _Questions seeking debugging help ("why isn't this code working?") must include ... a specific problem or error ... in the question itself._
Answer: Change = to - on the second line of your posted index.html.haml view.

{"id"=>"#"}


Creating dynamic class from a string containing the class definition

Question: I have a stored procedure which accepts the table name, then it reads the table structure and returns me the table structure in the form of a class definition in a string.
E.g.:
string myString =
 "
   public class TableName
   {
     public int Column1 { get; set; }
   }
 "

Is it possible a create a Class/Type from the string containing the class definition ?
For eg:-
Type type = GenerateType(myString);

I have to pass this type variable to my further piece of code so please help me to create class/type from the string containing the class definition.
Comment: [Try Roslyn](https://github.com/dotnet/roslyn). But what do you plan to do with instances of a class whose type is unknown at compile time?
Comment: I think you are actually looking for *serialization*. There are many ways to achieve this, it depends on your needs and the complexity of your classes. Usually, serializing to/from Json is sufficient for many cases.
Comment: This is going to sound like I'm being facetious, but I'm not. Execute the stored procedure, copy the class definition it generates, and then paste that into a class file in your project. Then you will have achieved what you asked in your question - you will have created a type to hold the output of the stored procedure.
Comment: Are you creating some type of [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)?
Comment: Create new type at runtime is very complex do you really need that? I suggest you to find alternatives maybe [dynamic](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic) or [ExpandoObject](https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.110).aspx) can help? If you find you have to create a new type give [TypeBuilder](https://msdn.microsoft.com/en-us/library/system.reflection.emit.typebuilder(v=vs.110).aspx) a look.
Comment: This has to be one of the very strangest things I've ever seen. Ever. If I'm getting this straight, it's C# code that defines a class that describes a table and columns, while itself being stored in a column in a table. Please don't do this.
Comment: @ScottHannen, you have understood half of the requirement correctly i.e. my class structure and table structure is same. You can visualize it as an ORM generated class but it is not stored in a column in the table. I have an SP which reads the table definition from system table and then concatenates the information to look like class structure and then returns that concatenated string .
Comment: @ScottHannen I cannot manually copy the class definition and paste it into a class file. This has to be done through the code dynamically. Here I am creating the class dynamically based on the table structure. This dynamically created class will be consumed by my further piece of code
Answer: You can use the CSharpCodeProvider to compile your result at runtime and then use the Activator - Class to create an object from your generated code.
// compile your piece of code to dll file
Microsoft.CSharp.CSharpCodeProvider cSharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters compilerParameters = new System.CodeDom.Compiler.CompilerParameters();
compilerParameters.GenerateInMemory = true;
compilerParameters.GenerateExecutable = false;
System.CodeDom.Compiler.CompilerResults cResult = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, "using System; namespace Tables { 'put here your class definition' }");

// then load your dll file, get type and object from class
Assembly assembly = cResult.CompiledAssembly;
Type myTableType = assembly.GetType("Tables.Tablename");
var finalResult = Activator.CreateInstance(myTableType);

Comment: Thank you very much. This works just perfectly. Saved my time
Comment: Getting an issue in this line 'Assembly assembly = cResult.CompiledAssembly'. This works if I am in the executing assembly (For eg:- Main method is in the same assembly) but in my scenario this code is inside a DLL and I am referring this DLL in my startUp project. In this case I am getting exception 'Cannot load file or assembly'
Comment: Check your cResult.Errors => i suggest your code doesn't compile
Comment: Yes, There was an error in cResult. Fixed and working now. Many thanks


Email alert if there is any 502 or 500 error logged in Elastic-search

Question: Is there any tool, Which i can use/configure over my ELK Stack where i get email alert if any we get any error on out website. Many a times it happened that at night we get some error but no one looks in to that and later it become a big problem. I'm just looking for a tool which can send alert every 6 hours or something.
Comment: open source tool? As far as I know elastic licence include Watches for alerting email.
Comment: Yes, an opensource tool which can help me to do some custom stuff later if required as much i know watchers will not give that much details
Answer: Use X-pack and enable the watchers configuration.
Comment: but how exactly ? I have an index created with the help of metricbeats and with all the data, but still could not find how to configure it


Continuous straight lines through the origin of a non-continuous function

Question: Give an example of a function $f: \mathbb R^2 → \mathbb R$ which is not continuous at $(0, 0)$, but such that $f|_L: L → \mathbb R$ is
continuous for all straight lines L through the origin $(0, 0)$.
Comment: use "\mathbb R" to get a nice looking $\mathbb R$.
Comment: @JohnHughes Or even just /Bbb R ...
Comment: Except that it's "\Bbb R". :)  Thanks, @DonAntonio -- this is new to me...all those wasted characters...:(
Answer: This is a standard example, and googling "continuous along each line through the origin but not continuous at the origin" gave me this question as the first result. I will give a (slightly altered) account of the arguments there.
Take the function
$$
f(x,y) =\cases{ \frac{x^2y}{x^4+y^2}&if $(x,y)\neq(0,0)$\\0&if $(x, y) = (0,0)$}
$$
Now, along the lines $x = 0$ and $y = 0$, we clearly have $f(0,y) = f(x, 0) = 0$, so the function is continuous along those lines. For any other line, we may write $y = mx$ with $m \neq 0$, which gives (at all points except the origin)
$$
f(x, mx) = \frac{x^2\cdot mx}{x^4 + m^2x^2} = \frac{mx}{x^2+m^2}
$$
and we see that 1) the denominator is never zero, and 2) the function value goes to $0$ as $x\to 0$. Therefore the function $f$ is continuous along this line as well.
However, now we set $y = x^2$, and we get
$$
f(x, x^2) = \frac{x^2\cdot x^2}{x^4 + x^4} = \frac12
$$
which does not go to $0$ as $x \to 0$. Therefore the function is not continuous at $(0,0)$.
Answer: Define $f(x,y)=\frac{y^2}{x}$ for $x\neq0$ and $0$ otherwise.  Then for each $y=mx$, $f(x)=m^2x$ which is continuous.  Trivially continuous along $x=0$.  But the limit is equal to $1$ at the origin as we approach along $x=y^2$, so $f$ is not continuous.


On trichotomy of order for natural numbers

Question: I am currently going through Chapter 2 of Tao's Analysis book, and I don't quite understand the proof of the Trichotomy of order for natural numbers (Proposition 2.2.13).
Let $a,b$ be natural numbers. Then exactly one of the following statements is true: $a<b,a=b,b<a$.
The proof goes as follows (reproduced from the book itself). First we show that we cannot have more than one of the statements holding at the same time. If $a<b$ then $a\neq b$ by definition, and if $a>b$ then $a\neq b$ by definition. If $a<b$ and $b<a$, then we would have that $a=b$, which is a contradiction. Thus, no more than one of the statements is true.
My question is in regard to the proof strategy that is being used for this part. I do understand what is going on, it makes sense to me. I see that the first two cases are to say that if one of the statements happen, then the other two cannot happen and the third case says that if the three happen at the same time, that's impossible.
I want to ask what's the proof strategy that is being followed (I'm relatively new to proof writing, so I need to have it clear in my head), because this is the first proof of this kind I have seen.
I appreciate your help.
Comment: I don't see how $a < b$ and $b < a$ together somehow imply $a=b$
Comment: The goal here is to prove exactly one of the following 3 statements is true for any a, b, and your book's proof strategy is proof by contradiction by claiming there may be two statements simultaneously true.  There're only 3 cases (unordered pairs of statements) out of the 3 statements here, so the author discussed those 3 cases each of which arrived at contradiction. So the original goal is achieved.
Comment: Tao uses anti-symmetry of the order to justify this, but I do understand your point
Comment: Oh, I see, good point
Comment: Presumably you have already established that at least one of $ab$ must be true. E.g. suppose $a<^* b$ means $1<b/a\in\Bbb N.$ Then $3\not <^* 4$ and $3\ne 4$ and $4\not <^* 3$.
Answer: In the third edition he cites Prop. 2.2.12 as containing the statement which is used to conclude $a = b$ from $a < b \land b < a$. But to be honest I don't see any statement that immediately implies this. Prop. 2.2.12 does contain the anti-symmetry law, but anti-symmetry refers to $\leq$ and can therefore not be used on $a < b \land b < a$.
What is needed here is the transitivity of $<$ ; since $a < b \land b < a$ then implies $a < a $ which already gives the desired contradiction.
The overall idea of that first part is to show
$$
 \neg (a < b \land a = b)  ~\land~ \neg (b < a \land a = b) ~\land~ \neg (a < b \land b < a)
$$
porving that at most one of the 3 parts of the disjuction $a < b \lor a = b \lor b < a$ is true. The second part of the proof (as found in the book) then shows by induction that the disjunction is true and therefore at least one of the parts must be true.
Comment: @AlexRuiz They are not logically equivalent. If $A$ and $B$ are both true, then $\neg(A \land B) \land \neg (C \land B) \land \neg (A \land B)$ is false, but $A \lor B \lor C$ is true. The first one is saying "from $A, B, C$ at most one can be true" and the second one tells you that "at least one of $A, B, C$ is true". And in the proof both parts are shown for $A \equiv a < b$, $B \equiv a = b$ and $C \equiv b < a$.
Comment: Why is not the case that we want to show that $[a<b/land/neg (b<a)/land/neg (a/neq b)]\lor [b<a/land/neg (a<b)/land/neg (a/neq b)]\lor [a=b/land/neg(a<b)/land/neg (b<a)]$?
Comment: @AlexRuiz Yes $(a < b \land \neg b < a \land a \neq b) \lor (\neg a < b \land b < a \land a \neq b) \lor (\neg a < b \land \neg b < a \land a = b)$ is indeed what we want to show overall. And it follows from the first part of the proof (which I specified) combined with the second part, which shows $a<b∨a=b∨b<a$ by induction.
Comment: My apologies, I couldn't work these past couple of days. So from what I just worked out, $\neg (a<b\land a=b) \land \neg (b<a\land a=b)\land \neg (a<b\land b<a)$ is equivalent to saying $a<b \lor b<a \lor a=b$. I must say this is a very smart equivalence, am I right?
Answer: The basic proof strategy is this:
First: to establish that exactly one of the three claims hold, you typically show two things:

That at least one of the two claims hold

That at most one of the two claims hold

Please note that in your post, you only describe a proof for the second half, but I am sure the first half is provided in the book as well
Second, to establish that at most one of several claims hold, all you have to show is that you cannot have any of the two claims holding at once: if you show that, then clearly you also cannot have three or more claims holding.  This is what the proof does: it rules out all combinations of two claims: the first and the second can't hold together, the second and the third can't hold together, and the first and the third can't hold together.
Your analysis is actually a little off on that last one: it's not that the proof shows that you can't have all three, but simply that you can't have $a < b$ and $b < a$ at the same time, because if you do then, you have $a=b$, and now you have both $a < b$ and $a = b$, which some earlier theorem must already have ruled out.
Comment: @AlexRuiz Sorry, but I am not quite clear what you just asked here. First, yes, it is totally standard to prove 'exactly one' by proving 'at least one' and 'at most one'. But again, in your post you only provide a proof of 'at most one' .... I am sure Tao also provides a proof of 'at least one', but you are not reporting that part in your original post. Second, it is defintely *not* true that 'each proof shows each of these goals'! If I show 'at most one', I have not shown 'at least one', and vice versa. This is why you need to do both.
Comment: Sorry for a late reply, so in this type of proofs it's just standard to prove those two things yuo mentioned? It's just that it's hard for me to see how each proof shows each of these two goals. I don't really see the difference


Loading Application Image icon in to imageView Using Glide

Question: I m making fileManager app and i load drawble image icon in my image view using glide:
this is my drawble method:
 public Drawable getapkIcon(String filepath){

    PackageInfo packageInfo = context.getPackageManager().getPackageArchiveInfo(filepath, PackageManager.GET_ACTIVITIES);
    ApplicationInfo appInfo = packageInfo.applicationInfo;
    if (Build.VERSION.SDK_INT >= 8) {
        appInfo.sourceDir =filepath;
        appInfo.publicSourceDir = filepath;
    }
    Drawable icon = appInfo.loadIcon(context.getPackageManager());

    return icon;

}

glide performs:
Glide
.with(mContext)
.load(mIconRepository
.getapkIcon(filepath))
.placeholder(R.mipmap.ic_launcher)
.into(holder.apkImage);

which shows error:
 java.lang.IllegalArgumentException: Unknown type class
 android.graphics.drawable.BitmapDrawable. You must provide a Model of a
 type for which there is a registered ModelLoader, if you are using a custom
 model, you must first call Glide#register with a ModelLoaderFactory for your custom model class

how can i solve?
Answer: According to my knowledge, you can't use Glide load method with BitmapDrawable, it's not a supported type.
You could implement model loader/decoder for it, but I think it's not worth to solve this problem.
Why don't you use simple ImageView.setImageDrawable(drawable) if your drawable is already in your local file system?
Comment: because its take some 0.5s time to load the image


Calculated column in writable data grid

Question: I have a datagrid in a VB.NET project which at present is directly bound to a binding source so changes get written straight to the underlying single table in the dataset.
I want to add a calculated column - a count of records on a linked table - while maintaining the ability to enter data directly in to the grid, which I lose if I use a query to get the current fields along with the calculated column.
Can anyone point me to the best way of doing this? Much appreciated as ever...
Answer: I've sorted it - an SQL subselect in the query in the dataset designer allowed me to do the count I needed while leaving the other fields writeable.
Comment: Thanks - I didn't know that performing joins locks out all the fields, but subselects do not.

Calculated column in writable data grid


Como trocar conteúdo sem trocar a estrutura?

Question: Comecei a fazer um site no código mesmo. Só que esse site vai ter várias páginas em que em toda página, a estrutura é a mesma, o que muda é apenas o conteúdo. Pra não ter que fazer no código página por página, fazer um monte de páginas, eu quero usar uma estrutura padrão fazendo include com php e pegando o conteúdo no mysql.
Exemplo:
https://www.youtube.com/watch?v= <- estrutura padrão | define conteúdo -> KPlPa07KBR0
https://www.facebook.com/pg <- estrutura padrão | define conteúdo -> /zulaxcloud/
Comment: Geralmente para fazer esse tipo de coisa se usa um framework MVC. Como por exemplo, o [Laravel](https://laravel.com).
Comment: @LuizFelipe tem alguma outro opção?
Comment: Não entendi qual a dúvida? Está com problemas nos `include`s?
Comment: @GuilhermeCostamilam na verdade eu queria fazer uma estrutura só para vários conteúdos. Por exemplo: www.meuseite.com/pg1 - www.meuseite.com/pg2 - www.meuseite.com/pg3
No caso, ele vai usar a mesma estrutura, mesmo template para as 3 páginas, o que vai mudar seria apenas o conteúdo.
Comment: E qual o problema, o que você não está conseguindo fazer? A única coisa que precisa é um index com o layout e design, as consultas e os include
Comment: @GuilhermeCostamilam eu já tenho a página padrão, as consultas e os includes. Mas como que eu vou criar um link para acessar um tipo de conteúdo usando a página padrão?
Answer: Se você já tem tudo pronto, você pode configurar o arquivo .htaccess para criar uma url amigável, como o próprio stackoverflow usa, um exemplo simples:
<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteRule ^pagina/([0-9]+)/?$ /index.php?pagina=$1 [NC]
</IfModule>

Isso fará com que páginas examplo.com/pagina/n, sendo n qualquer número inteiro, sejam redirecionadas para index.php, lá você pode pegar a página com o get e usar para buscar os dados no banco
<?php
    echo $_GET["pagina"];
?>

Para entender melhor como usar o arquivo .htaccess veja esse artigo
Comment: Isso mesmo que eu precisava. Obrigado!


UITextField doesn't update

Question: I have created programmatically 2 UITextfield that I want cleared before editing. The problem is when I clic on the UITextfield, they clear well (I check it with NSLog) but the View doesn't update.
When I edit with the keyboard the textfield, the new string seems to append the existent string (instead of clearing and editing) but, in fact the textfield doesn't edit.
I have read all the forums relative to this problem but I can't find a solution. It seems to be a thread problem with the UITextFieldDelegate...
Note that the UITextFields are embedded in a scrollView.
I have already tried setNeedsDisplay on my textfields, clearsOnEditing property, putting the code in the "textFieldsShouldBeginEditing" and "textFieldsDidBeginEditing" methods and  a lot of other things without success. Some help would be very cool !
The code relative to the textfields :
<code>@implementation gaineViewController

- (UITextField *)hauteurText {
if(!_hauteurText){
_hauteurText = [[UITextField alloc]init];
_hauteurText.clearsOnBeginEditing = YES;
_hauteurText.delegate = self;
_hauteurText.keyboardType = UIKeyboardTypeNumbersAndPunctuation;

}
return _hauteurText;
}

- (UITextField *)largeurText {
if(!_largeurText){
_largeurText = [[UITextField alloc]init];
_largeurText.clearsOnBeginEditing = YES;
_largeurText.delegate = self;
_largeurText.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
}

return _largeurText;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

if ([textField isEqual:self.largeurText]) {
NSLog(@"%@",self.largeurText.text);
self.largeurText.text=@"";
NSLog(@"%@",self.largeurText.text);
}

if ([textField isEqual:self.hauteurText]) {
NSLog(@"%@",self.hauteurText.text);
self.hauteurText.text=@"";
NSLog(@"%@",self.hauteurText.text);
}

return YES;
}

@end
</code>
Comment: Have you tried checking textField == self.hauteurText. This is valid because you're actually looking at the same exact instance (identity matters instead of equality).
Comment: Nothing wrong with the code you posted. Post more.
Comment: Where/how do you actually put the text fields into a view?
Answer: You said "It seems to be a thread problem with the UITextFieldDelegate..."
What do you mean, thread problem? UIView objects in iOS are not thread-safe. Are you trying to update the UI from a background thread? If so, that's your problem.

UITextField doesn't update


How to capture the content of stdout/stderr when I cannot change the code that prints?

Question: I have a function foo that can't be modified and contains println! and eprintln! code in it.
fn foo() {
    println!("hello");
}

After I call the function, I have to test what it printed so I want to capture the stdout/stderr into a variable.
Answer: I strongly recommend against doing this, but if you are using nightly and don't mind using a feature that seems unlikely to ever be stabilized, you can directly capture stdout and stderr using hidden functionality of the standard library:
#![feature(internal_output_capture)]

use std::sync::Arc;

fn foo() {
    println!("hello");
    eprintln!("world");
}

fn main() {
    std::io::set_output_capture(Some(Default::default()));
    foo();
    let captured = std::io::set_output_capture(None);

    let captured = captured.unwrap();
    let captured = Arc::try_unwrap(captured).unwrap();
    let captured = captured.into_inner().unwrap();
    let captured = String::from_utf8(captured).unwrap();

    assert_eq!(captured, "hello\nworld\n");
}

It's very rare that a function "cannot be changed", so I'd encourage you to do so and use dependency injection instead. For example, if you are able to edit foo but do not want to change its signature, move all the code to a new function with generics which you can test directly:
use std::io::{self, Write};

fn foo() {
    foo_inner(io::stdout(), io::stderr()).unwrap()
}

fn foo_inner(mut out: impl Write, mut err: impl Write) -> io::Result<()> {
    writeln!(out, "hello")?;
    writeln!(err, "world")?;
    Ok(())
}

See also:

How can I test stdin and stdout?
How to take ownership of T from Arc<Mutex<T>>?
How do I convert a Vector of bytes (u8) to a string?
Answer: Not sure if this would work on windows, but should work on unix like systems. You should replace the file descriptor to something you can read later. I don't think it is really easy.
I would suggest to use stdio_override which already does that for you using files. You can redirect it, then execute the function and the read the file content.
From the example:
use stdio_override::StdoutOverride;
use std::fs;
let file_name = "./test.txt";
let guard = StdoutOverride::override_file(file_name)?;
println!("Isan to Stdout!");

let contents = fs::read_to_string(file_name)?;
assert_eq!("Isan to Stdout!\n", contents);
drop(guard);
println!("Outside!");

The library also support anything that implements AsRawFd, through the override_raw call. Confirming that it will probably just work on unix.
Otherwise, you can check on the implementation on how it is done internally, and maybe you could bypass a writer instead of a file somehow.
Answer: Shadow println!:
use std::{fs::File, io::Write, mem::MaybeUninit, sync::Mutex};

static mut FILE: MaybeUninit<Mutex<File>> = MaybeUninit::uninit();

macro_rules! println {
    ($($tt:tt)*) => {{
        unsafe { writeln!(&mut FILE.assume_init_mut().lock().unwrap(), $($tt)*).unwrap(); }
    }}
}

fn foo() {
    println!("hello");
}

fn main() {
    unsafe {
        FILE.write(Mutex::new(File::create("out").unwrap()));
    }
    foo();
}

Comment: It's very interesting vision to solve the problem. Thank you very much.
Comment: This doesn't make sense. If `foo` is inside of the user's code, then they could change it. If it's not inside of their code, then shadowing `println` will have no effect.
Comment: "*they could change it*" That contradicts what OP says: "*can't be modified*". OP writes "*I have*" -> hints at being their code but being unable to change it for a foreign reason. For example it could be homework.
Comment: My pleasure @Brad


How to redirect the k8s dashboard through NGINX

Question: I have managed to launch the dashboard on localhost e.g.: http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/ as documented on the official page Web UI (Dashboard) but when I access the url I get the through the node-name I get the following error:
Insecure access detected. Sign in will not be available. Access Dashboard securely over HTTPS or using localhost.
According to the documentation Login not available the user should either connect through localhost (not possible in my case because of headless node) or connect as https:/...
I am trying to redirect the default dashboard url to https:node.test but I can not get it working.
My current configuration:
server {
        listen                  443    ssl     http2;
        server_name             node.test;

        ssl_certificate         /etc/nginx/certs/cert.crt;
        ssl_certificate_key     /etc/nginx/certs/key.crt;

        ssl_ciphers                     HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers       on;
        ssl_protocols                   TLSv1.2 TLSv1.3;

        # 10MB shared ssl session with timeout 10 min
        ssl_session_cache               shared:SSL:10m;
        ssl_session_timeout             10m;

        rewrite ^/$ http:/localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/ break;
}

I get a 404 response sample:
$ curl https://node.test

<title>404 Not Found</title>

404 Not Found

nginx/1.16.1

Sample of how I am launching the kubectl proxy:
$ kubectl proxy --port=8001 --address='node' --accept-hosts="^*$"
Starting to serve on IP:8001

How can I get the correct redirect?
Answer: In case that helps someone else in future the solution is the following:
server {
        listen                  443    ssl     http2;
        server_name             node.test;

        ssl_certificate         /etc/nginx/certs/cert.crt;
        ssl_certificate_key     /etc/nginx/certs/key.crt;

        ssl_ciphers                     HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers       on;
        ssl_protocols                   TLSv1.2 TLSv1.3;

        # 10MB shared ssl session with timeout 10 min
        ssl_session_cache               shared:SSL:10m;
        ssl_session_timeout             10m;

        location / {
                proxy_pass              http://node:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/;
        }
}

Assuming that you have the kubectl proxy running in the background and listening:
$ kubectl proxy --address node --accept-hosts '.*'
Starting to serve on IP:8001

Update: In case that someone else would like to add a loadbalancer for the UI it can be done like this:
upstream kubernetes-ui-dev {
        least_conn;
        server  hostname_here:8001;
        # another server
        # another server
}

server {
        listen                          4443    ssl     http2;
        server_name                     node.test;

        ssl_certificate                 /etc/nginx/certs/cert.crt;
        ssl_certificate_key             /etc/nginx/certs/key.crt;

        ssl_ciphers                     HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers       on;
        ssl_protocols                   TLSv1.2 TLSv1.3;

        # 10MB shared ssl session with timeout 10 min
        ssl_session_cache               shared:SSL:10m;
        ssl_session_timeout             10m;

        location / {
                proxy_pass              http://kubernetes-ui-dev/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/;
        }
}

Hope this helps someone else also.


Programmatically rearrange order of entity reference list on node

Question: My content type has a node reference field that allows users to enter an unlimited amount of nodes in. I need to programmatically change what comes first in this list.
Using the code below I'm able to obtain the data from the field.
<code>$node = \Drupal::entityTypeManager()->getStorage('node')->load($function);
$focus = $node->field_focus_area->getValue();
</code>
And it produces:
<code>array(2) {
  [0]=>
  array(1) {
    ["target_id"]=>
    string(2) "31"
  }
  [1]=>
  array(1) {
    ["target_id"]=>
    string(3) "161"
  }
}
</code>
In order to rearrange it I tried doing
<code>$newOrder[0] = ['target_id'=> 161];
$newOrder[1] = ['target_id'=> 31];

$focus->field_focus_area->rekey($newOrder);
</code>
But it was then when I realized that rekey was a protected function so I could use it. How would I programmatically rearrange the deltas (if that's what you'd call it) of an entity reference field programmatically?
Answer: After getting and rearranging the field data you can set it again:
<code>$node->field_focus_area->setValue($newOrder);
</code>


Finding the generating function of $\sum_{k=1}^n k^2$

Question: I am new to generating function and I am stuck with this problem, any suggestion on how to solve it. Thank you
Comment: Firs of all, do you know the existence of a closed form expression for $\sum_{k=1}^{k=n} k^2$ ?
Comment: Have you worked on this subject  ? Besides have you been given a methodology for example, how to find the generating function of Fibonacci sequence ?
Comment: I am trying to find the closed form of this summation using ordinary generating function
Comment: You haven't answered my first question...
Comment: I haven't work much on this subject, but I know the generating formula for Fibonacci sequences
Comment: The formula I was referring to is $\sum_{k=1}^{k=n} k^2=\dfrac16 n (n+1)(2n+1)$, though you can do without it...
Answer: \begin{align}
\sum_{n\ge 0} \sum_{k=1}^n k^2 z^n
&= \sum_{k\ge 1} k^2 \sum_{n=k}^\infty z^n \\
&= \sum_{k\ge 1} k^2 \frac{z^k}{1-z} \\
&= \frac{1}{1-z} \sum_{k\ge 1} k^2 z^k  \\
&= \frac{1}{1-z} \sum_{k\ge 1} (k(k-1)+k) z^k  \\
&= \frac{1}{1-z} \left(z^2 \sum_{k\ge 1} k(k-1) z^{k-2} + z \sum_{k\ge 1} k z^{k-1}\right)  \\
&= \frac{1}{1-z} \left(z^2 \frac{d^2}{dz^2}\sum_{k\ge 1} z^k + z \frac{d}{dz}\sum_{k\ge 1} z^k\right)  \\
&= \frac{1}{1-z} \left(z^2 \frac{d^2}{dz^2}\frac{z}{1-z} + z \frac{d}{dz}\frac{z}{1-z}\right)  \\
&= \frac{1}{1-z} \left(z^2 \frac{2}{(1-z)^3} + z \frac{1}{(1-z)^2}\right)  \\
&= \frac{z(1+z)}{(1-z)^4}
\end{align}
Comment: [+1] This derivation is more classical than mine, therefore more advisable to a newcomer in the field...
Answer: Rearrange the terms of the generating function
$$G(x)=1x+(1+4)x^2+(1+4+9)x^3+(1+4+9+16)x^4+\cdots$$
in this way :
$$\begin{array}{ccccc|r}
&&&&&\text{sum of lines}\\
\hline
1x&1x^2&1x^3&1x^4&\cdots&x\dfrac{1}{1-x}\\
&4x^2&4x^3&4x^4&\cdots&4x^2\dfrac{1}{1-x}\\
&&9x^3&9x^4&\cdots&9x^3\dfrac{1}{1-x}\\
&&&16x^4&\cdots&16x^4\dfrac{1}{1-x}
\end{array}$$
(the sum of lines are consequence of the famous formula for the sum of a geometric series).
Summing the last column, we get
$$G(x)=\underbrace{(x+4x^2+9x^3+16x^4+\cdots)}_{\gamma(x)}\dfrac{1}{1-x}$$
The first factor, $\gamma(x)$, is the generating function of the squares of integers, simpler to be analyzed.
You will find how one can obtain a closed form formula for $\gamma(x)$ at the end of paragraph 2.4 page 5 of this excellent MIT document
how to obtain a compact form for $\gamma(x)$.
For more information about the sequence of so-called pyramidal numbers, see here.


Is there is any module which creates new users by reading a spreadsheet/excel file?

Question: Could anyone tell me if there is any module which creates new users by reading a spreadsheet/excel file? I have added few more fields to the user registration form, and that might make this a bit tricky! Any suggestions would be helpful.
Comment: agreed totally! My bad.
Comment: dont understand how come someone would downvote a simple question!
Comment: I guess you could pretty well Google up User Import module on your own. Most of simple questions already have answers easy to find, so asking them is - usually - a sign of lack of effort and "do my work for me" approach. Not always, but when it may look like that, be prepared to get downvotes, or show what you have tried and how did it failed your expectation. But then it's not a simple question anymore.
Answer: Try out the user import module

Import users into Drupal, or update existing users, with data from a
  CSV file (comma separated file). Provides a wide range of features out
  of the box, and a comprehensive API to customise imports.
Comment: Full excel support is way above anything inside Drupal will be ever able to do, unless someone'll pour nice amount of money to get it to work.
Comment: well..I have seen this module but it supports only CSV, but my client wants excel import.
Comment: Then save the excel file as a csv file
Answer: Well, from my experience, importing users could be a tricky task.
The user import module is nice and easy, but if you'll need more features, you'll end frustrated. Some field types aren't supported (e.g. date fields). Importing Profile2 fields, if you'll need them, is almost impossible. The last patch is one year old (it's mine), it's not 100% working, and no other tried to continue working on it. But if you can switch to CSV, it'll get you up and running very quickly. You can send an email to the new users so they can activate their account, you can automatically generate usernames and roles etc.
If XLS is mandatory you should switch to Feeds and the Feeds XLS parser. By adding Feeds Profile2 you can also easily import Profile2 fields. Just remember that if you use Feeds, you won't be able to automatically enable and mail users. You'll have to modify Drupal's registration mail template to suit you needs, and then manually enable the imported users. At that point they'll receive the signup email.
Since I've started my site using User Import I'm continuing with it, but after importing basic user info I'm passing the CSV again to the Feeds module in order to update the users with the Profile2 info and with the fields that aren't supported by User Import. I'm also considering to totally switch to the Feeds module, but at the moment I don't have time, plus I'm too lazy.
So: if you want an easy module, CSV is OK and you have simple fields to import, go for User Import. If you need XLS, you have advanced fields or Profile2 info and you don't mind having some extra complexity, Feeds is the way.


Compute: $\sum\limits_{n=1}^{\infty}\frac {1\cdot 3\cdots (2n-1)} {2\cdot 4\cdots (2n)\cdot (2n+1)}$

Question: Compute the sum:
$$\sum_{n=1}^{\infty}\dfrac {1\cdot 3\cdots (2n-1)} {2\cdot 4\cdots (2n)\cdot (2n+1)}$$
At the moment, I only know that it's convergent and this is not hard to see if you look at the answers here I received for other problem with a similar series. For the further steps I need
some hints if possible. Thanks!
Comment: Guys, thanks a lot for your nice answers (+1)! The value of the series is really beautiful.
Answer: Starting with the power series derived using the binomial theorem,
$$
(1-x)^{-1/2}=1+\tfrac12x+\tfrac12\tfrac32x^2/2!+\tfrac12\tfrac32\tfrac52x^3/3!+\dots+\tfrac{1\cdot2\cdot3\cdots(2n-1)}{2\cdot4\cdot6\cdots2n}x^n+\cdots
$$
and integrating, we get the series for
$$
\sin^{-1}(x)=\int_0^x(1-t^2)^{-1/2}\mathrm{d}t=\sum_{n=0}^\infty\tfrac{1\cdot2\cdot3\cdots(2n-1)}{2\cdot4\cdot6\cdots2n}\frac{x^{2n+1}}{2n+1}
$$
Setting $x=1$, we get
$$
\sum_{n=1}^\infty\tfrac{1\cdot2\cdot3\cdots(2n-1)}{2\cdot4\cdot6\cdots2n}\frac{1}{2n+1}=\sin^{-1}(1)-1=\frac\pi2-1
$$
Answer: We have
$$\sum_{n=1}^{\infty}\dfrac {1\cdot 3\cdots (2n-1)} {2\cdot 4\cdots (2n)\cdot (2n+1)}
= \sum_{n=1}^\infty {2n\choose n}\frac{1}{4^n(2n+1)}.$$
Now notice that
$$\int_0^{1/2}dx\, 2x^{2n} = \frac{1}{4^n(2n+1)}.$$
Thus, we need only compute the sum
$$\begin{eqnarray*}
2\sum_{n=1}^\infty {2n\choose n}x^{2n}
&=& 2\sum_{n=0}^\infty {2n\choose n}x^{2n} - 2 \\
&=& \frac{2}{\sqrt{1-4x^2}} - 2
\end{eqnarray*}$$
and integrate.
Answer: Let's rewrite this as :
$$\sum_{n=1}^{\infty}\frac {1\cdot 3\cdots (2n-1)} {2\cdot 4\cdots (2n)\cdot (2n+1)}=\sum_{n=1}^{\infty}\frac {(2n)!} {4^n (n!)^2(2n+1)}$$
But this is merely the expansion of $\arcsin(x)-1$ for $x=1$ as found at this page on central binomial series :
$$\arcsin(x)=2\sum_{n=0}^{\infty}\frac{\binom{2n}{n}}{2n+1}\left(\frac x2\right)^{2n+1}$$
That is $\ \displaystyle \arcsin(1)-1=\frac {\pi}2-1$
The previous link to Boris Gourévitch work concerning $\pi$ is rather interesting because of the many relations provided concerning $\binom{2n}{n}$ and because it shows that the central binomial term may be at the numerator as well as at the denominator (see $(378)$).
It will be at the numerator for $\arcsin(x)$ and at the denominator for $\arcsin(x)^2$ and $\dfrac{\arcsin(x)}{\sqrt{1-x^2}}$ (relation $(396)$) !
Comment: In [Mike Spivey's answer](http://math.stackexchange.com/a/77609) to my only question so far, the central binomial coefficient also appears in the denominator.


Understanding and distinguishing piano slurs and phrases

Question: I'm learning piano and recently encountered slurs and phrases. I'd like clarification on the following that relate to these two ideas.

The book[1] I'm using introduces the idea of phrases, then later introduces slurs:

In vocal music, singing more than one note on one syllable is shown by a slur...

The accompanying example shows pairs of slurred notes within existing phrases, along with lyrics. The phrase, including these slurred notes, are all played with the same hand.
Am I correct in taking these particular slurs to be for vocalist only? So, a pianist would play all these as a single phrase, ignoring these slurs?
Slur is defined much later as:

a curved line over or under a group of two or three notes. Think of it as a very short phrase...

So, do slurs only really have relevance for piano outside of phrases, as a way of indicating connectedness of notes, e.g. playing notes legato?
The definition in 2 doesn't explicitly mention it, but I've seen it mentioned that slurs connect different notes together, not the same repeated note.[2]
If you have repeated notes connected by a curved line across more than one bar, will this always represent a tied note, never slurred notes? (Or maybe a slurred repeated note is still potentially meaningful for piano if you're using the sustain pedal?)
It seems you can distinguish tie lines from slurs/phrases. Tie lines go between the notes, whereas slur and phrase markers tend to go "closer", and more over/under the affected notes. Is there any clear way of telling a slur apart from a phrase by the curved line's appearance alone, or do you always have to look at the number of notes and musical context?

[1]: The Classic Piano Course, Book 1 by Carol Barratt.
[2]: For piano, maybe, at least. You can have meaningful slurs on the same note for some instruments.
Answer: To answer point 4 first: ties and slurs are completely different things, although the notation looks similar. Ties always join notes at the same pitch, and indicate that the two written notes are played as a single long note. You will eventually see slurs over repeated notes at the same pitch, but don't worry about that yet.
The basic reason for writing ties is because some rhythms can't be written any other way. For example, you can't write a single note which starts in one bar, and ends in the middle of the following bar. You have to write two notes of the correct length to fill up the end of the first bar and the start of the second one, and tie them together.
Since you referenced a book for "absolute beginners," the following comments abut slurs are intentionally "the truth, but not the whole truth." The repertoire of the piano includes music written during the last 400 years or so, and during that time the meaning of musical notations has changed significantly. Trying to explain "everything" to a beginner would be confusing and overwhelming, rather than helpful.
Also, as you progress you will discover (or at least, you should discover) that piano music relies very much on creating illusions in the listener's mind - as an obvious example, since every note starts to decay in volume as soon as you have played it, playing a slow legato melody is literally impossible, but if you listen to a good performance of say Beethoven's Moonlight sonata (the first movement) that is what you think you are hearing, even though one long note of the "tune" may have become completely inaudible before the next note is played!
Slurs have different meanings for different instruments, and for singers. For example, for string instruments (violin, cello, etc) all the notes under a slur are played with one movement of the bow, but in some situations there can still be intentional gaps between the notes! In vocal music, slurs merely indicate that one syllable of the lyrics is sung to more than one note, and nothing more than that.
In piano music, you can make a rough distinction between "short" and "long" slurs.
"Short" slurs over 2 notes up to about 4 notes are the most informative. They mean that the notes should be joined together (legato), except for the last note which is played slightly shorter than its written value.
To be honest, Longer slurs don't mean very much in most piano music, except for a general indication to play legato, and to show the way the notes are grouped into phrases (which are often 4 bars long).
It is fairly common to see a long slur with short slurs "nested" under it. In that case, pay most attention to the short ones.
As you said, using the sustain pedal creates another set of possible options - but most likely your piano course won't introduce using the pedal until you can play fluently with both hands together. Synchronising both hands while they are doing "different things at the same time" is enough of a challenge at the start, without also using your right foot do to something different from either hand!
Answer: I think phrases and slurs are not totally consistent in the literature, and indications of articulation can occur within a larger phrase. If a slur line lies in between two notes that are the same pitch, then it is most likely a tie. But ties are not always written this way. Context is always important.


How can I only show the first image of a multi-value image field in the teaser?

Question: I have a content type with an image field that can contain an unlimited number of images. The field is used to display an image gallery in the full node view, but I also want to use the first image of the field in the teaser.
I vaguely remember doing something like this years ago in Drupal 6, but now I can't find any option to do this in Drupal 8. I'm not sure if I'm misremembering, or just looking in the wrong place.
How can I display only the first image of an image field in the teaser?
Answer: You can do this on your own easily by extending core's ImageFormatter class from a custom module. Simply copy core's ImageFormatter.php into a custom module. Rename everything properly, remove all methods except viewElements() and then add only one simple break; at the last line of the foreach in viewElements(). After enabling the module (or after flushing cache if you added the formatter to an existing custom module) you can choose the new formatter under display settings for your teaser view mode of your content type. Works in views, too.
Did that for you in a quick custom module: image_first_formatter.


Central limit theorem without independence

Question: Let $(X_n)_n$ be a sequence of i.i.d random variables following the uniform distribution $\mathcal{U}([0;1]).$ Let $f:\mathbb{R}^3 \rightarrow\mathbb{R},$ be a continuous function.
Prove that $$W_n=\frac{1}{\sqrt{n}}(\sum_{k=1}^nf(X_k,X_{k+1},X_{k+2})-n\int_{[0;1]^3}f(x,y,w)dxdydw)$$ converges in distribution.
The exercise seems to be an application of the central limit theorem, since $Y_n=f(X_n,X_{n+1},X_{n+2})-E[f(X_1,X_2,X_3)]$ have the same distribution, but the problem is that $(Y_n)_n$ are not independent,
I tried to write $$W_n=\frac{1}{\sqrt{n}}\sum_{k=1}^{\left \lfloor{\frac{n}{3}}\right \rfloor}Y_{3k}+\frac{1}{\sqrt{n}}\sum_{k=0}^{\left \lfloor{\frac{n-1}{3}}\right \rfloor}Y_{3k+1}+\frac{1}{\sqrt{n}}\sum_{k=0}^{\left \lfloor{\frac{n-2}{3}}\right \rfloor}Y_{3k+2},$$
This way, $(Y_{3n})_n,(Y_{3n+1})_n,(Y_{3n+2})_n$ are independent, so we can apply the central limit theorem, but in the expression of $W_n$ the considered random variables aren't independent so that we can say that the sum converges in distribution.
Is there a way to solve the problem? And more generally, the result remains true
if $(X_n)_n$ is i.i.d without knowing the related distribution?
This exercise is inspired from problem 10, page 156, from Theory of Probability and Random Processes. Maybe there is a way using Markov chains and ergodicity, but this is not in the program, since in the mentioned book, Markov chains and related results are explained, later, in other chapters.
Comment: Multivariate CLT?
Comment: You want to apply multivariate CLT?
Comment: $(Y_{3n},Y_{3n+1},Y_{3n+2})_n$ isn't independent
Answer: Let $Y_i:=f(X_i,X_{i+1},X_{i+2})$ and $\widetilde{Y}_i:=Y_i-\mathsf{E}Y_i$. It is clear that $Y_i$ and $Y_{i+j}$ are independent for $j\ge 3$. Split the sum of $\widetilde{Y}_i$'s into $K$ blocks of size $p$ with gaps of size $2$ between each pair of consecutive blocks, i.e., write
\begin{align}
\sum_{i=1}^{n} \widetilde{Y}_i&=(\widetilde{Y}_1+\cdots+\widetilde{Y}_p)+(\widetilde{Y}_{p+1}+\widetilde{Y}_{p+2})+(\widetilde{Y}_{p+3}+\cdots+\widetilde{Y}_{2p+2})+\cdots\\
&=\sum_{j=1}^K B_{n,j}+\sum_{j=1}^K S_{n,j}+R_n,
\end{align}
where $B_{n,j}:=(\widetilde{Y}_{(j-1)p+2j-1}+\cdots+\widetilde{Y}_{jp+2(j-1)})$, $S_{n,j}=\widetilde{Y}_{jp+2j-1}+\widetilde{Y}_{jp+2j}$, and $R_n$ is the remainder term.

Choose $K=\ln(n)$ and $p=n/\ln(n)$. Since $\{B_{n,j}\}_{j=1}^K$ is a triangular array of centered i.i.d. random variables, we can apply the central limit theorem (for triangular arrays). The approximation error consists of at most $3\ln(n)$ terms ($K$ terms of size $2$ and at most $\ln(n)$ terms in $R_n$) and is asymptotically negligible.
Comment: Is it possible to explicit $R_n$?
Comment: The exact expression is rather messy. $R_n\ne 0$ if $n$ is not exactly divisible.


How do I reply to a message only if it was from a DM in discord.js v14?

Question: I want my bot to reply only if the message was sent via DM, not on any of the channel's server.
These are my intents and partials
const client = new Client({
  intents: [
    IntentsBitField.Flags.Guilds,
    IntentsBitField.Flags.GuildMembers,
    IntentsBitField.Flags.GuildMessages,
    IntentsBitField.Flags.MessageContent,
    IntentsBitField.Flags.DirectMessages
  ],partials:[
    Partials.Channel,
    Partials.Message
  ]
});

And this is the code im trying to use to read DMs. I got it from a tutorial but I cant find the channel object when I log the message.
client.on('messageCreate', async (message) => {

    // Check if the message is a direct message (DM)
    if (message.channel.type === 'DM') {
      message.author.send('Message Received');
    }
  });

Any ideas?
I dont get the "Message Received" message when I send a dm but if i remove the dm verification i get the reply.
Answer: message.guild will be null inside a DM; this is one way to check if the message is from a DM.
if (message.guild === null) return;


C++ cmath pow error present in older version of the compiler, but not on the newer one

Question: With the 4.2.1 g++ compiler I get the following error:
functions.cpp:24: error: call of overloaded 'pow(long int&, long int&)' is ambiguous
/usr/include/architecture/i386/math.h:343: note: candidates are: double pow(double, double)
/usr/include/c++/4.2.1/cmath:373: note:                 long double std::pow(long double, int)
/usr/include/c++/4.2.1/cmath:369: note:                 float std::pow(float, int)
/usr/include/c++/4.2.1/cmath:365: note:                 double std::pow(double, int)
/usr/include/c++/4.2.1/cmath:361: note:                 long double std::pow(long double, long double)
/usr/include/c++/4.2.1/cmath:357: note:                 float std::pow(float, float)

Here's the responsible code:
long power(long a, long b) {
    if (b < 0) return 0;
    return pow(a,b);
}

However, on my 4.6.1 version there are no errors nor warnings for my code where I use two longs for the pow evaluation (even with the -Wextra flag).
Why is this? And is using two longs for the pow function a mistake on my part?
Comment: looks like 4.6 added `pow(long,long)` as an extension
Comment: The standard says it should be double http://pubs.opengroup.org/onlinepubs/9699919799/functions/pow.html So I believe that as long as you stick with the standard you're fine, you just need to do a cast.
Comment: Anycorn, could you provide a reference (post it as an answer)
Comment: I can't - the standard doesn't say anything about `pow(long,long)` - hence i assume it's an extension.
Comment: good work on your part to point out the difference in complilation!!
Comment: it seems to be part of c++0x which 4.6 implemetns: http://stackoverflow.com/questions/5627030/why-was-stdpowdouble-int-removed-from-c0x
Comment: I would be happy to accept an answer that directly shows where this casting is done (if this at all is possible).
Answer: As far as I know, pow is not confirmed to support long, long as parameters by ANSI. Please consider using double (or casts to) and if needed, round the result like this:
long int result = llround(pow((double)2L, (double)4L));

Answer: The problem is that there is no definition of pow that takes two longs as parameters. Because of this, the longs will be converted into some other data type, but this conversion causes ambiguity since there are many possible ways that the conversion can happen. gcc doesn't know how to interpret the call, so it gives you an error.
Comment: I understand this. But why is  problem in the older version of the compiler, but not on the newer one?
Comment: It could be that the newer version maps the call to a compatible method. For example, it might have some convention for type conversion. It might turn the longs into doubles so that it doesn't lose precision.
Answer: Pow has only support for double and not long.
Maybe in the newer version they added an implicit cast to double from long. thats the best i could think of.
i havent heard of extending suport to long in pow!


Given a sample of random variables, and n, how do I find the ecdf of the sum of n Xs?

Question: I can't fit $X$ to a common distribution so currently I just have $X \sim \text{ecdf(sample_data)}$.
How do I calculate the empirical distribution of $\sum(X_1 + ... + X_n)$, given $n$? $X_1$ to $X_n$ are iid.
My sample size is around $6\times10^7$. $n$ needs to be around 10-20.
To give an example of what I am doing: Suppose $X$ is the age of a person. If I put 10-20 people in a room, what is the distribution of the sum of ages in the room? I have lots of peoples ages, and no reason to fit the distribution of an age to any of the common distributions.
(previously on StackOverflow - suggested to move here).
Comment: Cammil, a possible interpretation of the question is that you have a large batch of $N$ data values $(x_1,x_2,\ldots,x_N)$; you stipulate a smallish number $n \le N$; and you wish to determine (or estimate) the distribution of $(x_{i_1}+x_{i_2}+\cdots+x_{i_n})$ as the indexes $(i_1,i_2,\ldots,i_n)$ range over all $n$-element subsets of $1,2,\ldots,N$. Am I on the mark?
Comment: The term empirical distribution refers to the sample distribution for the discrete set of n observations.  If you have n observed values Xi i=1,...n then the sum is just a single number. So what do you want from it?  Maybe I could say its empirical distribution is a point mass at the observe point.  But that can't possibly be what you want to know.
Comment: Now I'm confused about what the data actually is @cammil - can you clarify by editing the question?
Comment: @MichaelChernick, wouldn't it make sense to use the empirical distribution of the $X_{i}$'s, assume iid, and then use that to estimate the distribution of the sum? Of course, in that case you're right - empirical distribution would be the wrong terminology.
Comment: I have _way_ more than n data points. I need to know n for roughly n<= 20, I have about 6x10^7 data points.
Comment: That is basically correct. I have given an example of the situation I am modelling in my edit.
Answer: I will interpret your question to be: How can we estimate the sampling distribution for the sum (or equivalently, the mean) from a iid sample $X_1, \dotsc, X_n$ in a nonparametric way, without assuming anything about the common distribution of the $X_i$?
One approach would be bootstrapping, see Explaining to laypeople why bootstrapping works
Another (related) approach is using the saddlepoint approximation, there is an example in How does saddlepoint approximation work?
(these methods can also be used if the goal is sum/mean of a future iid sample of size $m$ possibly different from $n$, from the same population).  The saddlepoint approximation can be seen as approximating the bootstrap solution, but without simulation.
<code>EDIT after you clarified the Q in an edit
</code>
You have a very big sample, and want to estimate the cdf for subsampling a (much smaller) sample from that large sample. The ecdf from the big sample, as in the answer above, is still the right answer, assuming you are subsampling by simple random sampling (with or without replacement). If you have some weighted or stratified sample, the answer will be different.


Find all $f \in L^1(\mathbb{R})$ to satisfy $\int_{-\infty}^{\infty} f(t)e^{(-t^2+2xt)}dt = 0$

Question: The problem is

Find all $f \in L^1(\mathbb{R})$ to satisfy $\int_{-\infty}^{\infty} f(t)e^{(-t^2+2xt)}dt = 0$ a.e..

I'm studying convolution and Fourier transform in Folland chap 8. I faced this problem but I don't know at all. Someone help me?
Answer: The given equation is equivalent to $\int f(y)e^{-(y-x)^{2}}dy=0$ or $\int f(x-y)e^{-y^{2}}dy=0$. The convolution of $f$ with the exponential is therefore $0$ a.e.. Taking FT we see that $\hat {f} \hat {g}=0$ where $g(y)=e^{-y^{2}}$. $\hat {g}$ is never  $0$ and so we get $\hat {f}=0$ which implies $f=0$ a.e.
.
Comment: What about the $e^{x^2}$ outside the convolution?..because i pressume you added and substracted $x^2$ in the exponent.
Comment: $e^{x^{2}}$ comes out of the integral. Since this function is never $0$ you can cancel it. @MariosGretsas
Comment: Yes yes..i forgot  that there is an equation to be solved.. i just had in mind only the appropriate expression for the integral... my apologies...:) +1


centos cron job running php file

Question: I have a php file under php called test.php set to run every 5th minute of the hour.
When ever I run the file manually (by going to the web browser and runnint the path) it works fine. But when the cron job tries to run it I get the error message
my cron job is
<code>#### Delete Records
5 * * * * /var/www/html/phpsysinfo/cronUpdateLeadBucketOnEnergycAlliance.php
</code>
my phpfile is (path : /var/www/html/phpsysinfo/phpfile)
<code><?php
require("dbconnect.php");
 $sql = mysql_query("DELETE FROM list where status <> 'LEAD'") or die(mysql_error());
?>
</code>
and the error that I get is:
<code>/var/www/html/phpsysinfo/phpFile.php: line 1: ?php: No such file or directory
/var/www/html/phpsysinfo/phpFile.php: line 2: syntax error near unexpected token `"dbconnect.php"'
/var/www/html/phpsysinfo/phpFile.php: line 2: `require("dbconnect.php");
</code>
thanks
Answer: You're missing the call to the php binary in your cron, it should look like this
<code>### Delete Records
5 * * * * php -q /var/www/html/phpsysinfo/cronUpdateLeadBucketOnEnergycAlliance.php
</code>
Please substitute php with php-cli depending on how the php command line binary is named on your distribution :)
Comment: ...you will probably have to specify the path to the php binary too.
Comment: only if php is in a location not available in the PATH but yeah, good point :) +1
Comment: ok, strictly speaking you "should" include the path to the php binary so that you are explicit about what you are running and not getting hijacked by something unexpected in the path.

centos cron job running php file


Como substituir todos valores de uma determinada tabela no MYSQL de uma vez?

Question: Tenho uma tabela (produtos) que tem a coluna product_params
Varios produtos estão com o valor dessa tabela com max_order_level="" e quero substituir todos para max_order_level="1", ou seja, trocar o valor vazio de max_order_level para 1.
Há uma forma que eu possa fazer isso tudo de uma só vez?
Comment: Qual é o tipo da coluna?
Comment: ela é varchar(255)
Comment: Update produto set max_order_level="1"; se quer fazer isso em todos os produtos da tabela não precisa de where.
Answer: Sim. Deve haver várias, aqui está uma delas:
Você pode usar a função REPLACE (não confundir com o comando REPLACE) no update. Ela vai te retornar a string original completa, somente com a parte procurada substituída.
Assim:
UPDATE produtos
    SET product_params = REPLACE(product_params, 'max_order_level=""', 'max_order_level="1"')
WHERE product_params LIKE '%max_order_level=""%'

A única restrição seria que o produto tivesse esse parâmetro definido como você espera (max_order_level=""), só para reduzir a quantidade de registros afetados para os que o serão efetivamente.
Veja esse exemplo funcionando no sql fiddle.


Do dichotomous or continuous moderators lead to most statistical power when testing interactions?

Question: My understanding is that, in general, continuous variables offer more power over dichotomous variables. For example, doing a between groups (e.g., men vs. women) t-test testing height would be better than doing a chi-square test (e.g., men vs. women) testing height with dichotomous groups (e.g., tall vs. short).
I am interested in testing moderation, namely, whether depression (moderator) affects outcomes differentially across two different anxiety treatments. I think depressed people will do better in one treatment over the other.
I was going to test for moderation using a continuous depression variable, but landed upon the following statement (http://davidakenny.net/cm/moderation.htm):
"Power for tests of moderation is very low when one or both of the variables are continuous (McClelland & Judd, 1993)." I took a look at McClelland & Judd, 1993 and could not find the rational for this. I am now wondering whether I should split depression into high/low groups and examine slopes in each group rather than test for interaction using a continuum
Do dichotomous or continuous moderators lead to most statistical power when testing interactions?
Answer: The question is quite tricky as it depends on different properties of the data set.
The paper of McClelland and Judd is a very bad choice of a reference (even though it is cited a lot) as there is numerous problems in the paper. It is also not about dichotomous versus continuous variables even though there is an example on the matter, i.e., the "field study" vs "experiment study", which, btw, is very poorly designed if you look closely, and most of the paper is based on it.
The first problem (or lack of power thereof) that can occur is when the "natural" scale of the variable is continuous but is dichotomized. This leads to reduce variance in the variable, which reduces the effect. This problem is similar to median-spliting, for instance, which is not a practice recommended. This is however hard to capture as it more theoretically-orientated than statistical.
The second consideration is how the variables are correlated to each other, which is independent on their scale, but may or may not be artificially enhanced by the scaling.
The third consideration is that, dichotomous variable that are fixed (let say 50-50 like in an experimental design) will have no sampling error in the long run, which will reduce the sampling error, which increases power. This may be an increase in power associated to dichotomous variables.
I have not found yet a good account as to what cause the increase in sampling error in moderation analysis. It is somewhat related to this still open post with no definitive (or convincing) answers.
Answer: Artificially dichotomizing a continuous variable is generally agreed to lead to less power. However, if the only difference between the analyses is the continuous vs. binary variables (e.g., all the effect sizes are the same and the variances are the same) then there is hardly any difference. The example in McClelland & Judd, 1993 is weird because they make such sweeping statements, but in their simulated example the binary variables have an SD of 1, but the continuous variables have and SD of 0.5 (pg. 379, 3rd paragraph). So of course the continuous interaction is worse. They seem to have made this choice so that the range of the continuous and and binary variables is the same, without considering the implications of different standard deviations.


How do I check for C++11 support?

Question: Is there a way to detect at compile-time if the compiler supports certain features of C++11?  For example, something like this:
#ifndef VARIADIC_TEMPLATES_SUPPORTED

#error "Your compiler doesn't support variadic templates.  :("

#else

template <typename... DatatypeList>
class Tuple
{
    // ...
}

#endif

Comment: You could have a header called "assert_variadic_template_support.hpp" that you can include and within do something like `template  struct compiler_must_support_variadic_templates;`. A syntax error would quickly reveal the problem. (Just as an aside, a proper error message is much better.)
Comment: The 'right' way to solve this problem is a configure test.
Answer: There is a constant named __cplusplus that C++ compilers should set to the version of the C++ standard supported see this
#if __cplusplus <= 199711L
  #error This library needs at least a C++11 compliant compiler
#endif

It is set to 199711L in Visual Studio 2010 SP1, but I do not know if vendors will be so bold to increase it already if they just have (partial) compiler-level support versus a standard C++ library with all the C++11 changes.
So Boost's defines mentioned in another answer remain the only sane way to figure out if there is, for example, support for C++11 threads and other specific parts of the standard.
Comment: C++11 sets the value of `__cplusplus` to `201103L`. That asserts full conformance to the 2011 standard; it doesn't tell you about partial conformance or compiler extensions. If `__cplusplus` is set to `201103L`, then either the compiler fully conforms or it's lying to you. If it's not, then you can't really tell which features it supports.
Comment: @DonaldDuck: Strictly speaking, no, they don't. A compiler that sets `__cplusplus` to `199711L` is not a conforming C++11 compiler. They probably have options to make them behave correctly.
Comment: g++ 4.7.x (and presumably newer) sets this when `-std=c++11` option is specified (may also with `-std=gnu++11`).  They do this, even though they are not quite feature complete (4.8 brings us a lot closer).  Note - there is a gap between what the compiler supports and what's available in the standard library. Both 4.7.x & 4.8.x are currently missing regex support - but that's a library, not a compiler feature.
Comment: I wonder why this is not the accepted answer. Also, you could use [this suggestion](http://stackoverflow.com/questions/5047971/how-do-i-check-for-c11-support#comment23849959_10849807) to further improve your answer, it's very good.
Comment: @KeithThompson For me, both Code::Blocks and Visual Studio set the value of `__cplusplus` to `199711L` for C++ 11.
Comment: This answer makes no sense; why would we look for 1997, if we need to test for C++11 support.  C++ was first standardized in 1998, so every C++ compiler should be setting this to at  least 199711 if it conforms to any version of ISO C++ at all.
Comment: Regarding *"I do not know if vendors will be so bold to increase it already if they just have (partial) compiler-level support versus a standard C++ library with all the C++11 changes."*   The assumption should be that the OP wants a test of a decently high confidence for C++11. If the vendors are not bold enough to announce C++11 support via `__cplusplus`, then the confidence level is poor. Some C++11 feature the program depends on might in fact not be there.
Comment: 199711L was the best available information at the time. In Stroustrup's own words: "In C++11 the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L. " - feel free to give an up-vote to more recent answers with the actual constant used in the finalized standard, I'll do the same! | Adoption happens incrementally, so I think it was fair to mention Boost for more granular checking :)
Answer: As stated by the C++11 standard (§iso.16.8):

The name __cplusplus is defined to the value 201103L when
  compiling a C++ translation unit.

With the value of that macro, you can check whether the compiler is C++11 compliant.
Now, if you are looking for a standard way to check if the compiler supports a whatsoever subset of C++11 features, I think there is no standard, portable way; you can check compilers documentation or std library header files to get more information.
Comment: For example, static_assert is supported in VS2010 and in all c++11 copilers. So, if you check for a value of  __cplusplus greater or equal than the one set in VS2010 (i.e. >= 199711L), you can be fine.
Answer: I know that this is a very old question, but this question might be often seen, and the answers are a bit out of date.
Newer compilers with the C++14 standard have a standard way to check features, including C++11 features. A comprehensive page is at https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
In summary, each feature has a standard macro defined that you can check with #ifdef. For example, to check for user defined literals, you can use
#ifdef __cpp_user_defined_literals

Comment: I didn't know that. I think that this simple feature is coming late, but still can be very useful, especially the `__has_include()` macro.
Comment: Does it exist for C++20 or C++23 features ? It is quite painful that, when using a C++20 feature, you never know if the compiler implements it. I know that there is a list on https://en.cppreference.com/w/cpp/compiler_support/20 but it is not obvious to find the feature from its title and I don't want to check everytime I use a feature..
Answer: You can use this:
#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900)
    cout << "C++11 is supported";
#else
    cout << "C++11 is not supported";
#endif

For C++11, most compilers set the __cplusplus macro at 201103L. But Visual Studio, depending on how old it is and how it's configured, sets it at 199711L, which is the value used by other compilers for before C++11.
This code compares the _cplusplus macro with 201103L for all compilers except Visual Studio, and if the compiler is Visual Studio, it checks if the version of Visual Studio is later than 2015, the first version of Visual Studio which completely supports C++11 (for Visual Studio 2015, the _MSC_VER macro has the value 1900, see this answer).
Comment: This answer is incorrect. For `g++ -std=c++98` with GCC 4.8, it incorrectly prints `C++11 is supported`.
Comment: @pts Sorry, just a typo. It should be fixed now.
Answer: For check support C++14 and other. Testing on GCC 5.2.1.
#include <iostream>

int main(){
        #if __cplusplus==201402L
        std::cout << "C++14" << std::endl;
        #elif __cplusplus==201103L
        std::cout << "C++11" << std::endl;
        #else
        std::cout << "C++" << std::endl;
        #endif

        return 0;
}

Answer: If you do not want to use Boost.Config and need to test for compilers that support C++11 then checking the value of the constant __cplusplus will do. However, a compiler might support most of the popular features of the C++11 standard yet it does not support the entire specifications. If you want to enable support for specific Visual Studio compilers which are not yet 100% compliant to C++11 specifications then use the following code snippet which allows compiling in Visual Studio 2013:
#if defined(_MSC_VER)
#   if _MSC_VER < 1800
#       error This project needs atleast Visual Studio 2013
#   endif
#elif __cplusplus <= 199711L
#   error This project can only be compiled with a compiler that supports C++11
#endif

A complete list of versions of the compiler for Visual Studio is provided at How to Detect if I'm Compiling Code With Visual Studio 2008
Comment: This test will succeed in any C++ compiler that conforms to C++98 or later and that is not the Microsoft C++ compiler.
Answer: In the traditional Linux/Unix world, autoconf is traditionally used to test for the presence of libraries and compiler features and bugs placing them into a config.h that you use in your files as needed.
Comment: @LokiAstari: That's not how autoconf works. Autoconf provides macros that let you have your configure script compile a test source file and set the #define to 0 or 1 based on the success of the compilation. diverscuba23's answer provides information by pointing out the OP is reaching for a suboptimal solution to the real problem.
Comment: Yes autoconf can be used to test for features but it you must make it generate the appropriate macro for failure or successes that can then be tested by the code above. So by itself this answer adds no information.
Comment: http://stackoverflow.com/q/11909347/580412 https://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx_11.html
Answer: Quick history
When this question was asked in February 2011, support for C++11 was inconsistent. Compilers needed time to catch up to the standard, so in the meantime, they released with partial support. For example, a compiler might have implemented variadic templates, but not auto.
If you had code that depended on a subset of C++11 features, you didn't have a standard way of asking the compiler whether it supported them specifically.
You could check for overall C++11 support with #if __cplusplus >= 201103L, but:

That constant and its meaning weren't technically official until the standard was accepted later, in August 2011.
This was too coarse. Compilers probably only set __cplusplus to 201103L once they had full feature support—and no one had full feature support yet. So, if you used this, you would unnecessarily reject most or all of the compilers that people would want to use to compile your code.

One pragmatic solution was to use the third-party Boost.Config library, which maintained a bunch of feature test macros. Boost.Config's maintainers kept track of which compilers supported which features, and updated the macros accordingly for each Boost.Config release.
(This stuff about Boost is based on an early, now-deleted answer from @James McNellis.
Today
C++11
Today, there's a version of every major compiler that supports the whole C++11 standard. .
If your code requires any of C++11, it's now reasonable to require that the compiler supports all of C++11. So, use #if __cplusplus >= 201103L. (See @Paulo M's answer for a standards reference for this macro.) But beware that there are complications with MSVC—see @Donald Duck's answer.
Beyond
Since C++20, in addition to the coarse-grained __cplusplus macro, you can also #include <version> to get a bunch of feature test macros. This is basically a standards-based alternative to Boost.Config.
According to this answer from Jarryd, these macros are actually available in at least some 2016-era C++14 compilers.
Comment: I really wish there were additional macros which specify the respective version number assigned to a given standard. I.e., I wish the next C++ ISO standard would specify e.g.__cplusplus1998 as 199711L, __cplusplus2011 as 201103L, __cplusplus2014 as 201402L etc. Each new standard would add its own macro to the list. I have to look the values up every time I want to use one, and it is too easy to make typos.
Answer: When your check is for a C++11 library availability (not a language feature), for example the <array> header, you can #if __has_include(<array>).
Sometimes checking #if __cplusplus >= 201103L would tell you that you use C++11 but other settings like the standard library version setting in Xcode may still not have the new libraries available (most of them are available in different names ie <tr1/array>)

How do I check for C++11 support?


Correct way to make a DataMapper association

Question: I want to have a table of users. These users shall have n contacts and n messages..
My code is:
<code>...
class User
  include DataMapper::Resource

  property :id, Serial, :key => true
  property :nickname, String

  has n, :contacts
  has n, :messages
end

class Contact
  include DataMapper::Resource

  belongs_to :user

  property :id, Serial, :key => true
  property :authgiven, String

  has 1, :user
end

class Message
  include DataMapper::Resource

  belongs_to :user

  property :id, Serial, :key => true
  property :data, String
end

#apply models (validation etc.)
DataMapper.finalize
...
</code>
There are no errors initializing DataMapper, but when I try to create a new User or whatever, save always returns false... Can someone please point out what is wrong?
I'm quite new to DataMapper, it always worked for me with simple tables without relationships, so I believe it has to do with the way I declared the 1:n relationship...
Answer: Hey you should remove that has 1, :user line from Contact model and you should be good.
Comment: Well ok thx I found that already... I replaced it with an Integer which should store the id... It would be more elegant as an association, though...


Existe Data Annotation que evita duplicidade de dados no Banco?

Question: Como faço para evitar que dados sejam duplicados no banco usando Data Annotation ou seria através de outra validação?
Comment: Você quer criar uma **Unique Key** via *data annotation*, certo?
Comment: sim, por exemplo, e-mail único, produto único etc...
Comment: A resposta do Eduardo já resolve.
Comment: Ok, obrigado pela ajuda
Comment: @FabioSouza Está usando EF? Que versão?
Comment: @bigown desculpa a ignorância, mas o que seria EF? Entity Framework? se for é a versão 6
Comment: @FabioSouza, respondendo sua pergunta acima, EF, e abreviatura para Entity Framework.
Answer: public class User
{
   [Index(IsUnique=true)]
   public string UserName{get;set;}
}

Comment: com isto ele já verifica no banco se já tem a informação cadastrado?
Comment: o [Index(..)]  não é reconhecido pelo sistema, me da essa mensagem: **the type or namespace name 'Index' could not be found (are you missing a using directive or an assembly reference?)** e se eu clico **CTRL+ponto** ele pede pra gerar uma classe...
Comment: com isso ele vai criar um campo que não vai poder ter valores iguais. se você quer verificar vai ter que customizar seu data annotation.
Answer: Uma forma de fazer isso é com RemoteValidation, funciona assim: você deverá criar uma ActionResult que retorne um JsonResult com true or false indicando se a validação passou. Essa validação será feita por Ajax se usar a Unobtrusive Validation.
Isso não é um tipo da validação que irá criar um índice no banco de dados, o que lançaria uma exceção ao tentar salvar o dado duplicado. O índice te garante integridade, com certeza, mas essa solução é mais amigável ao usuário não sendo necessário tratar o fluxo da exceção. Use as duas soluções se for o caso.
No model:
// primeiro parametro é nome da ação, o segundo do controller
[Remote("ValidarEmailUnico", "Usuario", ErrorMessage = "E-mail já cadastrado")]
public string Email{ get; set; }

UsuarioController:
 public ActionResult ValidarEmailUnico(string Email)
 {
    var emailDisponivel = contexto.Usuarios.Where(u => u.Email == Email).Count() == 0;
    return Json(emailDisponivel, JsonRequestBehavior.AllowGet);
 }

Mais aqui: http://www.macoratti.net/15/02/aspn_vremt1.htm
Comment: No caso teria que inverter o retorno, pois Any irá retornar true se houver e-mail cadastrado.
Comment: `var emailDisponivel = contexto.Usuarios.Any(u => u.Email == Email);`  Assim ficar melhor  e mais performática.
Comment: isso, dessa forma é melhor, mas ele ainda teria que passar o parâmetro chave da tabela ...
Answer: Tem algumas formas, a que provavelmente é a mais adequada para você seria usar o atributo Index para criar um índice no banco de dados e indicar que ele deve ter chave única.
public class SuaClasse {
   [Index("NomeDoIndice", IsUnique = true)]
   public string ColunaUnica { get; set; }
}

Coloquei no GitHub para referência futura.
É possível montar o índice com várias colunas.
Não esqueça de adicionar o namespace System.ComponentModel.DataAnnotations.Schema para poder usar esse atributo.
Documentação.
Comment: o que seria o "NomeDoIndice"?
Comment: Seria o nome que quer dar ao índice dentro do banco de dados. Ele tem que ter um nome. È como se estivesse escrevendo isso no banco de dados. è como estivesse usando um `CREATE TABLE`.
Comment: Hum talvez seja por isso que ele estivesse dando erro ao executar meu sistema dizendo que minha tabela já existia... sabe o que eu poderia estar fazendo de errado ? Já tentei com o nome igual ao campo, nome diferente e até sem nome, mas dava sempre a mesma msg.
Comment: Aí o problema parece ser outro completamente diferente do que está na pergunta.
Comment: Este erro só aparece se estiver usando este annotation
Comment: Depois eu edito a pergunta mostrando o que eu fiz e o erro que da.
Comment: É, isso é normal, se você tira algo que está dando erro realmente ele não aparece, mas não é o que deseja. Não deve editar a pergunta, se tem outro problema, deve ser outra pergunta. Essa parece ter sido resolvida. Veja o [tour].


using an existing token as a variable in a custom token

Question: I am using simplenews to send out a newsletter.  I have a custom module.  It has a table that relates a user code to the user's email.
email_address                  user_code
firstname.lastname@example.com        37XylT12

In the simplenews email I will send, the idea is that each user will receive a link with their usercode in it (i.e., http://www.domain.com/?q=go&c=37XylT12).
I've been attempting to create a custom token to place in the text of the newsletter and replaced with my custom link prior to send.  However, I have two issues: 1) I cannot find an example of a token that includes a db_select query to return data and 2) I cannot find a way to access the simplenews email token ([simplenews-subscriber:mail]) in my custom module -- I need this value to lookup the code.
If someone could point me in the right direction, I would appreciate it.
KMT
Answer: Accessing the database to set a token is not different from accessing the database in other cases.
function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $sanitize = !empty($options['sanitize']);

  $replacements = array();

  if ($type == 'YOUR TOKEN TYPE') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'YOUR TOKEN':
          $replacements[$original] = /* CODE TO QUERY THE DATABASE */;
          break;
      }
    }
  }

  return $replacements;
}

As for accessing the value of a token defined from a module, when you know the token you are looking for, you can call token_replace() passing the token for which you want to know the value as first parameter. Keep in mind that your implementation of hook_tokens() is going to be called again; be careful of not causing a loop.
Comment: I've completed the database component and it is working with string values I type in, however, I'm struggling with the token_replace() function.  The token I'm trying to replace is below -- $text = token_replace('[simplenews-subscriber:mail]');  If I return $text to the page, it is correct.  However, if i try to use the value in php, it is [simplenews-subscriber:mail].  Please advise.
Comment: I am not sure I understand what you mean. In your code, you need to use $text as value of the token.
Comment: It was an issue I ran into calling a token from another module.  In the module, the variable $subscriber was set within the module.  The token_replace() call needed me to submit the variable of $subscriber, but I could not.  I ended up adding a custom token to the module in a separate, custom tokens.inc file.  It's not perfect, but it works.  Thanks for your help!


Why does the minor scale have modes?

Question: My knowledge of music theory is very limited at the moment. I'm in the process of learning about scales and modes. I've learned that the major scale has a mode for every degree of the scale. The 6th degree is the Aeolian, or natural minor, mode.
After learning more about the minor mode/scale (the terms seem to be used interchangeably when talking about Aeolian, but not the other modes ...), I see that it comes in a few flavors. Natural minor, melodic minor, harmonic minor. It also has modes of its own.
Why does the minor scale have modes? Do other modes of the major scale have modes of their own?
Answer: The harmonic minor and melodic minor scales are not modes of the natural minor scale. A mode is a very specific idea in music where you start building a scale on another note of the scale.
For example, A minor consists of the notes A, B, C, D, E, F, G, A  and it's built using the scale pattern W-H-W-W-H-W-W. You also may notice that C major consists of the notes C, D, E, F, G, A, B, C and it's built using the scale pattern W-W-H-W-W-W-H. As you can see, these scales are closely related and are created by starting at a different place in the scale pattern, and when we talk about modes of scales this is what we refer to. You would not call the melodic or harmonic scale a mode of the natural minor, but a scale that is based on that scale with a few deviations explained here.
The melodic and harmonic minor scales each do have modes and in general, any scale will have N modes where N is the number of distinct notes in it, with a few exceptions because of symmetric scales like the whole tone and chromatic.
Most scales I can name are modes of the standard major/minor scale, the harmonic minor scale, and the melodic minor scale, so if you just study those, you'll have a lot of material. You can still encounter/make new scales and they will have names based on what scales they relate to. For example, if you really wanted to, you could build a melody & harmony off the major scale with a lowered 2nd degree. In C, this would be:

C - Db - E - F - G - A - B

You would call this Ionian b2 because it is pretty much the Ionian/major scale with a lowered 2nd.
Comment: @grinch every mode has a scale. A minor is a scale. It is also a mode of the major scale. Think of a mode as more of a relationship between scales where you could say major is a mode of minor or vice versa depending on context. And yes Ionian b2 is based off the major scale, but is not a mode of it and it will have 7 modes because it has 7 notes in its scale.
Comment: This clarifies it quite a bit. To solidify a few things for myself - am I right in the following conclusions? In your first example, with A minor... A minor is not technically a scale of it's own because it shares the exact notes of C major. So it is a mode of C major built off of the 6th tone. So natural minor does not have any modes. In the last example with Ionian b2 - this is a scale based on the major scale. Because it has an altered set of notes, this would have it's own set of modes.
Comment: @grinch All modes share the name notes as their parent major (Ionian) scale. In fact, if they don't they can't be a mode. Dom's example of Ionian b2 is, as Dom said, *not* a mode because of the altered tone.  *However*, if you decided in a hypothetical sense to make Ionian b2 your parent mode, then all of the other modes would need to share the exact same notes with no alterations because *they are relative to the parent scale*. The only difference between modes is where you focus the tonal center.
Answer: So if we take the Major scale and write down the modes for that:
Ionian -
Dorian -
Phrygian -
Lydian -
Mixolydian -
Aeolian -
Locrian
That is a set of modes for both the Major and Natural Minor scales. The Minor scale simply starting in a different place. Realistically you can start pulling out all sorts of scales and form modes from these. The modes for the Melodic Minor are (and I had to look these up):
Melodic Minor -
Dorian b2 -
Lydian Augmented -
Lydian Dominant -
Mixolydian b6 -
Locrian Natural -
Altered Dominant -
There would be other modes for the Harmonic Minor scale, Double Harmonic Scale, or other scales which do not have the same intervals as the Major scale. Some scales will simplify to a smaller number of modes, such as the Diminished Scale, which only has two distinct modes. One can argue the Chromatic Scale can have modes, but it only has one as they would all be identical. So to conclude your first question - why does the Minor Scale have modes - all scales will have modes of some description and it may be helpful to draw a distinction between the Melodic/Harmonic Minors as new scales compared to the Natural Minor, which is in itself a mode of the Major scale.
For your second question - whether the major modes have their own modes within themselves - well they have the rest of the major modes. If you take the Dorian mode and play a scale starting on the second note you would expect to play a Phrygian scale. As I said earlier it helps to draw a distinction between the Natural Minor (Aeolian mode) and the other two minors you highlight, which have their own set of modes for their subtle differences.
Answer: The natural minor to any major scale is the sixth degree of any given major scale. A parallel minor scale shares the same starting tone but follows its own natural minor scale and would have a different natural relative major.
In doing the major scale itself, there are then the modes...
So yes, a mode is simply playing from one note to that same exact note in the order that it falls within that key. D to a D in the key of C is your Dorian minor mode. G to to a G in the key of C is your mixolydian mode, or the mode that will fit perfectly over a Dominant chord(a dominant chord unaltered).
Answer: A mode is basically using scale notes, and starting the sequence on a different note from that sequence. As in D Dorian uses the same notes as found in C major. But you know that. By using a different set of notes, such as those found in the harmonic minor scale, a slightly different set of modes appear. As already answered, using, say, the chromatic scale, there could be, it may be argued, that there are 12 different modes that come from it. Debatable. So, yes, using harmonic or melodic minor scales will produce more modes. Obviously, referencing from the natural minor will only take you back through the original modes from the original 'mother' key. Modes made from modes can't exist.
Comment: Yes, *I* would debate it. Using 12 pitches chromatically saturates a scale and removes a tonal center - the thing by which modes are differentiated. That said, the closest you could approximate what you propose would be permutations of tone rows, which of course wouldn't be identified aurally.
Answer: It has modes for the same reason that Major scale has modes. Nothing special about it. Harmonic and melodic minor scales are different scales not modes of natural minor. Here is a nice diagram of all three side by side made using guitar Chords and Scales software:
Answer: We use 'Mode' in a narrow sense to describe the 7 scales obtained by starting a major scale on the 'wrong' note.   We also sometimes describe several scales that categorise as minor (not necessarily JUST natural, melodic and harmonic)  as 'different modes of the minor scale.  And, even more widely, we might call ANY scale a 'mode' -  'Ukranian Dorian', 'Hungarian minor'  etc. etc.
Don't worry if you come across a usage of the term 'mode' that doesn't correspond with one of the OTHER usages!  And don't bother to condemn the looser definitions as 'wrong'.  Just be sure to clarify that you're talking about e.g. the 'church modes' if that's what you ARE talking about.

Why does the minor scale have modes?