Drupal 7 and Views 3: Page Display and Random Appended Arguments in URL

Question: This is going to seem like an odd question. I am not sure if this is the way Views is meant to work but I want to see if I can turn it off.
Say I have a View with a Page Display with a defined URL like so: /testimonials
The Display takes not arguments what so ever. Here is the problem: I can now access this view using URLs like this:

/testimonials/5898
/testimonials/hello/what
/testimonials/stupid/appended/data

I can't for the life of me figure out how to turn this off in Views. Any ideas?
Comment: Naturally, I would like it to throw a 404 error since a page at that path, in theory, does not exist. I don't mind writing code to do it but I would prefer if there is a way Views supports it. I also updated my question to give a better idea why this is a problem for me.
Comment: What would you like to happen when you access /testimonials/5898?
Comment: This answer may help you too:

http://drupal.stackexchange.com/questions/48093/how-do-i-set-my-views-to-return-a-404-using-global-null-under-contextual-filter
Answer: 5898 is just an extra URL argument in View's point of view. Views doesn't have the ability to throw 404 pages because there are "extra" arguments in the URL. Views does throw 404s when there is no argument in the URL (if configured that way). In any case, you can implement something like hook_views_pre_view() and redirect the user to a separate 404 page if you see that extra arguments are found in the URL. This should take like 15 minutes for a Drupal developer to do.
Comment: I was afraid of that. I would think that Views would support this if the display is not defined to accept arguments and there are arguments in in the URL. In any case, back to my IDE I go. Thanks for your help.


Can this inequality proof be demystified?

Question: At http://www.artofproblemsolving.com/Forum/download/file.php?id=44351 , one finds a short proof by Vasile Cirtoaje of the inequality
$$
\sqrt{8(a^2+bc)+9}+\sqrt{8(b^2+ac)+9}+\sqrt{8(c^2+ab)+9} \geq 15 \ (\text{when} \ a,b,c\gt 0, \ a+b+c=3)
$$
Unfortunately, this proof has several surprising, seemingly un-motivated steps, giving
the impression that only a pure genius could have found them.
So, can anyone "demistify" this proof, possibly transforming some parts into longer but
conceptually more natural ones ?
Related : Prove $\sqrt{x^2+yz+2}+\sqrt{y^2+zx+2}+\sqrt{z^2+xy+2}\ge 6$, given $x+y+z=3$ and $x,y,z\ge0$
Comment: @Sanchez Unnatural step 1 : why replace $\Sigma{\sqrt{A}}$ with $\Sigma{\sqrt{A}-(3a+b+c)}$ ? (of course, it all works out in the end, but that's not a satisfying explanation in my view). It is natural
to replace $\Sigma{\sqrt{A}}$ with $\Sigma{\sqrt{A}-(\alpha a+\beta b+\gamma c)}$, but why
choose $(\alpha,\beta,\gamma)=(3,1,1)$ ? By the way, $3a+b+c$ is not the same thing as the
$3a-b-c$ appearing in $\sqrt{(3a-b-c)^2+q}$, it is a sort of "conjugate". It would seem more
natural to consider $\sqrt{(3a-b-c)^2+q}-(3a-b-c)$ instead of $\sqrt{(3a-b-c)^2+q}-(3a+b+c)$.
Comment: Which steps are unnatural to you?
Comment: @Sanchez Unnatural step 2: why replace $\sqrt{A}-(3a+b+c)$ with $\frac{A-(3a+b+c)^2}{\sqrt{A}+(3a+b+c)}$ ? Of course, it all works out in the end, but that's not a satisfying explanation in my view).
Answer: I'd rather leave this as a comment, but it's probably too long so I'll leave it here.

A basic strategy in tackling inequalities of few variables is to write things into sum of squares, in brute force way. In the case of three variables we would want to write an inequality as

$$C(a-b)^2 + B(a-c)^2 + A(b-c)^2 \ge 0$$
where $A,B,C$ are polynomials in $a,b,c$. If $A,B,C \ge 0$ all the time then we are of course done, but even in other situations we can usually say something. For example if the inequality is symmetric, one can suppose that $a \ge b \ge c$, then if $A \ge 0$ and $B+C \ge 0$, then
$$C(a-b)^2 + B(a-c)^2 + A(b-c)^2 \ge (B+C)(a-b)^2 + A(b-c)^2 \ge 0$$
There are many variants along this theme. One noteworthy variant is via the Vornicu-Schur lemma, which seeks to write an inequality of the form
$$A(a-b)(a-c) + B(b-c)(b-a) + C(c-a)(c-b) \ge 0$$
and proceed in a similar fashion.

The natural question then is, how to write something into sum of squares? A natural approach is then to pick out $a-b$, $b-c$, $c-a$ terms as much as possible. For example, if there is a $a^2+bc$ term, it is common to write it as $(a-b)(a-c) + a(b+c)$, for the sake of getting $(a-b)(a-c)$ which hopefully gives us a sum of square/Vornicu-Schur like expression.
For the question at hand, to tackle $\sqrt{8(a^2+bc) + 9}$, one can of course write it as $\sqrt{8(a-b)(a-c) + a(b+c) + 9}$, which does not look very helpful with the square root there. One common strategy to remove square root (and product $(a-b), (a-c)$ like term) is to rationalize the denominator. Solely for the purpose of getting sum of squares expression we would consider $\sqrt{A} - (xa + yb + zc)$ as you have mentioned.

How do we pick $x,y,z$? Unfortunately I don't have a good answer for this. We definitely want $x+y+z=5$ since we expect each $\sqrt{A} - (xa + yb + zc)$ vanish when $a=b=c$. One explanation for the choice $(x,y,z) = (3,1,1)$, is that when we rationalize $\sqrt{A} - (xa + yb + zc)$, we get $A - (xa+yb+zc)^2$, and we want it to be as simple as possible for the sake of easier analysis. $(x,y,z) = (3,1,1)$ immediately kills off the square terms which is a good thing to have.
(Remark: personally, I would rather try $(x,y,z) = (11/5, 7/5, 7/5)$ - one obtains this if one set
$$8(a^2+bc)+9 - (xa+yb+zc)^2 = (9-x^2)(a-b)(a-c) + (1-y^2)(b-a)(b-c) + (1-z^2)(c-a)(c-b)$$
I didn't check if this would work though.)


an error in R code written for finding clusters

Question: I am relatively new to R. I just try to find out optimum number of clusters for iris data using the following methods:
library(datasets)
head(iris)

# method1:
wss <- (nrow(iris)-1)*sum(apply(iris,2,var))
  for (i in 2:3) wss[i] <- sum(kmeans(iris,                           centers=i)$withinss)
plot(1:3, wss, type="b", xlab="Number of Clusters",ylab="Within groups sum of squares")

# method2:
library(fpc)
pamk.best <- pamk(iris)
cat("number of clusters estimated by optimum average silhouette width:", pamk.best$nc, "\n")
plot(pam(iris, pamk.best$nc))

Both methods throw up error. So please do someone shed light on it. Many Thanks in advance.
Comment: When getting error message you should include the exact error message in your question. Did you look at the result of `apply(iris,2,var)`? That might give you a clue as to what's going on. You can't use kmeans on categorical (factor) data directly.
Comment: Has nothing to do with the programming: I think your criterion for the optimum number of clusters for kmeans shouldn't be the the minimum of the withinss, because that will reduce every time you add a cluster, until every observation is one cluster.
Answer: apply(iris,2,var)

gives you an error because the 4th column is not numeric.
Try
apply(iris[,1:4],2,var)
The same goes for the second method.
Error in pam(sdata, k, diss = diss, ...) :
  x is not a numeric dataframe or matrix.


Looking for an app that can record piano and visually represent what was played

Question: My son is learning piano, he is good at playing the correct note but struggles with the timing. We have an iPad and I sometimes record him and look at the waveform to try and show when his timing is incorrect but it is not easy to deduce this from the waveform.
Is there a program that could record the piano playing then visually give a representation of what is played as sheet music, in fact all I really need is something that indicates the length of the notes played, does such a thing exist.
Comment: You could also use a metronome to help with the timing.
Comment: I think this might be off topic here, but on topic on Software Recommendations. Not sure though. I'm not voting to close. An app like this seems interesting
Comment: He is already practicing with a metronome, is he not? This is the assumption that I made when I wrote my answer below. Using a metronome is a low-tech solution that all beginning musical instrument students should always use.
Comment: I would suggest to use the correctly played music as a reference, comparing to the student music.
Answer: Yes, indeed. Computer programs for doing this have been around for more than 30 years.
But to help your son with his timing, you don't want to record and display audio waveforms, and you don't want to have a computer program transcribe his recorded playing into standard music notation (there are certainly programs that can do this, but this will be of little use to him at this stage, as I will explain below). What you need instead is to record and display his playing on a MIDI piano-roll editor.
The kind of computer program that can do this (among many other functions) is called a Digital Audio Workstation, or DAW. There are myriad programs available for Mac and PC. They are all designed for musicians to record and edit music. They are not specifically designed to help a student analyze whether they are playing in time or not. But they can be used for that purpose.
In this usage scenario you cannot use a real acoustic piano. Rather, you need a digital piano or keyboard which is connected to the computer and the DAW application using the MIDI protocol, with MIDI cables or MIDI-over-USB.
[You need to understand what MIDI data is; in this usage scenario, you are not recording the audio from your son's piano playing. Rather, you are recording the MIDI data generated by your son's fingers depressing and lifting each individual key on the keyboard as he plays. This gives the great advantage of being able to display and analyze each individual note, to a greater degree of accuracy and resolution than is possible by recording audio and looking at the waveforms.]
As a basic assumption, your son needs to be accustomed to practicing with a metronome.
The DAW program running on the PC or Mac records what your son plays on the keyboard (while he listens to and plays according to its metronome click) and then displays each note on a scrolling graph, showing its exact start and stop position against a grid display. The graph and grid is referred to as a piano-roll MIDI editor.
The DAW program can usually display the MIDI data either on the piano-roll grid or as standard music notation (with some limitations). For someone who has bad timing, however, switching to standard music notation created by the program from MIDI data is not going to be helpful, as the music notation faithfully transcribed from the errant performance is going to look like a lot of garbled nonsense.

Piano-roll MIDI editor view of a piano part recorded in Apple GarageBand. The green bars display the exact starting position and ending position of each individual note, against a grid that shows the measures of music and subdivisions of the beats in each measure, according to the metronome.

The same piano notes recorded in GarageBand displayed in standard notation. The only reason the notation looks good in this example is that the notes were played extremely accurately in the first place.
Examples of suitable entry-level Digital Audio Workstation (DAW) programs are:

Apple GarageBand, which comes free with every Mac
Presonus Studio One for Mac and PC
Steinberg Cubase (owned by Yamaha) for Mac and PC
Cakewalk for PC

Most of these programs exist in several different versions: a free version for beginners, an inexpensive version for intermediate users, and an expensive version for professional studio recording. For your purposes, you can get the least expensive version of any of these programs.
Learning to set up and use any of these programs is not intuitive. It requires reading the owners manual that comes with the program, and working through the tutorial examples, or possibly watching a professional tutorial video series or reading a third-party how-to book. When you launch one of these programs for the first time, you will have absolutely no idea how the program works or how to get it to do what you want. So you will have to do some reading and studying.
Answer: I don't think so for two reasons:

Converting even perfectly timed MIDI backwards to a score is in
several respects unsatisfying, as can be found in many other answers
on this forum.
The errors a beginner will typically make (holding this eighth a bit
too long, that quarter too short, emphasis on wrong notes,
inconsistent tempo) are very difficult to encode in standard
notation. The piano roll representation offered by most software is -
on the other hand - so different from score notation, that mismatches
will not be easily recognized. (This is quite similar to your waveform experience).

Summarized: I don't expect a short-term substitute for a metronome (depending on the instrument type: a tuning device) and an instrumental teacher (even if the first two may be realized by software).
Comment: This is why, in my answer, I introduced the questioner to the concept of MIDI piano-roll display, which works much better than standard notation for helping correct the problem he describes.
Answer: Smart Music does something like this.  It has exercises and songs to play through the program that shows a note green if you played the correct note and at the correct time, and red if you played the wrong note in the wrong place, the right note at the wrong time, etc.  It also has a huge repertoire of music.
It works for many instruments, too.
http://www.smartmusic.com/
Comment: I used to use hyperscribe in Finale (same company), but it was super picky and not very helpful unless you could play rock solid with a metronome. I'm glad smartmusic is better than that.
Answer: Aurialia has good training exercises that would display the exactly wanted content (notation sheet with labels where the hits were expected, and red labels showing actual hit timing as done by student), and would achieve the assumed goal (rhythm training with computer tools).
However Auralia cannot analyze arbitrary piano music; you need to use the built-in training exercises and can only enter rhythm beats with arbitrary key on MIDI or simply computer keyboard (while Auralia plays the rest of the melody).


How do I move a node's tags to be near its author information in my Bartik subtheme

Question: I want to style a node's author data and tags slightly differently to the Bartik theme in Drupal 9.3. That is, rather than:
Submitted by user1 on Mon, 1/1/70
Tags
  foo
  bar

I'd like to have:
Submitted by user1 at Mon, 1/1/70 on foo | bar

So far, I have created a subtheme tweak with the following definition in tweak.info.yml:
name: Tweak
type: theme
description: This is a sub-theme of Bartik
core_version_requirement: ^8 || ^9
base theme: bartik
version: '9.3.0'

regions:
  header: Header
  primary_menu: 'Primary menu'
  ...

I have copied the following templates into my subtheme and modified them:
templates/node.html.twig
templates/field--taxonomy-vocabulary-1.html.twig

I have enabled my subtheme and I can confirm that the overriding templates are being executed. That is, I get the following:
Submitted by user1 at Mon, 1/1/70
on foo | bar

Unfortunately, there is a lot of HTML in between the two lines, ie.

  Submitted by

user1

at
Mon, 1/1/70 - 16:29

 on
  foo
 | bar

What I'd like to have is the output from field--taxonomy-vocabulary-1.html.twig within the same
 as the Submitted by ... content. However, I cannot see how to do that. Can anyone give me some pointers?
Answer: @khummari's answer didn't work for me. However, I was able to adapt it.
I continued to use field--taxonomy-vocabulary-1.html.twig to theme the tags as I desired.
I then modified node.html.twig as follows. I used
{{ content.taxonomy_vocabulary_1 }}

to render the tags in my desired location. To prevent them rendering in their default location, I rendered the node's content as follows:
{{ content|without('taxonomy_vocabulary_1') }}

This feels like a bit of a hack though. Does anyone have a better suggestion?
Answer: In node--article.html.twig override in your theme's template directory as follow

Then override the tags field twig template as follow

following should be the result
Comment: Please don't use screenshots for showing code. They are a hell to read on mobile and impossible to copy/paste. Please paste the code and use code-highlighting instead.
Comment: @khurrami thanks for the help. I've tried your suggestion and unfortunately `{{ content.field_tags }}` is rendering as empty in my case. Was there something else you changes that's not included in your answer?
Comment: Interestingly `{{content.taxonomy_vocabulary_1 }}` does render what I need. However, this is rendering in two places. I'm not sure how to turn the second (original) case off.


Why is the probability of drawing a certain element from a population of size $N$ be $1/N$ even though the sampling is done without replacement?

Question: Related:
Trying to understand the derivation of expectation of sample mean $E(\bar x)= \mu$ where $\mu$ is the mean of the population

I've been trying to understand $\mathrm E(x_i)= \mu$ where $x_i$ is the element at the $i^{\textrm {th}}$ draw from a population of size $N$ for making a sample of size $n$ by SRSWOR.
I read between the lines of my book again; here is the excerpt:

Let $x_1,x_2,\ldots,x_n$ represent a simple random sample from the population $X_1,X_2,\ldots,X_n$. In SRSWR, the probability of selection of any particular member of the population at any drawing remains a constant $1/N$; because before any drawing the population contains all the $N$ members. It may be shown that this result is also true in SRSWOR, although the population size varies at each stage of the selection. Thus, the probability of obtaining the population member $X_k$(suppose) at the $i$-th drawing is a constant $1/N$ both in SRSWR and SRSWOR; i.e., $$\mathrm P(x_i= X_k)= \frac{1}{N}$$

While I'm sure of this for SRSWR, I'm not getting this for SRSWOR.
How can the probability of drawing a certain element from the population at a certain draw be $1/N$ for even the author says 'the population size varies at each stage of the selection'?
If after each turn, the population size is not the same, hoe can still the probability of drawing certain element be $1/N$ when the sampling is done without replacement?
Can anyone please explain me the case for SRSWOR?
Comment: It is illustrative to note that $P(X_2 = x) = \sum_{y=1}^n p(X_2 = x | X_1 = y) p(X_1 = y)$ by the law of total probability.
Comment: Yes it is true that $P(x_i = X_k) = 1/N$, mathematically you would use induction to prove the general case. However, the intuition is that, "It's equally likely that all the other previous draws could be anything else."
Comment: @AdamO: Suppose, you pick up $X_k$ at the first turn; now wouldn't it be wrong to say $\mathrm P(x_2= X_k)= 1/N\;?$ For you've not replaced the element before the second turn, isn't it?
Comment: Yes but if the previous draws do *not* select that element on the $i$-th turn, you are *more* likely to draw that element on the $i$-th turn than with SRSWR. Think about the $N$-th draw, the $N-1$ possible cumulative permutations of previous draws which do draw the $k$th element have probability $(N-1)/N$, but the 1 possible draw that does include the $k$-th element has 100% probability of doing so, leading to probability $1/N$ for a successful draw.
Comment: @AdamO: Is the book saying right?
Comment: How could the answer be anything *other* than $1/N$?  If it were, then it would be some definite function of the $N$ objects whose different values would distinguish among those objects--but under the assumptions of randomness, all objects play equivalent roles in the sampling model.
Answer: By way of induction and the total law of probability it holds that:
$$P(X_2 = k) = \sum_{i=1}^n P(X_2 = k | X_1 = i) P(X_1 = i)$$
and supposing it holds for any $j$ that $P(X_j = k) = 1/N$ then
$$P(X_{j+1} = k) = \sum_{i=1} ^ N P(X_{j+1} = k | X_j = i) P(X_j = i)$$.
I think the comments I've contributed on the post contribute more of the intuition behind this finding.
Comment: I don't think this is correct, because the poster asked about "How can the probability of drawing a certain element from the population at *a certain draw* be 1/N" in SRSWOR. This is not the same thing as the overall  probability of selecting an element, which is the probability of selection at at *some* draw, which is indeed 1/N.
Answer: Let $A_l^{\textrm {j}}$ denotes an event that a particular unit $X_j$ is not selected at the $l^{\textrm {th}}$ draw. The probability of selecting, say, $k^{\textrm {th}}$ unit at $i^{\textrm {th}}$ draw is: (taking $A_i^{\textrm {k}}$= $A_i$)
\begin{align}
P (x_i = X_k) &= P(A_1 \cap A_2 \cap A_3 \cap A_4 .... A_{i-1} \cap \overline{A_i})\\
              &= P(A_1)P(A_2|A_1)P(A_3|A_1A_2).....P(\overline{A_i}|A_1A_2...A_{i-1}) \\
              &= (1-\frac{1}{N})(1-\frac{1}{N-1})...(1-\frac{1}{N-i+2})\frac{1}{N-i+1}\\
              &= (\frac{N-1}{N})(\frac{N-2}{N-1})...(\frac{N-i+1}{N-i+2})\frac{1}{N-i+1}\\
              &= \frac{1}{N}
\end{align}


Determining what the decision boundary will look like in various scenarios

Question:
I'm currently trying to work through this question, but not quite sure where to start. The cases I need to consider are (in turn):
(a): $lamda_0$ = 0, $lamda_1$ = 0, $lamda_2$ = $\infty$
(b): $lamda_0$ = $\infty$, $lamda_1$ = 0, $lamda_2$ = 0
Thanks!
Answer: For (a), $\theta_2$ will be chosen as $0$ since $\lambda_2=\infty$, and there is no other way to minimize the loss. Similarly, for (b), $\theta_0=0$.
(a) If we have $\theta_2=0$, the decision boundary will look like $\theta_1x_1+\theta_0=0$, i.e. the vertical line.
(b) If we have $\theta_0=0$, the decision boundary is $\theta_1x_1+\theta_2x_2=0$, a line passing from the origin.
For having a horizontal line as boundary, you need $\theta_2x_2+\theta_0=0$, where $\theta_1$ is forced to be $0$ due to $\lambda_1=\infty$.
Normally, you'd have a threshold in logistic regression, but here it is chosen as $\tau=0.5$ as I follow.


Problemas com modelagem de dados com Persistence.xml

Question: Criei uma aplicação da faculdade para criar tabelas automáticas pelo Hibernate com JPA
porém deu erro em algumas tabelas, que foram essas;
CatalogDAO
OrderDAO
ProductDAO
porém esta gerando o seguinte erro,
quando eu clico em  CatalogDAO gera esse erro;
        catalog0_.CATALOG_ID=?
20:07:25.347 [main] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtaining JDBC connection
20:07:25.347 [main] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtained JDBC connection
20:07:25.359 [main] DEBUG o.h.l.e.p.AbstractLoadPlanBasedEntityLoader - Done entity load : com.accenture.extremeex.domain.Catalog#1
Exception in thread "main" javax.persistence.EntityNotFoundException: Unable to find com.accenture.extremeex.domain.Catalog with id 1
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:181)
    at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:262)
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:176)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at com.accenture.extremeex.domain.Catalog_$$_jvst9c4_9.getCatalogName(Catalog_$$_jvst9c4_9.java)
    at com.accenture.extremeex.dao.CatalogDAO.main(CatalogDAO.java:16)

quando tento executar essa classe OrderDAO gerra esse outro erro;
   (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
20:09:08.829 [main] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper - could not execute statement [n/a]
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order (BILLED_AMOUNT, BILLING_INFO_ADDR_LINE_1, BILLING_INFO_ADDR_LINE_2, BILLIN' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.7.0_67]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) ~[na:1.7.0_67]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.7.0_67]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526) ~[na:1.7.0_67]
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:407) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.Util.getInstance(Util.java:382) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2333) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2318) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84) [hibernate-entitymanager-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181) [hibernate-entitymanager-4.3.6.Final.jar:4.3.6.Final]
    at com.accenture.extremeex.dao.OrderDAO.salvar(OrderDAO.java:97) [classes/:na]
    at com.accenture.extremeex.dao.OrderDAO.main(OrderDAO.java:34) [classes/:na]
20:09:08.830 [main] WARN  o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 1064, SQLState: 42000
20:09:08.830 [main] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order (BILLED_AMOUNT, BILLING_INFO_ADDR_LINE_1, BILLING_INFO_ADDR_LINE_2, BILLIN' at line 1
20:09:08.831 [main] DEBUG o.h.j.spi.AbstractEntityManagerImpl - Mark transaction for rollback
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1187)
    at com.accenture.extremeex.dao.OrderDAO.salvar(OrderDAO.java:97)
    at com.accenture.extremeex.dao.OrderDAO.main(OrderDAO.java:34)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
    ... 2 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order (BILLED_AMOUNT, BILLING_INFO_ADDR_LINE_1, BILLING_INFO_ADDR_LINE_2, BILLIN' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
    at com.mysql.jdbc.Util.getInstance(Util.java:382)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2333)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2318)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    ... 23 more

e na classe ProductDAO gera esse erro;
20:10:32.217 [main] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtaining JDBC connection
20:10:32.217 [main] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtained JDBC connection
20:10:32.236 [main] DEBUG o.h.l.e.p.AbstractLoadPlanBasedEntityLoader - Done entity load : com.accenture.extremeex.domain.Catalog#1
Exception in thread "main" javax.persistence.EntityNotFoundException: Unable to find com.accenture.extremeex.domain.Catalog with id 1
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:181)
    at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:262)
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:176)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at com.accenture.extremeex.domain.Catalog_$$_jvstb59_9.getCatalogID(Catalog_$$_jvstb59_9.java)
    at com.accenture.extremeex.dao.ProductDAO.salvar(ProductDAO.java:44)
    at com.accenture.extremeex.dao.ProductDAO.main(ProductDAO.java:25)

alguem pode me ajudas? as outras tabelas foram criadas menos essas classe
o código está aqui.
https://github.com/wladyband/extreme/tree/master/ExtremeEX
Answer: A causa do erro nas classes "CatalogDAO" e "ProductDAO" é a mesma: Unable to find com.accenture.extremeex.domain.Catalog with id 1. Na tabela "catalog" não existe nenhum registro com CATALOG_ID igual à 1.
A causa do erro na classe "OrderDAO" é o nome da tabela "order", pois "order" é uma palavra reservada do SQL. Você pode renomear a tabela ou usar "order" entre aspas duplas. Neste segundo caso altere a anotação na classe "Order" para:
@Entity(name="\"order\"")


Probability of getting a rational number for continuum trials

Question: As far as I know, the probability of getting a rational number from the interval $(0, 1)$ is zero if we follow the Lebesgue measure. Still, it doesn't mean it's impossible.
Now, suppose we have a continuum number of independent random variables $X_{\alpha}$, where $\alpha \in \mathbb{R}$. Each of them is a sample from the interval $(0, 1)$. Would then the probability of getting at least one rational be positive?
Comment: @mlofton Your initial statement is incorrect. Let $U$ have a Uniform$(0,1)$ distribution and for each $x\in(0,1)$ let $E_x=\{x\}.$ These events all have probability zero, yet their union is $\bigcup_{x\in(0,1)} E_x = (0,1),$ which has probability $1.$
Comment: @mlofton: *countable* unions of zero sets have zero measure. The interesting aspect here is that we haven an *uncountable* union.
Comment: @StephanKolassa I found this: https://en.wikipedia.org/wiki/Infinite-dimensional_Lebesgue_measure. Does this mean that sequence $X_{\alpha}$ with assumptions stated as in my question doesn't exist?
Comment: Hi: No. the union of events, each of which has lebesgue measure zero,  is still zero.  ir's analogous to the uniform distribution. Suppose a variable X has a uniform distribution over (0,1). The probability that X = x is zero. But if you generate a uniform random variable, x's are created. Think of the probability being so small that it's zero mathematically. But if you start adding them up, the zero-ness goes away.
Comment: whuber: thanks for heads up. I was el wrongo. Stephan: Thanks for pointing out where I erred. I like to say that I intended to say countable but I didn't :).
Answer: This set of random variables can be considered as a function $f:\alpha \to X_\alpha$. So the question is what is $P(\exists \alpha | f(\alpha) is rational)$.
When the question is put this way, you can see that it relies on having a probability measure on the space of possible functions. The question, if asked for any "continuum number of random variables", is unanswerable.
If the set of possible functions is the constant functions (with the natural measure), then the answer is zero. But with many natural sets of functions the answer is one, since any nonconstant continuous function has some rationals in its image.
Comment: Is there any canonical way of defining a measure on such functions? I mean, something like product measure on $\Omega = (0, 1)^n$, which is $\mu(A_1 \times A_2 \times \cdots \times A_n) = \prod_{i=1}^{n}\mu(A_i)$, but for $\Omega = (0, 1)^{\mathbb{R}}$?
Comment: Not really. L2 is a popular measure space over functions, but there are others. Which you use depends on context.


How many solution are possible for $x,y,z \in \{0,1,2,3,4,...\} , 50x+25y+10z=2000$?

Question: $$x,y,z \in \{0,1,2,3,4,\ldots\}, 50x+25y+10z=2000$$ I have no clue to this form of equation . But I can solve by two variable .
  This is multiple choice question $$703\\716\\820\\861$$ Can anyone help me?
Comment: first divide by $5$ , then use G.C.D.
Comment: How can i use g.c.d ?
Answer: $$\quad{50x+25y+10z=2000\div5\\10x+5y+2z=400\\\implies y=2y'\\z=5z' }$$now $$\quad{x,y',z' \in \{0,1,2,3,4,5...\}\\10x+5(2y')+2(5z')=400\\x+y'+z'=40\\\begin{pmatrix}
 40+3-1 \\
 3-1
 \end{pmatrix} =\frac{42\times 41}{2}=861}$$


Simple way to add sudo to docker image

Question: I'm trying to create a way to easily test my installation scripts for Ubuntu. What I'm doing now is that I create a temporary docker container like this.
docker run --rm -it ubuntu bash and then copy in my script. This gives me a fresh ubuntu install, which instantly gets created and then removed on exit.
The problem is that i can't include the word sudo in my installation script without the script throwing errors. I need to use sudo in real world applications, so I can't remove it.
Is there some simple way to add sudo functionality, or "Ubuntu-like-images" which has this?
Comment: You don't need `sudo` in Docker at all.  `docker run -u root your-image` and you're root.  In most images the default user is root as well.  (You also wouldn't typically use the unmodified `ubuntu` image; instead, write a Dockerfile that `COPY`s your script in, and you won't have to keep repeating the copy step every time you launch the container.)
Comment: Are you trying to execute docker commands without sudo?
Comment: The commands are all inside my shell scripts, and they are not docker commands.
Comment: `apt-get install -y sudo`? `docker run --rm -it ubuntu bash -c 'apt-get install -y sudo && bash'`?
Answer: @KamilCuk provided the solution, where all i needed was just to install sudo.
apt update && apt-get install -y sudo

Simple way to add sudo to docker image


What is the probability of exactly two out of n persons sharing a birthday?

Question: The classical Birthday problem asks for the probability of at least two out of $n$ people sharing the same birthday or sometimes for the least amount $n$ of people required such that with a probability of 50% at least two of them share their birthday. But what about the question how probable it is that also no more than two people share their birthday?
Comment: @AndréNicolas : I think you missed a factor : P("n-1 don't share a birthday") = Nb of cases where n-1 don't share a birthday / $365^{(n-1)}$.
P = Nb of cases where n-1 don't share a birthday * ${n \choose 2} / 365^{n}$ = P("n-1 don't share a birthday") * ${n \choose 2}$ / 365
Am I right?
Comment: Got something from an answer below?
Comment: @Did I somehow missed the answer notifications, thanks for the ping - I'll try and vote/accept them by tomorrow
Answer: We interpret the question as asking for the probability that precisely two people share a birthday.
Imagine lining up our $n\ge 3$ people, and writing down their birthdays. Under the usual not quite accurate assumptions, there are $365^n$ equally likely strings.
We now count the number of "favourables."
The two people who share a birthday can be chosen in $\binom{n}{2}$ ways. For each such choice, the common birthday can be chosen in $365$ ways.
For each such choice, the remaining $n-2$ slots can be filled in $(364)(363)\cdots (364-(n-3))$ ways, for a total of $\binom{n}{2}(365)(364)(363)\cdots(364-(n-3))$.
Answer: $\mathbb{P}$(no more than two people share their birthday) = $\mathbb{P}$(noone shares their birthday with anyone else) + $\mathbb{P}$(noone shares their birthday with anyone else except one pair)
Now,

$\mathbb{P}$(noone shares their birthday with anyone else) = $\frac{365!}{(365 -n)!}*\frac{1}{365^n}$
$\mathbb{P}$(noone shares their birthday with anyone else except one pair) = $\frac{364!}{(364 - \overline{n-2})!}*\left({n \choose 2} 365\right)*\frac{1}{365^n}$.
Answer: I think the answer of André Nicolas given in the comment is better, however, here is what I did :
Let's denote $Q(n)$ the probability that n people don't share a common birthday, and $P(n)$ that exactly two people share a common birthday.
$Q(n)$ is known for every $n$, cf. the Wikipedia link you gave. $P(1)$ also known.
We have the following relationship :
$P(n+1) = P(n)*\frac{n}{365} + Q(n)*\frac{365-(n-1)}{365}$
$P(n+1) = P(n)*\frac{n}{365} + Q(n)*\frac{366-n}{365}$
You can then compute all the probability up to 366, after, $P(n) = 0$
Answer: You need ${{n}\choose{2}}$ ways of choosing 2 people times probability the number of ways only those two share birthday [$365!/(366-n)!$ if $n\le366$ and $0$ otherwise] divided by the total possible ways $365^n$. Sorry, I am ignoring February 29 to keep things simple.
Answer: Draw at random $n$ birth dates from a set of $N=365$ different dates, independently and uniformly. The event that exactly $2$ birth dates coincide happens when, for some $1\leqslant k\leqslant n-1$, $k$ different dates are chosen, then a date already drawn is drawn again, then $n-k-1$ new different dates are drawn. For each such $k$, the probability that this happpens is
$$
p_k=\frac{N-1}N\cdot\frac{N-2}N\cdot\cdots\frac{N-k+1}N\cdot\frac{k}N\cdot\frac{N-k}N\cdot\frac{N-k-1}N\cdots\frac{N-n+2}N.
$$
The probability of the event that exactly $2$ birth dates coincide is
$$
\sum_{k=1}^{n-1}p_k=\frac{(N-1)!}{(N-n+1)!N^{n-1}}\cdot\sum_{k=1}^{n-1}k=\frac{n(n-1)}2\cdot\frac1{N^n}\cdot\frac{N!}{(N-n+1)!}
$$
Answer: n people and only two share a birthday.
Approach: Consider that $n-1$ don't share birthday with anyone. (everyone knows this) $(1)$
The last person will have to share birthday with anyone of the $n-1$ people.
The same has to be done for the initial $n-1$ people who didn't share birthdays.
This will give a sum of $ (n-1) + (n-2) + (n-3) + \dots + \big(n-(n-1)\big) = \frac { n (n-1) } 2 $ $(2)$.
Answer $ = (1) * (2) $
Comment: (1) * (2)/365...apologies for missing out 1/365
Comment: You can edit your answer if necessary
Comment: Thanks for the edit. How to carry out Edit?
Comment: Push the edit button back to your post
Comment: click on  the edit where you have this : share cite edit follow delete flag


using poly( function within training model in caret package resulting in dataframe error

Question: Here's the code that I am running:
library(caret)
library(ISLR)
data('Auto')
cverror <- c()
for(i in 1:5){
  train_control <- trainControl(method='LOOCV')
  models <- train(mpg~poly(horsepower,i), data = Auto, trControl=train_control, method='glm')
  cverror[i] <- (models$results$RMSE)^2
}

cverror

What I'm trying to accomplish is to calculate the MSE (mean square error) for different polynomial levels using a loop so I don't have to code line by line. The error message I receive is:
 Error in `[.data.frame`(data, , all.vars(Terms), drop = FALSE) :
  undefined columns selected

Why am I receiving this error? My study mates said that this code runs fine on their machine, but it doesn't work on my personal or work computers. I have the latest RStudio and R versions installed with all packages up to date.
The following line of code works just fine:
train(mpg~poly(horsepower,2), data = Auto, trControl=train_control, method='glm')

This is in relation to the tutorial found on page 192/193 of the ISLR text (which I'm expanding upon).
Answer: If i <- 2 its value is not substituted into the formula. The formula is literally mpg ~ poly(horsepower, i).
Try this:
library(caret)
library(ISLR)
data('Auto')
cverror <- numeric(5)
for(i in 1:5){
  train_control <- trainControl(method='LOOCV')
  f <- bquote(mpg ~ poly(horsepower, .(i)))
  models <- train(as.formula(f), data = Auto, trControl=train_control, method='glm')
  cverror[i] <- (models$results$RMSE)^2
}

cverror
#[1] 24.23151 19.24821 19.33498 19.42443 19.03321

PS: Higher degree polynomials pretty much guarantee over-fitting. I'd not recommend a polynomial of a degree higher than 2, maybe 3. There are usually better models available in such a case. Higher degree polynomials are rare for "natural" processes.
Comment: Can you help me understand what the function, "bquote" does? I've never used (nor heard of) this function before. The help document (?bquote) was not very helpful.
Comment: It creates an expression, but takes the variable given in `.()` from the enclosing environment and substitutes its value into the expression.
Comment: If you prefer you could use `sprintf` or even `paste` instead.
Comment: Roland, what's very odd is that Nik's original code works perfectly on my machine, without having to use `bquote` or `as.formula`. I know we have different versions of R and RStudio; perhaps the function's behaviour changes over the version change?
Comment: @Rahul I'm not aware of changes in R that would impact this.
Comment: @NikhilAgarwal I tried your code on my windows machine at work, and get the exact error you are facing. R ver 3.3.1.
Answer: I had a similar issue. Have you tried using the following?
models <- train(x = poly(Auto$horsepower,i), y = Auto$mpg, data = Auto, trControl=train_control, method='glm')

(I have not tested this specific piece of code.)
Comment: The question already has an accepted answer, please avoid answering old questions if it dosent add anything new to the existing answers.


Calculate the maximum area (maximum value)

Question: TX farmer has 100 metres of fencing to use to make a rectangular enclosure for sheep as shown.
He will use existing walls for two sides of the enclosure and leave an opening of 2 metres for a gate.
a)  Show that the area of the enclosure is given by: $A = 102x – x^2.$
b)  Find the value of x that will give the maximum possible area.
c)  Calculate the maximum possible area.
How do I assign the two variables for area ? Can anyone assist me in solving this problem?
Answer: From your picture, one side of the rectangle is x.
Since you have 100 metres, this means the other side has length (100 - x) + 2 = 102 - x.
So, the Area A = $(102 - x) * x = 102x - x^2$
The maximum area occurs where $\frac{dA}{dx} = 102 - 2x = 0$
or where $x = 51$
So, the max area A = $102(51) - 51^2$
Comment: You're welcome.
Comment: thank you for your assistance and guiding me in the solution.
Area=length x width

Width = x
Length of the enclosure parallel to the wall = (100-x) +2
=102 - x
Area= x(102-x)
Area, A = 102x-x^2
dA/dx=102- 2x

At Stationary Point
dA/dx=0  ⇒ 102 – 2x = 0

2x=102
x=51

the maximum area occurs when x = 51
and
Area, A= (102x-x^2)
= 102x51 – (51)^2
= 2600


RIPE IPv4 Block with google cloud computing engine

Question: I was wondering if there is a way to use the RIPE IPv4 address block owned by us on google cloud? We want the main external IP from the cloud computing to be ours and not one given by Google.
Thanks for the answers in advance
Regards
D.
Comment: I've never heard of Google Cloud offering such a service. If you're a big enough customer, perhaps they can make some special arrangement. Contact Google enterprise support...
Comment: What are you trying to do with those IP addresses? Are you trying to use them instead of RFC 1918 addresses for internal IPs? Or are you trying to use them as external IP addresses?
Comment: If there isn't a way to configure that directly, you could also proxy requests through a machine that has the IP you want. Alternately, could you get away with pointing your domain at a different IP?
Comment: Thanks for your comments! I need them as external IP addresses. The internal ones from google cloud are okay, but I want to use my own IP's instead of the given external ones from google...
Comment: I am sharing this google help [centre article](https://cloud.google.com/solutions/custom-public-ip-addresses-on-compute-engine) which you might find helpful. This document shows how you bring your own external IP address to Google Cloud. This IP address has to be manually assigned to GCE VM and advertise back to the on-prem VPC from the Cloud Router with a Flexible Route Advertisement. It's worth mentioning that this address will not be advertised publicly from Google's edge network (AS 15169), but over the Cloud VPN connection.This would also apply over a Cloud Interconnect.
Answer: I can't comment whether it's possible on GCP but if you're open to other platforms AWS now supports exactly what you need since last week:
Bring Your Own IP for Amazon Virtual Private Cloud
Comment: The BYOIP is only supported in the US currently...
Comment: With AWS there is one huge issue, you can not assign IPs across regions. From their documentation: `You can bring each address range to one Region at a time.`.
Answer: Google Cloud announced this feature as an Alpha release in October 2019. There is a case study blog post and some tutorial in the solutions section that describes the implementation.
Also, note the important from the tutorial:

This tutorial assumes that you have a provider-independent IP space
  that you can advertise by using your own routing equipment.

If you value your time, I suggest wait, the implementation process looks unintuitive comparing to the competition and it will probably dramatically change in the future.


2-adic valuation of $5^{2^{k-2}}-1$

Question: I have the following exercice :

Consider that the 2-adic valuation of $x$ is $k \geq 2$. Prove that the 2-adic valuation of $(1+x)^2- 1$ is $k+1$.

Using the previous question, conclude that for $k\geq 2$, the 2-adic valuation of $5^{2^{k-2}}-1$ is $k$.

For the first l question, we know that $(1+x)^2 - 1= x(x+2) $. So, $$v_2((1+x)^2-1) = v_2(x)+\min(v_2(x),v_2(2))= k+1.$$
For the last question, I tried several methods but didn't work. Can someone give me a hint please?
Thanks!
Comment: In 1. you meant $k\ge 2$ as $v_2( (1-2)^2-1)=\infty$.
Comment: @reuns there was something wrong here when I edited the question. Look at it now
Comment: No try with $x=-2$ and $v_2((1+x)^2-1) = v_2(x)+v_2(x+2)$ was correct.
Comment: @reuns thanks! do I have to factor $5^{2^{k-2}} - 1$ if I want to solve the second question
Comment: No just apply 1.
Comment: @reuns ok, so $v_2(5^{2^{k-2}}-1)= v_2((1+x)^{2^{k-2}}-1)$ (here x = 4)  $\leq v_2((1+x)^{{2^{min(k-2)}}}-1) = v_2((1+x)-1) = v_2(x) = k $. Right?
Comment: Corrected question 1.  Should not affect question 2.
Answer:
If $v_2(x)=k\ge 2$ then $v_2(x+2)=1$ and $v_2( (1+x)^2-1)=v_2 (x(x+2)) =v_2 (x)+v_2(x+2) =k+1$.

Let $x_{k+2}=5^{2^k}-1=(1+x_{k+1})^2-1, v_2(x_2)=2$, by induction if $v_2(x_k)=k$ then $v_2(x_{k+1})=k+1$.

2-adic valuation of $5^{2^{k-2}}-1$


nginx 1.7.9: Reverse Proxy Web Sockets: hangs on service stop / service restart, never exits

Question: We use nginx for load balancing to a pair of websocket servers, and have hit an issue.
It will not gracefully exit or shut down once it has actually connected traffic to a web socket server. E.g. service nginx stop, or nginx -s quit or nginx -s reload causes one or more worker processes to report "worker process is shutting down" forever.
The flow is:

Start nginx with config below.
Pass traffic to the nginx endpoint
(even using web browser to hit the 443 port and get 404 error is
enough)
Use service control or send quit command
nginx is now hung.

We run nginx on centos v6
Details of our compile options and high level config:
    [root@nginx1 nginx]# nginx -V
    nginx version: nginx/1.7.9
    built by gcc 4.4.7 20120313 (Red Hat 4.4.7-11) (GCC)
    TLS SNI support enabled
    configure arguments: --user=nginx --group=nginx --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --with-http_gzip_static_module
--with-http_ssl_module --add-module=/opt/nginx_upstream_check_module-master/

Our config is below. How do we go about chasing this down? Right now we are forced to do hard kill/restart of nginx to update the config.
worker_processes  2;

error_log  logs/error.log;

events {
    worker_connections  20000;
}

worker_rlimit_nofile    40000;

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    upstream websocketserver {
        server 192.168.2.16:3842 max_fails=1 fail_timeout=60s;
        server 192.168.2.19:3842 max_fails=1 fail_timeout=60s;
    }

    server {
        listen 192.168.2.28:80;

    location / {

        proxy_pass http://websocketserver;

        proxy_next_upstream    error timeout invalid_header http_500;
        proxy_connect_timeout  2;
        proxy_read_timeout      86400;

        # WebSocket support (nginx 1.4)
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        }

        location / {
            deny all;
            return 404;
        }

    }
}

Comment: i added following headers in my nginx file, running with dphene service.

# WebSocket support (nginx 1.4)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

it solves my problem. Thanks
Answer: Possibly netstat and tcpdump are useful for debugging as well as lsof - is the worker process still connected and exchanging data?  I notice your proxy_read_timeout is a day rather than the default 60s, and wonder if that's significant.   It sounds like an nginx bug, and just possibly this post about ZLIB compression and keepalive is related: http://forum.nginx.org/read.php?2,170139,209671
Comment: "proxy_read_timeout is a day rather than the default 60s"  You win the prize. That is the issue. Thank you!
Answer: What i would do is attach to the nginx process using strace , then try and shut it down and check your strace to see what file descriptor it is hung on. With this information use lsof to track down which file descriptor it is waiting for and go from there. My guess is it may be one of your upstream servers causing this.
Comment: Thank you! I agree with your suspicion. But how do I modify the nginx.conf so that it times out and moves on, instead of hanging for 5-10 or more minutes?
Answer: If it is a websocket server like the browser websocket protocol it needs to send the websocket shutdown to the connected browsers and close the socket.  The application at 192.168.2.*:3842 would be capable of doing so.  So you would need to send a signal to that application to tell it to send shutdown to its connected websockets.


Deletar registro pelo ID

Question: Criei um botão para deletar um registro no banco com o seguinte código:
Arquivo form.php:
<form action='deletar.php' method='post'>
<input type='submit' name='deletar' value='deletar' />

Arquivo deletar.php:
$del = "DELETE FROM autoriza WHERE ID = '' ";
$delgo = mysql_query($del) or die('Erro ao deletar');
echo "deletado";

Já tentei algumas alternativas de coletar o ID de cada registro, mas não obtive sucesso.
O que mais encontrei foi criar uma variável ( $id = $_POST['id']; ) e usar a variável no comando mysql (DELETE FROM... ID='$id').
Como consigo deletar um registro pela sua ID?
Comment: Funções `mysql_` estão sendo deprecated... Use PDO ou mysqli.
Comment: Como assim, você quer deletar um registro específico sem dizer qual? Pode explicar melhor?
Comment: @bfavaretto: quando o usuário envia um registro pelo form, automaticamente gera um ID. Queria pegar esse ID para colocar DELETAR cada registro.
Comment: @GustavoCave Ainda não está claro... Você quer dizer que acabou de criar um registro, mas não sabe como mandá-lo de volta para o botão de deletar correspondente?
Comment: @bfavaretto exatamente isso!
Comment: Pelo visto você quer saber uma coisa totalmente diferente do que perguntou. A sua pergunta é sobre como passar o id do browser para o servidor. Pelo visto você já sabe fazer isso, e a resposta do FCCDias também explica. Mas o que você quer saber de verdade é como devolver um ID do servidor para o browser logo após a criação de um registro. Nesse caso seria melhor uma pergunta separada (se você mudar esta, invalida as respostas que já tem). Ou entendi tudo errado?
Comment: É isso @bfavaretto. Apenas deletar o registro no qual está sendo solicitado. No caso, usar a ID do registro para deleta-la.
Comment: Eu já consegui fazer deletar pelo ID, mas ele está pegando todas as linhas e então tudo é deletado.
Comment: E também consegui fazer deletar, mas sempre pega o ID menor e então deleta o mesmo, independente de qual eu tentei deletar.
Comment: Sinto muito Gustavo, mas por mais que você explique eu não consigo entender o que você já fez e o que não consegue fazer.
Comment: @bfavaretto sem problemas! agradeço a sua tentativa!
Answer: Eu fiz um post para um pergunta Login em PHP com Níveis de Permissão que mostra
como deveria proceder com $POST, Mysql*, PDO, Mysqli e filter_input para uma melhor segurança, mas, eu fui seguindo seu exemplo com intuito que entenda relação input, form, hidden com PHP. Seria muito legal depois de entender como acontece essa exclusão, que siga para a normalização da codificação, conforme link acima
No form deverá conter o campo text ou hidden com o valor do código que você deseja mandar para o script PHP realizar a tarefa de exclusão via SQL banco MySql.
No exemplo que estou te passando esse formulário contem um hidden com nome id com value de 1, então, ao clicar no botão deletar ele vai submeter o formulário e executar a SQL de exclusão
//Aqui o código id ta fixo (campo hidden)
<form action='deletar.php' method='post'>
    <input type='hidden' name='id' value='1'>
    <input type='submit' name='deletar' value='deletar' />
</form>

//Aqui você digita o código (campo text)
<form action='deletar.php' method='post'>
    <input type='text' name='id' value=''>
    <input type='submit' name='deletar' value='deletar' />
</form>

if (isset($_POST['id'] && is_numeric($_POST['id'])) {
     $del = "DELETE FROM autoriza WHERE ID = " . $_POST['id'];
     $delgo = mysql_query($del) or die('Erro ao deletar');
     echo "deletado";
}

Answer: $del = "DELETE FROM autoriza WHERE ID =".$_POST['id'];
$delgo = mysql_query($del) or die('Erro ao deletar');
echo "deletado";

Cria um codição para saber se foi enviado o id, ou use if (isset($_POST['id'].
E use mysqli, pois a mysql_ está sendo descontinuado na nova versão do PHP.

Deletar registro pelo ID


How to quick and easy remove part of an URL in Nginx with HttpRewriteModule?

Question: I know about the HttpRewriteModule, but I don't really know how to handle regex and I would need to redirect all URLs within a certain directory to another, specifically:
From: example.com/component/tag/whatever
To: example.com/tag/whatever
Could some one tell me how to do this in Nginx?
Answer: Do you mean something like:
rewrite ^/component(.*)$ $1 last;

Comment: You may need to replace last by break. (Last will try to resolve other locations after the rewrite).
Comment: It only worked for me with `break` and not with `last`.
Comment: `last` = stop rewriting this request and search for a new matching `location` block, and `break` = stop rewriting this request and continue execution within the current `location` block
Comment: https://www.regex101.com/r/qJ5gU1/1 has explanation on the right side
Comment: I think this will do it, thank you so much. I'm awful at regular expressions; I will have to try to learn them...
Comment: @ThomasDecaux  what is the difference between break and last
Answer: Depending where you define the rewrite directive you have two ways to implement it:
A. In the server context
server {
    ...
    rewrite ^/component(.*)$ $1 last;
    ...
}

B. In the location context
location /component {
    rewrite ^/component(.*)$ $1 break;
}

Teo, why did you change the flag last to break? Because, if this directive is put inside of a location context, the last flag will make nginx to run 10 cycles and return the 500 error.


Is the group $(G,*)$ abelian?

Question: Let $(G,*)$ be a finite group in which the sets $C_a$={$x\epsilon G$|$ax=xa$} have the same cardinality, for all $a \epsilon G$ \{e}. My question is: is the group abelian?
Comment: And next: we can ask whether it is true for infinite groups.  In particular, if all sets $C_a$ are finite.
Answer: Yes, it is true for finite groups and there are counter examples in infinite groups.
case$1$: Let $G$ be a finite group;
Assume that $G$ is nonabelian.
Let $g\in Z(G)$ and $g\neq1$ then $C_g=G$ then it is true for all element which is a contradiction since we assumed that $G$ is nonabelain.
So, We must also assume that $Z(G)$ is a trivial group.
Let's write class  equation and fix $k=[G:C_G(a)]$
$$|G|=|Z(G)|+ {nk}$$ for some $n\in \mathbb Z$ and since $|Z(G)|=1 $ we have
$$|G|=1+ nk$$
Then we have, $$|G|\equiv1 \text{ } mod(k)$$
 Which is a contradiction since $k$ is a divisior of $|G|$.
Note that:Class equation is $|G|=|Z(G)|+\sum [G:C_a] $
case$2$: For infinite group it is not true.
Let $G=S_3\times \mathbb Z$ then clearly $G$ is not abelian but for every element $a$ in $G$
$C_G(a) $ has countably infinite elements.
Conclusion: We see that it is true for finite groups and found counter example for infinite groups.
Even if it is not true for infinite groups, I wonder whether it is true or not for locally finite infinite groups.

Is the group $(G,*)$ abelian?


Use Jest to test an API endpoint and its response

Question: I want to use jest to test an API endpoint to check if it returns a response and if the JSON contains the parameter keys that I need.
My function looks like the following:
export function getFiveDayWeatherByCoordinates(id) {
  let url = FORECAST_ID_URL(id);

  return fetch(url)
    .then(response => response.json())
    .then(data => {
      return data;
    })
    .catch(err => console.log(err));

}

It returns a JSON with a set of parameters, I will post only a snapshot:
{
cnt: 14,
cod: "200",
city: {
  coord: {lat: 38.7169, lon: -9.1333},
  country: "PT",
  id: 8012502,
  name: "Socorro",
  population: 0,
  timezone: 3600,
}

Every tutorial that I see until now says to mock the response, but I want to test the actual API.
Comment: you can use Jest for testing your react app.
Comment: do you want to test the api in server side itself? is it express?
Comment: I want to test the openweathermap API, it's not mine
Comment: what and why do you want to test then? also you cant test response, you can validate though.
Comment: Yes, I want to validate the response. I want to test the API response to see if it doesn't break my application. Since any response change would break the app.
Comment: for that you already have catch block. if you want to validate some parameters in response, you write your own basic javascript validations. you cannot use jest and all for this.
Comment: What should I use to test an API? Maybe Postman? Because I will not be accessing my app every day to check if it's still working.
Answer: I would suggest using Frisby.js to test the API responses. It's a great test framework for API testing that runs in Jest. I've used it numerous times to write API and backend integration tests. Although, I typically keep these test suites separate from my UI unit tests.
Here's an example:
it('should return weather coords', async () => {
  return frisby
    .get(`${global.apiUrl}/my-weather-endpoint`)
    .expect('status', 200)
    .expect('jsonTypes', Joi.object({
      cnt: Joi.number().required(),
      cod: Joi.string().required(),
      city: Joi.object({
        coord: Joi.object({
          lat: Joi.number().required(),
          lon: Joi.number().required()
        }),
        country: Joi.string().required(),
        id: Joi.number().required(),
        name: Joi.string().required(),
        population: Joi.number().required(),
        timezone: Joi.number().required()
    }).required()
  });
});

Frisby also encourages the use of the Joi validation framework (it's already included in the npm package).
Comment: thanks for the advice, will have a look at Frisby.js, it looks to do what I need
Comment: you cant write a unit test for something that's your app does not include.
Comment: @AZ_ - It's not a unit test. It's more of an integration test. You can surely write a test that makes assertions about the response of an API, even if the API is not yours.
Comment: Glad it worked out @DiogoPeres. Good luck with your project.


Taylor series for $\log(1+x)$ and its convergence

Question: I know the expression for the Taylor series of $\log(1+x)$.
However, I don't understand how to prove the convergence of the series for $x>1$ and its divergence for $x<1$. Can someone explain the reason for this?
Comment: Hint, integrate the alternating geometric series
Comment: Alternately, differentiate n times. The ratio test will give you a radius of convergence of 1.
Comment: I'm voting to close this question as off-topic because it is about two years old with, by now, a known solution
Answer: We have (i) convergence if $|x|\lt 1$, and divergence if $|x|\gt 1$. This can be done by using the Ratio Test.
We also have (ii) convergence at $x=1$ and divergence at $x=-1$. For $x=1$, we have an alternating series. For $x=-1$, we get a close relative of a familiar divergent series.
Answer: For $0 \le r < 1$ $$\frac{1}{1-r} = \sum_{k=0}^\infty r^k$$
Integrate both pats $ln(1-r) =  \sum_{k=1}^\infty \frac{r^{k}}{k} $
For $-1 < r \le 0$ $$\frac{1}{1+r} = \sum_{k=0}^\infty (-1)^kr^k$$
Integrate both pats $ln(1+r) =  \sum_{k=1}^\infty \frac{(-1)^{k-1}}{k}r^{k} $


Boogie Woogie in another keys what are the limits?

Question: I'm a pianist and I play boogie woogie very well in C and G. Everyone knows that these are the easiest to play on, but guitarists like E and A and maybe D. I started to learn some riffs in A and E but it is not easy.
So my question is:
What are the limits for playing Boogie Woogie in these keys?
Can we reach the same level of proficiency playing in these new keys that we can reach playing in C or G?
Comment: I don't know enough to give a full answer, but I believe the answer is yes, it is possible to play as comfortably in A, E, D, or any other key as you currently do in C and G. In fact, I believe that many experienced pianists would disagree that C and G are the easiest keys to play in. In [this answer](http://music.stackexchange.com/a/15222/3265), the poster points out that "F# and C# Major/minor are relatively common keys for solo [piano] literature" because experienced pianists find it easier to play on the black keys!
Comment: @Kevin, that was me! This issue is probably more complicated than I made it sound, I think a lot of pianists, probably most if not all, find C or G major easier to *read*. But it's a weird case where what is easy for our eyes is not necessarily as easy for our fingers and vice-versa. I consider F# major in particular to be the absolutely easiest scale to play, and I tend to gravitate to that key or similar keys when freely improvising because it's so comfortable. Piano-centric composers like Beethoven, Chopin and Liszt tend to write in those keys very frequently.
Answer: There really are no major limits for playing anything in any key on piano. Certain players are more familiar and comfortable with certain keys, but it is possible for a pianist to play in any key. It's all just a matter of practice. The only minor stumbling block is the fingering of a piece may change with the key.
Answer: I think a big challenge I've faced in transitioning boogie woogie piano (or blues piano also), is around restructuring grace notes to play up (or down) to the black keys.
I've gotten sounds close to what I can make when playing Grace notes from sharps/flats onto the naturals, but there is the physical limitation imposed by the way a piano is built that I cannot quite overcome.
It's physically impossible to slide a single finger off of a natural (white) key onto a sharp/flat (black) key because it is above the point where the white key rests.
The opposite is not true, when a black key is fully depressed, it is above two white keys, and therefore can be struck with the same finger in a single motion.
There are physical limitations with the way the piano is built and for those reasons the same sound requires a more complex motion. In the case above, what can be played with a single finger in the key of C, requires two fingers in the Key of E flat. There are sounds that simply are impossible to recreate in other keys as a result.


Como desvincular elementos de objetos?

Question: Tenho a seguinte função
addPerson = function(id, name) {
    people[id] = name;

    console.log(people[id].parentNode); // Exibe corretamente
    console.log(name.parentNode); // Exibe corretamente

    name.parentNode.removeChild(name);

    console.log(people[id].parentNode); // Deixa de exibir
    console.log(name.parentNode); // Deixa de exibir

    if(!name.previousElementSibling) {
        $(name.parentNode).append(name);
    }else{
        name.previousElementSibling.insertAfter(name);
    }
};

--
O parâmetro name referência um elemento no DOM, quando a função é chamada people[id] recebe esse elemento, porém ao executar alguma alteração exemplo exclusão do elemento, a referência perde acesso aos métodos, exemplo o parentNode, tentei usar o clone do J-query, mas não funcionou.
Existe alguma forma de clonar o objeto, manter os métodos nativos e desvincular ele do elemento no DOM?
Comment: Hummm então em vez de vetor você poderia utilizar uma lista, acho que seria mais viável no seu caso.
Answer: Não precisas de clonar o elemento a não ser que precises de vários iguais.
Podes usar var semPai = el.parentElement.removeChild(el); e ficas com o elemento "na mão" fora do DOM.

var div = document.querySelector('div');
var btn = div.firstElementChild;
btn.addEventListener('click', function() {
  console.log('Clicado!');
});

var semPai = btn.parentElement.removeChild(btn);
console.log(div.children.length); // vazio
console.log(semPai.parentNode); // sem pai!

btn.click();

<button>Clica-me</button>

Se precisares saber a posicão inicial sugiro criares um objeto para guardar essa informação assim:

var objs = [];

var div = document.querySelector('div');
var btn = div.firstElementChild;
btn.addEventListener('click', function() {
  console.log('Clicado!');
});

// guardar para mais tarde
objs.push({
  el: btn,
  previousSibling: btn.previousElementSibling || {},
  parent: btn.parentElement
});

btn.parentElement.removeChild(btn);
console.log(div.children.length); // 0 => vazio
console.log(btn.parentNode); // null => sem pai! está fora do DOM

// depois mais tarde...
objs[0].parent.insertBefore(objs[0].el, objs[0].previousSibling.nextSibling);

<button>Clica-me</button>

Comment: Ainda não consegui, mesmo atribuindo diretamente a uma variável, estou usando uma biblioteca não sei se tem algo a ver.
Comment: @FelipeDuarte podes descrever mais o que a aplicação deve fazer? não te preocupes com a implementação, explica o que o precisas no programa
Comment: É um sistema de fazer e desfazer, estou usando essa biblioteca https://github.com/ArthurClemens/Javascript-Undo-Manager, ao acessar o método fazer preciso excluir o elemento (se existir) e recoloca-lo na mesma posição em que se encontrava
Comment: @FelipeDuarte ok. E como sabes onde estava? querias que o elemento guardasse isso mesmo estando fora do DOM, é isso?
Comment: É que estou fazendo testes, em definitivo tudo vai ser criado dinamicamente, por enquanto estou pegando direto no DOM. quando o método refazer for acionado, o elemento guardado no vetor, volte para o DOM na mesma posição, com previousElementSibling conseguiria coloca-lo na posição correta, porém o método some.
Comment: @FelipeDuarte juntei uma sugestão à resposta

Como desvincular elementos de objetos?


Initialize a collection of dataframes with dummy values

Question: I have a number of different statistical tests to be performed which resulting values all should be written to separate files.
Therefore I want to initialize a collection of empty pandas data frames
but without showing to many redundant lines in my code.
So far I initialize them all independently but there has to be a better way...who has an idea?
pearson_r_df  =  pd.DataFrame(columns=features_list,index=features_list).replace(np.nan, 1.0)
spearman_r_df =  pd.DataFrame(columns=features_list,index=features_list).replace(np.nan, 1.0)
dcor_r_df     =  pd.DataFrame(columns=features_list,index=features_list).replace(np.nan, 1.0)

I would love to have a one-liner like:
df1,df2,df3 = function_which_initizialises_several_dataframes()
Comment: Wrap your three lines in a function and return the three dataframes.
Comment: What issues did you find while writing such a function?
Comment: This should not be the problem but then I would have to define a new function. I am thinking about something like a list/dict comprehension ?
Answer: You can use a comprehension like so:
df1, df2, df3 = (pd.DataFrame(columns=features_list,index=features_list).replace(np.nan, 1.0) for _ in range(3))


C++ displaying the wrong object

Question:
I am a beginner in C++ and I am trying to create 2 classes that stores Movie for each Day. For example, there are 2 movies on saturday. One of the movie is Batman and the other is Spiderman. So the object Day saturday should store 2 different movies. However, the problem is when I tried to display the object stored in saturday with the function showAllMovies() within the class Day, it showed the last movie only. Any idea what I have done wrong?

EDIT: I can only use these libraries since my assignment won't allow me to use other libraries.
<iostream>, <iomanip>, <fstream>, <cmath>

#include <iostream>
using namespace std;

class Movie {
private:
    char* name;
public:
    void setName(char* n) {
        name = n;
    }
    char* getName() {
        return name;
    }
};

class Day {
private:
    int movieCount = 0;
    Movie movie[20];
public:
    void addMovie(Movie p) {
        movie[movieCount] = p;
        movieCount++;
    }
    void showAllMovies() {
        for (int i = 0;i < movieCount;i++) {
            cout << "Index: " << i << ", Name: " << movie[i].getName() << endl;
        }
    }
};

int main()
{
    Day saturday;
    int numOfMovies = 0;

    cout << "Input the number of Movies: " << endl;
    cin >> numOfMovies;

    cout << "Input the name of Movie: " << endl;
    for (int i = 0;i < numOfMovies;i++) {
        char movieName[10];
        //Get input
        cin >> movieName;
        Movie m;
        m.setName(movieName);
        saturday.addMovie(m);

    }

    //Show all the name of movies
    cout << "All movies on saturday: " << endl;
    saturday.showAllMovies();

    return 0;
}

Input:
2
Batman
Spiderman
Output:

I am expecting to get something like
All movies on saturday:
Index: 0, Name: Batman
Index: 1, Name: Spiderman

Thanks to everyone helping me out. The Solution is to change
char movieName[10];

to
char *movieName = new char[10];

Comment: You store a pointer to the name, and they all point to the same `char movieName[10];`. Use a `std::string` member instead.
Comment: Why you do not use std::vector to store your Movie objects and std::string to store Movie name?
Comment: Not related to your question, but use "std::string name;" instead of "char* name;"
Comment: What did you discover [when debugging](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)?
Answer: for (int i = 0;i < numOfMovies;i++) {
        char movieName[10];
        //Get input
        cin >> movieName;
        Movie m;
        m.setName(movieName);
        saturday.addMovie(m);

    }

when you call setName internally you make name (which is field of Movie object) point to movieName - however, movieName dies on the next iteration of the for loop due to scope.
The last instance of movieName should also not be accessed after the loop ends.
Comment: Any way I can solve it without using any other libraries like strings or vector?
Comment: @BlueFishy Instead of doing char `movieName[10]` create `creatMovieName` on the heap e.g. using `new`. then point to that. in that case it will not die when loop ends. But you will need to free it properly later on.
Comment: @BlueFishy Make a copy of the string using `strdup()`.
Comment: @GiorgiMoniava Thanks a lot! Solved the problem :)

C++ displaying the wrong object


GooglePlus Not Supporting for IOS 4.3

Question: I have a Application Where i am integrating GooglePlus SDK to support GooglePlus.Its working fine till IOS 5.But when we run on IOS 4.3 it crashes with following Error.
dyld: Symbol not found: _OBJC_CLASS_$_UIStoryBoard

i am not using Any storyBoard in my Application but why this error Comes??
As per googlePlus Documentation it supports From IOS 5. But i just want to Know there is any way where we can make it work for IOS 4.3 as my Application Supports from IOS 4.3.
Is it Possible To support for IOS 4.3? If Yes how can we solve this.
Comment: Don't support iOS 4.3.
Comment: Drop support for iOS 4, 5, and (maybe) 6. iOS 7 is already at 80% world-wide adoption: https://mixpanel.com/trends/#report/ios_7
Answer: As you can see from the exception, class UIStoryBoard is not supported in earlier versions of iOS than 5.0.
Since Google Plus SDK uses Storyboard in some way, unknown to me personally, you cannot use this SDK with any iOS that has version less than 5.0.
Reference from Apple:

UIStoryboard: Available in iOS 5.0 and later.

P.S. It seems to me that it is too redundant for any kind of a project to support version that is 3 releases older than current - iOS 7.

GooglePlus Not Supporting for IOS 4.3


Método save do Spring Boot sobrescrevendo registro

Question: O meu objetivo é pegar o registro de uma tabela chamada Membro através do ID e gravar esses registro em outra tabela chamada GrandeComissao.
Veja as tabelas em questão.
<code>@Entity
@Table(name = "membro")
public class Membro {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long codigo;

    @NotNull
    private String nome;

    @NotNull
    private String email;

    private String senha;
</code>
E a tabela GrandeComissao.
<code>@Entity
@Table(name = "grande_comissao")
public class GrandeComissao {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long codigo;

    private String nome;

    private Integer voto;
</code>
Esse abaixo é o comportamento atual. Existem 3 registros na tabela membro. Eu busco a tabela membro pelo ID e através dela eu consigo capturar os outros valores desse registro e pegar eles e gravarem na tabela grandeComissão assim no postman.
post  localhost:8080/grande_comissao/1
<code>{
    "codigo": 1,
    "nome": "Paulo cesar",
    "voto": 1
}
</code>
O que acontece é que ele fica sobrescrevendo. Eu não consigo salvar os três registros
<code>localhost:8080/grande_comissao/2
localhost:8080/grande_comissao/3
</code>
O resultado vai ser esse ao realizar uma consulta GET.
<code>{
    "codigo": 1,
    "nome": "Paulo gilson",
    "voto": 1
}
</code>
O resultado esperado deveria ser esse abaixo ao realizar uma consulta GET
<code>[
    {
    "codigo": 1,
    "nome": "Paulo cesar",
    "voto": 1
    },
   {
    "codigo": 2,
    "nome": "Paulo testa",
    "voto": 1
   },
    {
        "codigo": 3,
        "nome": "Paulo gilson",
        "voto": 1
    }
]
</code>
Eu preciso de ajuda para alterar o algoritmo responsável em realizar a gravação desses registros, pois não deveria está sobrescrevendo, alguém teria uma ideia de como corrigir o código abaixo.
<code>@PostMapping("/{codigo}")
public ResponseEntity<GrandeComissao> buscarPeloCodigo(@PathVariable Long codigo) {
    Optional<Membro> membro = this.membroRepository.findById(codigo);
    grandeComissao.setNome(membro.get().getNome());
    grandeComissao.setVoto(1);
    grandeComissaoRepository.save(grandeComissao);
    return ResponseEntity.ok(grandeComissao);
}
</code>
Estou aberto a perguntas!
Essa é minha classe controle
<code>@RestController
@RequestMapping("/grande_comissao")
public class GrandeComissaoResource {

    @Autowired
    private MembroRepository membroRepository;

    @Autowired
    private GrandeComissaoRepository grandeComissaoRepository;

    @Autowired
    private ApplicationEventPublisher publisher;

    GrandeComissao grandeComissao = new GrandeComissao();

    GrandeComissao grandeComissaoSalva = new GrandeComissao();

    @GetMapping
    public List<GrandeComissao> listar() {
        return grandeComissaoRepository.findAll();
    }

    @PostMapping("/{codigo}")
    public ResponseEntity<GrandeComissao> buscarPeloCodigo(Long codigo) {
        Long id = codigo;
        Optional<Membro> membro = this.membroRepository.findById(id);
        grandeComissao.setNome(membro.get().getNome());
        grandeComissao.setVoto(1);
        grandeComissaoRepository.save(grandeComissao);
        return ResponseEntity.ok(grandeComissao);
    }

}
</code>
Answer: Certifique-se de que o registro que está indo para o método save, esteja sem identificador pois se ele está sobrescrevendo provavelmente o objeto que está chegando está com um identificador
Retire -> GrandeComissao grandeComissao = new GrandeComissao(); de atributo da classe e coloque-o dentro do método
Assim:
<code>@PostMapping("/{codigo}")
    public ResponseEntity<GrandeComissao> buscarPeloCodigo(Long codigo) {
        Long id = codigo;
        Optional<Membro> membro = this.membroRepository.findById(id);
        GrandeComissao grandeComissao = new GrandeComissao();
        grandeComissao.setNome(membro.get().getNome());
        grandeComissao.setVoto(1);
        grandeComissaoRepository.save(grandeComissao);
        return ResponseEntity.ok(grandeComissao);
    }
</code>
Dessa forma você terá certeza de que toda vez que houver uma requisição nesse endpoint, será criado um objeto grandeComissao diferente para cada requisição
Answer: Tente fazer o seguinte:
Copie o trecho GrandeComissao grandeComissao = new GrandeComissao();
que vc declarou de forma global e cole na primeira linha do método buscarPeloCodigo;
Como vc declarou o objeto de forma global, quando ele passa pelo save é automaticamento injetado um id nele, quando vc chama pela segunda vez já deve ter um id lá, portanto a partir daí a aplicação fica dando updates ao invés de inserts.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


32bit ODBC Driver not Installing correctly on Windows 7 64 bit machine

Question: I am having a problem installing the 32 bit Advantage ODBC driver (v9.10) on a Windows 7 64 bit computer.  When I run the install routine, I am logged on under the local Administrator account and the install completes without any errors.  When I open the 32 bit ODBC manager and try to add a new System (or User) DSN, I get the following error message:  "The Setup routines for the Advantage Streamline SQL ODBC ODBC driver could not be found.  Please reinsall the driver".  Rerunning the install routine (with the repair option) and/or removing/reinstalling the driver does not resolve the problem.  I've also noticed that when I'm creating the DSN and I go to select the driver, the Advantage driver is listed but the Version, Company, File and Date fields are all blank.
Has anyone else see this and have a fix for it?
Thank you!
Comment: Better on serverfault.
Answer: I finally found a solution to this.  When I was intalling the driver, I had selected the option to install it for Everyone.  I uninstalled/reinstalled it only this time selecting the option to install it just for me.  For whatever reason, this fixed the problem and the driver installed/registered correctly.
Answer: You need to configure the connection by using the 32 bit ODBC Data Source Administrator. Instead of going through administrative tools use \Windows\SysWow64\odbcad32.exe.
Answer: You will definitly want to use the 32-bit ODBC Data Source Administrator as the other two have said.
However, I do have one other suggestion you may try.  I have seen this work when the driver does not get registered properly for some reason so it may help in this case.
Try copying the adsset.dll from  C:\Program Files (x86)\Advantage \ODBC to c:\windows\SysWow64 and see if that helps.
Answer: I havent dealt with Advantage, but I do know other drivers which are 32bits and installed on 64 bit machines.
Try installing the driver in your 32bit folder i.e the C:/Windows/SysWOW64 folder. see if that helps


What are some good interview questions for statistical algorithm developer candidates?

Question: I'm interviewing people for a position of algorithm developer/researcher in a statistics/machine learning/data mining context.
I'm looking for questions to ask to determine, specifically, a candidate's familiarity, understanding and fluidity with the underlying theory, e.g. basic properties of expectation and variance, some common distributions, etc.
My current go-to question is: "There is an unknown quantity $X$ which we would like to estimate. To this end we have estimators $Y_1, Y_2, \ldots, Y_n$ which, given $X$, are all unbiased and independent, and each has a known variance $\sigma_i^2$, different for each one. Find the optimal estimator $Y=f(Y_1,\ldots, Y_n)$ which is unbiased and has minimal variance."
I'd expect any serious candidate to handle it with ease (given some time to work out the calculations), and yet I'm surprised at how many candidates which are supposedly from relevant fields fail to make even the smallest bit of progress. I thus consider it a good, discriminative question. The only problem with this question is that it is only one.
What other questions can be used for this? Alternatively, where can I find a collection of such questions?
Comment: For many machine learning people (including good ones), that question is way out of their comfort zone. This is an obvious statistician question.
Comment: This question is legitimately borderline on / off topic. However, it has many views, several upvotes, an answer w/ several upvotes, &, moreover, is CW. It could stay open, IMO.
Comment: A point of caution, Google did a big study of their internal HR process and found that interviewer scores didn't correlate at all with subsequent job performance!! My impression of the literature here is that (1) puzzle type questions are the absolute worst, serving only to make the interviewer feel smart (i.e. 0 forecasting power) and (2) resume,  experience based questions may have predictive value. Past performance forecasts future performance & you may want to focus questions to ascertain what their past performance was, but the interview is far less informative than interviewers think.
Comment: Unbiasedness is guaranteed by having the weights sum to unity. However, even limiting your solution to linear combinations of the estimators, it's almost always going to be the case that multiple estimators based on the same data will be *highly* correlated. (If they are truly independent, then they would be applied to disjoint, independent subsets of the data.) It's not at all evident that a linear combination of estimators will be optimal, though.
Comment: The go-to question might be worded in a confusing manner. For example, the use of $X$ with a capital would make $X$ seem random. But since you're mentioning minimum variance, it would seem like you want $X$ to be non-random (in which case, why does the variance of the estimators not have a written dependence on $X$?)
Comment: @MeniRosenfeld: Well, you used the word optimal, which is the problem. Let $X$ be a parameter.  If $Y_1 = X + S_1$ and $Y_2 = X+ 2 S_2$ where $S_1,S_2$ are both i.i.d. rademacher's, $Y_1,Y_2$ are independent given $X$ and both are unbiased estimators of $X$ with different variance. However, knowing $Y_2 - Y_1$ is 3,1,-1 or -3 gives you what $S_1$ and $S_2$ are, and thus you can estimate $X$ exactly (i.e. with variance zero). However, your linear estimator will have positive variance since $w_i^2, \sigma_i^2 >0$ for some $i$.
Comment: A lot of basic knowledge questions will filter out clearly incompetent candidates ("what is a confidence interval?"). However, the best way to see if a person will fit the position is to be transparent with the kinds of problems you want to solve. So just present a few things you want them to work on and ask for their ideas on how they would approach the problem if:

1) They have one week to code a solution.

2) They have a few months to code a solution.

Don't be vague, actually show them a few tables of your data (instead of doing a thought experiment on the board).
Comment: @MarcClaesen: I've seen statistics Phds fail on it too. Anyway, ML and stats are very closely related, and I do want to rule out those for which this question is outside their comfort zone (even if they may be good for other positions).
Comment: Just ask calculus questions. You'll be surprised how many candidates can't take integrals.
Comment: @meni I am intrigued, what you as an interviewer consider an A+ answer to your question ?
Comment: @Batman: When I'm actually asking it I spend more time explaining the question, and I'm there to answer any questions and make sure everything is clear.
Comment: @Repmat: First, I expect them to realize that taking $Y=\sum_iw_iY_i,\ \sum w_i=1$ is a logical thing to do (I don't expect to prove that this is the best possible). Then I'd expect them to realize that $w_i$ should be smaller the larger $\sigma_i$ is. Then I expect them to write $\mathbb{V}[Y]=\sum_iw_i^2\sigma_i^2$. Then I expect them to find the $w_i$ for which this is minimal (answer is $w_i \propto 1/\sigma_i^2$), there are several ways to do that, some with more cumbersome calculations than others. They don't have to get everything instantly, they can take their time and get some hints.
Comment: @Batman: Interesting observation. But the point is that the function $f$ should give an unbiased estimator whatever the distributions of $Y_i$ are (under the constraints). You can construct a better estimator for this particular distribution, but it will not generalize. I'm fairly confident a weighted average is the only way to guarantee unbiasedness (I'll be happy to be corrected). And anyway, the candidates that fail don't do so because they're sophisticated enough to think of edge cases - it's because they don't know basic stuff such as variance being additive for independent variables...
Comment: Find out if the candidate to develop statistical algorithms knows anything about the fundamentals of numerical mathematical calculation and software, i.e., numerical analysis, to include effects of finite precision roundoff error, and tolerances and convergence for iterative processes. Would you believe std being computed as sqrt(abs(var)) or sqrt(max(var,0)), as the fix to having gotten a sqrt of negative argument error using a numerically unstable method to calculate variance ... in multi-billion dollar weapon systems? Many R packages in CRAN are totally unsound and unreliable numerically.
Comment: using software libraries like R's glmulti or MPC would engage the question, but perhaps in a more "do the job" and not as much "first principles derivation" as the asker seems to be looking for.
Answer: What do you want your statistical developer to do?
The US Army says "train you will fight, because you will fight like you were trained".  Test them on what you want them to do all day long.  Really, you want them to "create value" or "make money" for the company.
Boss 101
Think "show me the money."

Money grows on trees called employees.  You put in a "dime" (their wages) and they pay you a "quarter" (their value).
If you can't relate their job to how they make money for the company then neither you nor they are doing their job correctly.

Note: If your symbolic manipulation question doesn't cleanly connect to the "money" then you might be asking the wrong question.
There are 3 things every employee has to do to be an employee:

Be actually able to do the job
Work well with the team
Be willing/motivated to actually do the job

If you don't get these down rock solid, no other answer is going to do you any good.
If you can replace them with a good piece of software or a well-trained teenager, then you will eventually have to do it, and it will cost you.
Data 101
What they should be able to do:

use your internal flavors of software (network, os, office,
presentation, and analysis)
use some industry standard flavors of software (Excel, R, JMP, MatLab,
pick_three)
get the data themselves.  They should know basic data sets for basic
tasks.  They should know repositories.  They should know which famous
data is used for which task.  Fisher Iris.  Pearson Crab.  ... there
are perhaps 20 elements that should go here.  UCI, NIST, NOAA.
They should know rules of handling data.  binary data (T/F) has very
different information content than categorical (A,B,C,D) or
continuous.  Proper handling of the data by data-type is important.
A few Basic statistical tasks include: are these two the same or
different    (aka cluster/classify), how does this relate to that
(regression/fitting including linear models, glm, radial basis,
difference equations), is it true that "x" (hypothesis testing), how
many samples do I need (acceptance sampling), how do I get the most
data from few/cheap/efficient experiments (statistical Design of
experiment) - disclaimer, I'm engineer not statistician  You might
ask them the question "what are the different fundamental tasks, and
how do you test that the statistician can do them efficiently and
correctly?
access/use the data themselves.  This is about formats and tools.
They should be able to read from csv, xlsx (excel), SQL, and
pictures.  (HDF5, Rdata)   If you have a custom format, they should
be able to read through it and work with the tools quickly and
efficiently.  They should know strength/weakness of the format.  CSV
is quick use, been around forever, fast prototype, but bloated,
inefficient and slow to run.
process the data properly, using best practices, and not committing
sins.  Don't throw away data, ever.  Don't fit binomial data with a
continuous line.  Don't defy physics.
come up with results that are repeatable and reproducible.  Some
folks say "there are lies, damn lies, and statistics" but not at my
company.  The same good input gives the same good output.  The output
isn't a number, it is always a business decision that informs a
technical action and results in a business result.  Different tests
may set the dial at 5.5, or 6.5, but the capability is always
above 1.33.
present findings in the language and at the level that the decision
makers, and/or minion-developers, and/or themselves in a year, can
understand with the least errors.  A beautiful thing is being able to
explain it so your grandma gets it.  This (link) is my answer, but I like it.

Analytic zingers:
I think impossible questions are great.  They are impossible for a reason.  Being able to know whether something is impossible out the gate is a good thing.  Knowing why, having some ways of engaging it, or being able to ask a different question can be better.
Other CV questions.  (link)
On reddit.  (link)
others (link)
BTW: this was a good question.  I might have to update this answer over time.
Comment: This seems to be a good answer, for a different question than the one I asked. I didn't ask how to pick good employees (I'd probably ask something like that on workplace.se if I needed to), I asked about testing a specific qualification.
Comment: I will whittle it down to stats only then.