How does a categorical fixed effect differ from a random intercept?

Question: I'm trying to get my head around the differences between including a categorical variable as a fixed effect or as a random intercept. Let's get some data - which I found over here.
d <- haven::read_sav(file ="https://github.com/MultiLevelAnalysis/Datasets-third-edition-Multilevel-book/blob/master/chapter%202/popularity/SPSS/popular2.sav?raw=true")
d <- select(d, pupil, class, extrav, sex, texp, popular)
d$class <- as.factor(d$class)

In that blog I linked, they construct the following model (among others):
model2 <- lme4::lmer(popular ~ 1 + sex + extrav + texp + (1 | class), data = d)

summary(model2)$coef
              Estimate  Std. Error   t value
(Intercept) 0.80976625 0.169993377  4.763516
sex         1.25379981 0.037290049 33.622905
extrav      0.45443099 0.016165300 28.111510
texp        0.08840725 0.008764057 10.087480

Now I understand each unique level of $class is given a random intercept, but I can't seem to fully grasp how this is fundamentally different from the following:
model2.2 <- lm(popular ~ 1 + sex + extrav + texp + class, data = d)
summary(model2.2)$coef[1:4, ]
              Estimate Std. Error   t value      Pr(>|t|)
(Intercept) 0.62879232 0.12653481  4.969323  7.291758e-07
sex         1.37942361 0.04233690 32.582067 4.466222e-187
extrav      0.47530311 0.01815907 26.174417 4.569729e-130
texp        0.08882755 0.00350321 25.356048 3.474237e-123

In which each level of $class is given a $\beta$ estimate in relation to some reference level. I would understand different values for each level, but I don't get why the estimates and SEs of the other (fixed) effects are affected.
Answer: Fixed vs Random
I know this is an old question but I don't believe the old answer here really tackles the question fully. There are two ways you can think about it: what I will informally call the theoretical perspective and the data reduction perspective.
The theoretical perspective is that the fixed effects are those that you are actually interested in modeling as a direct effect on your outcome variable. We could include someone's gender/sex as a categorical predictor of income because we know from past research that these variables have some relationship with each other and can be an important one to investigate. However, some would be less concerned with, for example, the neighborhood someone comes from with relation to income if its not important to their model (though certainly this doesn't mean other researchers wouldn't find it so). If included as a random effect, we are in some part implying that we just think it's an annoyance factor that needs to be removed to clean up how accurate our fixed estimates are (though see below for when thats not such the case).  A key thing to notice here is that one person's fixed effect can be another person's random effect depending on what they're trying to say about their model.
The other perspective, one that I think is often lost when mixed models are taught, is the data reduction perspective, which is simply that we want to summarize a lot of information about variations in a DV based off selected clusters. This in my opinion is often more informative, because we often aren't interested in a random effect with few levels or one that doesn't include a lot of variance...we want something normally that varies a lot in order to 1) summarize the average distance from, say, the conditional mean 2) specifically compare across a variety of clusters (for example seeing which schools are above the mean in reading outcomes over others) and 3) remove bias from standard errors in the regression. In short, whereas many regressions are less concerned with what the random noise is trying to tell us, mixed models operationally add it in to inform researchers about a large depth in heterogeneity across settings, people, or other contextual factors so that we have more accurate assumptions about what the fixed effects are actually doing. This "pollution" in random variance can actually tell us a lot. A great example is the classic subject x item crossed effects design, wherein we can learn a lot about the ease/difficulty of different items and subject aptitude in general while untethering it from what fixed effects we deem important.
These two perspectives are in my opinion both important for selecting a categorical effect as either fixed or random. How one selects them is heavily weighted by theory as well as the underlying data supporting such models.
Edit: There is another factor that I believe helps solidify the distinction more, and that is the importance of the replication perspective. When we consider fixed effects, we are interpreting the effects as those we should see across studies with some semblance of stability. With repeated experiments, our understanding of the fixed effects should converge into an average effect of interest. This is not the case for random effects, where by definition we consider these effects to be totally random and should not have a predictable pattern (other than average variance perhaps).
As an example from Simon Wood's book on GAMs (p.72), the chapter on mixed models provides this example:

Now consider a practical example. The Machines data frame, from the
nlme package, contains data from an industrial experiment comparing 3
different machine types. The aim of the experiment was to determine
which machine type resulted in highest worker productivity. 6 workers
were randomly selected to take part in the trial, with each worker
operating each machine 3 times (presumably after an appropriate period
of training designed to eliminate any 'learning effect')...
We are interested in the effects of these particular machine types, but are only interested in the worker effects in as much as they reflect variability between workers in the population of workers using this type of machine. Put another way, if the experiment were repeated somewhere else (with different workers) we would expect the estimates of the machine effects to be quite close to the results obtained from the current experiment, while the individual worker effects would be quite different (although with similar variability, we hope).

This should further clarify the difference between fixed and random effects, as it should be clear that with your example, classes should not have a predictable fixed effect on the outcome given how widely they would vary from experiment to experiment.
Why This Matters for Your Comparison
Recall that above I mentioned how random effects influence the standard errors in measurement. This is because typically regressions which do not account for correlated errors are downward biased...in other words they greatly underestimate how influential an actual effect is because the accuracy of these estimates is influenced by the clusters in the data.
Probably the biggest reason you aren't seeing the big picture is because you are only looking at point estimates for the fixed effects in each regression. I fit a common toy dataset in R called sleepstudy to a lmer model below, then summarize and plot the random effects.
#### Load Libraries ####
library(lmerTest)
library(lattice)

#### Fit Data ####
fit <- lmer(Reaction ~ Days + (1|Subject),
            data = sleepstudy)
summary(fit)

#### Plot ####
dotplot(ranef(fit))

The summary is quite long, but the part you probably skipped is this portion that follows, which shows how the random effects vary (here subjects vary in reaction time substantially). This means that the day of this study effected reaction time, but this varied by subject, and without modeling this we cost ourselves some accuracy in the estimated effect consecutive day has on reaction time.
Random effects:
 Groups   Name        Variance Std.Dev.
 Subject  (Intercept) 1378.2   37.12
 Residual              960.5   30.99
Number of obs: 180, groups:  Subject, 18

Plotting the random effects shows a great summary of the random effects, which show by-subject variance around the conditional mean, the points being the average effect and the bars around it the fluctuation around those means. For example, Subject 337's reaction time is far slower on average, whereas Subject 309 is quite quick compared to others.

Going back to my previous point, this is important, as we could have just as easily entered Subject in as a fixed effect. However, this would have given us a ton of coefficients (one per subject), now way to meaningfully summarize their differences, and likely wouldn't be theoretically meaningful.
Answer: I answer the question:

I would understand different values for each (class) level, but I don't get why the estimates and SEs of the other (fixed) effects are affected.

The question posed in the title is already answered by @ShawnHemelstrand (+1).
Let's start by reproducing the model summaries. This step is important because the second model reported by the OP is not the intended model. (class is read as a numeric variable, so it has to be cast as a factor to estimate class-specific fixed effects.)
In the first model class is a random effect:
mod1 <- lmer( popular ~ sex + extrav + texp + (1 | class), data = d)

tidy(mod1, "fixed")
#> A tibble: 4 × 7
#>   effect term        estimate std.error statistic    df   p.value
#> 1 fixed  (Intercept)   0.810    0.170        4.76  226. 3.40e-  6
#> 2 fixed  sex           1.25     0.0373      33.6  1948. 7.68e-196
#> 3 fixed  extrav        0.454    0.0162      28.1  1955. 2.56e-146
#> 4 fixed  texp          0.0884   0.00876     10.1   102. 5.41e- 17

In the second model class is a fixed effect.
mod2 <- lm( popular ~ sex + extrav + texp + factor(class), data = d)

tidy(mod2)
#> A tibble: 103 × 5
#>    term           estimate std.error statistic   p.value
#>  1 (Intercept)      0.409     0.272      1.50  1.33e-  1
#>  2 sex              1.24      0.0376    33.0   8.87e-189
#>  3 extrav           0.452     0.0163    27.7   4.62e-142
#>  4 texp             0.0773    0.0143     5.39  7.79e-  8
#>  5 factor(class)2  -0.197     0.212     -0.928 3.54e-  1
#>  6 factor(class)3   0.0955    0.221      0.431 6.66e-  1
#>  ...

I have truncated the second summary table since the question is about the fixed effects. (To learn more about the random effects, see @ShawnHemelstrand's answer.)
Right away we notice something interesting: the estimate and std. error for sex and extrav change very little while the estimate and std. error for texp changes quite a bit. Why is that?
It's helpful to know what information these three explanatory variables represent: sex and extrav are the student's sex and extraversion on a scale from 1 to 10; texp is the teacher's experience in years.
So sex and extrav are individual-level predictor: they describe the students and vary within classes; while texp is a group-level predictor: it describes the classes and thus varies between classes but not within.
And that's the reason why the estimate and std. error of sex and extrav don't change much whether we treat the classes as fixed or random effects: the classes are big (they vary in size from 16 to 26 students) and most classes are coed (88 out of 100 classes have both sexes), so the individual-level effects are mostly estimated from within-class differences between boys and girls and between students across the spectrum of extraversion who are in the same class. These within-classes differences have the same interpretation in both models: if we compare two students in the same class, the expected difference in their popularity is due to sex and extraversion; the class and teacher effects cancel out.
If the dataset were balanced, so that each class has exactly the same distribution of sex and extrav, then there would be no difference between the models as far as the estimation of the sex and extrav effects is concerned. This of course will be very unlikely to occur in an observational study but more likely to hold in a designed experiment.
Answer: The SE of the fixed effects are made smaller when the  random effect is added because the new implied grouping of term members adds information that wasn't previously included. This grouping is not implied or encoded in a fixed effects style. It's additional information that you added. Sometimes folks will say that the improved term "steals" variance from other terms that they shouldn't have otherwise had.
Gelman and Hill's book, Data Analysis Using Regression and Multilevel/Hierarchical Models can help.
Also, see this excellent blog post on the topic.
Comment: Thanks, that helps! Will check out those resources. :)


I'm a 17 year old boy who has been described as a Tenor, but somehow I feel like my voice hit a brick wall

Question: First of all I have no idea how to warm up because somehow it feels pointless. second is that one day I would sing high and a few days or a week later it would seem like my voice is struggling to reach the same height.
I've been feeling this way for years. I've been singing since I was 4 years old but I was ignorant of what it means to be a singer. As a matter of fact I had no idea about the world, that singing can be a profession and that you need proper technique.
Back then I was very shy to the point of feeling like I couldn't breathe. In my spare time when I was alone I would sing at my highest and I would sound a little feminine, but now I don't really know where is my highest.
I often characterize my voice as a road, at the ending of that road is not a barricade it's a collapsed bridge. Sorry for all the intro but my question is, how do I get to the other side of that bridge or how do I release my voice to go higher and extend my vocal range?
Answer: There are so many things that you can do wrong as a singer. Only a qualified vocal teacher listening to you physically will be able to tell you exactly what you are doing wrong, and how to work on your problems. You need to take some lessons.


If $X \in \{1, 2, 3\}$, $Y, Z \in \mathbb{R}$ are random variables, what is meant by $X \not\!\perp\!\!\!\perp Y|Z$?

Question: Let $X \in \{1, 2, 3\}$, and $Y \in \mathbb{R}$  and $Z \in \mathbb{R}$ denote random variables. Suppose that:
$$X \not\!\perp\!\!\!\perp Y|Z.$$
In words, $X$ is not conditionally independent of $Y$ given $Z$. In probability notation, does the above statement mean one of the following?
(1)
$P(Y|Z, X=1) \neq P(Y|Z, X=2) \neq P(Y|Z, X=3)$
Or does it mean:
(2) $P(Y|Z, X=j) \neq P(Y|Z, X=j')$ for at least one pair of $(j, j')$ where $j \in \{1, 2, 3\}, j' \in \{1, 2, 3\}$ and $j \neq j'$.
Note that (1) is a special case of (2). I'm not quite sure whether $X \not\!\perp\!\!\!\perp Y|Z$ means (1) or (2).
Answer: It means (2) to the extent that (2) is well-defined (eg, ignoring concerns about sets of measure zero)


How does arbitration work in baseball?

Question: First, my understanding is that they use professional labor arbitrators, not people with a strong specific knowledge of baseball. So "old" metrics, hits, runs, RBIs and ERAs count for more than on base percentages (OBPs) or FIPs (field independent pitching statistics).
Second, my further understanding is that first, second and third year "arb" players tend to get about 40, 60 and 80 percent of what a free agent would get "on average," although their is a wide variation in individual cases. That is, in some cases, the arbitrators would value players rather differently than the managers who sign free agents.
Third, my last understanding is that the arbitrator has to choose either the player's or team's salary proposal. He cannot "split the difference" or go outside the ranges.
Why does baseball use a system like this? Is three (limited discretion) a factor of one (limited baseball experience)? And why has it worked as well as it has for a long time, despite obvious flaws?
Answer: On your first point: Fangraphs certainly agrees with you that old metrics seem to dominate.  There are no hard and fast rules about which stats are presentable, though; it's solely due to who is hearing the case - and there is no doubt that stats (both old and new) have made a huge difference (see Baseball Prospectus'** article on Arbitration, for example).
A list of what evidence you may present:

The following evidence is admissable:

The quality of the player's contribution to his club during the past season (including but not limited to his overall performance, special qualities of leadership and public appeal).
The length and consistency of his career contribution.
The record of the player's past compensation.
Comparative baseball salaries (the arbitration panel is provided with a table of confidential baseball salaries for all players broken down by years of service).
The existence of any physical or mental defects on the part of the player.
The recent performance of the club, including but not limited to his league standing and attendance.

Second, as to why 'younger' players get less: Players and their agents are only allowed to compare themselves to other players in their service year or players with one year more service time.  As much of the success of the arbitration is due to finding other players with the same stats, this significantly limits the argument that players may have compared to the market-inflated salaries.  The arbitrator basically can only compare the player to other players in arbitration, until they are in their last year of arbitration; so Mike Trout cannot be compared to Albert Pujols, for example, despite the fact that any idiot would sign Trout for more than Pujols at this point.  This can be argued to be waived in the case of 'special' players (see: Trout), but typically it does not yield nearly the 'market' salary nonetheless.
From BP:

In other words, Super Twos can be compared to Super Twos and three-year players, but not four-year players. Threes can be compared to other threes and fours, but not fives. The exception is that fives can compare themselves to anyone, just like free agents.

Further, this likely leads to aggressive signing of young superstar players to pre-arb contracts, like Mike Trout ($24M/year for 6 years); this is because owners want to avoid setting overly large arbitration precedents and schedule when money will be delivered such that it doesn't inflate other salaries.  Trout will earn $24MM a year, but it is back loaded: 5MM in (service) year 3, 15MM in year 4, 19MM in year 5, then 33MM in the last 3 years (service years 6,7,8).  This helps avoid large arbitration comps for other players somewhat.
They certainly do not reflect market salaries would be, even in the final year of arbitration (though they do get closer).  The market salary is effectively the highest amount any one GM thinks a player is worth, and bakes into it not only the past performance of the player, but the likely future performance as well - some years of control over the player, expected growth, and such.  Arbitration salaries do not consider this 'future performance', except as it may be realized in other players' comparative salaries - which, remember, are also arbitration derived until the final year.  In addition, the fact that no teams are bidding 'against' the team and player means that the arbitrators' decision does not include the additional money a player likely would receive from other owners bidding on his talents.

Finally, your third point is correct: the arbitrator must choose one of the two options.  In theory, the arbitrator would compare the midpoint of the two proposed salaries to the determined 'correct' salary and choose the one closest, but as BP notes in the earlier-linked article, that is not set in stone, and they may make their decision based on whatever they choose - which probably depresses extreme salaries some.

As far as your questions at the end: the system works largely because it's a compromise between the players (who would like earlier free agency) and the owners (who would prefer six years of complete control).  It probably benefits the clubs slightly, particularly as it's easy to identify certain players who are likely to receive 'bad' awards (closers in particular seem to get overly high awards - hence trades like the Addison Reed trade in the 2013/14 offseason) and cut them without cost; but it certainly is helpful to players as well compared to what it would be otherwise, and the owners are unlikely to agree to completely open free agency after 3 or 4 years.
Why did it exist? Read the Hardball Times article linked in the other answer; it explains how it came to pass in the 1970s.  Basically, arbitration existed before free agency, after the 1974 strike/lockout; it was the compromise that allowed salaries to have at least some tie to performance (before that, owners set the salary for a player, and a player could play for that salary or not play baseball at all due to the reserve clause).
The reason it is Final Offer Arbitration is because that is common in labor negotiations.  See the wiki on Arbitration:

It is designed to encourage the parties to moderate their initial positions so as to make it more likely they receive a favourable decision.

Without it, both sides likely would make outraegous offers.  Still happens sometimes (see: Eric Gagne) but in general clubs and players are within a million or so in most cases.

** The BP article I linked is from 2012.  In 2013, a major change was made that removed the 'free agent' arbitration option, so that no longer applies.  Clubs now may tender a qualifying contract to FAs (a bit north of $14MM in 2014), which retains their rights to draft pick compensation, but there is no risk of an arbitrator awarding the player more.
Answer: It works very well for the players.  Not sure where you are getting your information from.
A little history:  Owners put it in place, then they were quite surprised when Bruce Sutter was awarded 700,000 dollars.  They quickly traded him and promoted Lee Smith.
To put 700,000 into perspective.  The Yankees sold for $10,000,000 only 7 years prior
History of Arbitration and what it did for Team salaries
The arbiters use what ever stats are put forth by the two parties so only old metrics if that is what is presented.
Arbitration players get their market value.  Greg Maddux got 14.75 million in 2002.
The whole point of one dollar value or the other is so that the two parties work hard to get the deal done without arbitration.
Comment: Your source clearly disagrees with your statement that Arb players get their market value.

How does arbitration work in baseball?


Why is the inverse of a bijective linear transformation defined by the inverse of its matrix?

Question: Let $f$ be a bijective linear transformation. Why does it hold that $A_{f^{-1}} = A^{-1}_f$, where $A_f$ denotes the transformation matrix corresponding to $f$? I can apply the theorem and understand what it says. What I'm looking for is a proof. So far, I understand the following:

A function has an inverse iff it is bijective.
Every linear transformation $f: V \rightarrow W, x \mapsto f(x)$ with arbitrary vector spaces $V$ and $W$ is defined by a transformation matrix $A$ such that $f: V \rightarrow W, x \mapsto Ax$.

I couldn't find a proof in my lecture notes and don't know where to start doing it myself so any help would be appreciated.
Answer: Fix a a basis $B$ of a finite-dimensional vector space $V$. For each linear map $f\colon V\longrightarrow V$, let $A_f$ be the matrix of $f$ with respect to the basis $B$. Then, if $g\colon V\longrightarrow V$ is another linear map, you have$$A_{g\circ f}=A_gA_f\quad\text{and}\quad A_{f\circ g}=A_fA_g.$$So, in particular,$$\operatorname{Id}=A_{f^{-1}\circ f}=A_{f^{-1}}A_f\quad\text{and}\quad \operatorname{Id}=A_{f\circ f^{-1}}=A_fA_{f^{-1}}.$$That is$$A_{f^{-1}}=A_f^{\,-1}.$$
Comment: You shall find a proof [here](https://math.stackexchange.com/questions/1948502/show-that-multiplication-of-matrices-corresponds-to-composition-of-linear-transf).
Comment: Thank you. Why is $A_{g\circ f}=A_gA_f$ and $ A_{f\circ g}=A_fA_g$? I know that $F_{BA}=F_B\circ F_A$ where $F_{BA}:K^n \rightarrow K^m, x \mapsto (BA)x$, but can't derive the former from the latter.


Java - regex - find all matches

Question: I need some help in Java regex.
My text is this abc abc abc xyz xyz xyz.
I need to find all matches which have only one word between abc and xyz
Here there are the two matches that should be returned:

abc abc xyz  ==> an abc is present between abc and xyz
abc xyz xyz  ==> an xyz is present between abc and xyz

My regex pattern:
abc\s+([a-z]*?)\s+xyz

It seems to match only the first match which is abc abc xyz. It does not find abc xyz xyz
What is the right pattern to match all?
Comment: I don't understand your expected matches.  Can you edit your question and show us what you perceive all matches to be?
Comment: I agree with Tim, it's not clear what you expect. If think you're looking for a lot more matches.
Comment: guys, please check it is very clear. actually there are 2 matches
Comment: @TimBiegeleisen, it is updated now.
Comment: as i said just one word
Comment: My answer matches your third regex too anything fault in that?
Comment: How is 'abc abc xyz' one word?
Comment: @BlackMamba, check yours here - https://www.regexplanet.com/advanced/java/index.html - it does not work. BTW, i did not downvote
Comment: @daniu.. what?? man read the question carefully
Comment: Your question still doesn't explain what you want or what you want is not achievable from data you've posted. abc abc abc xyz xyz xyz either produce one group containing  `abc abc xyz xyz` or ` abc abc` Nothing else is possible from this string
Comment: Got you. I reworded your question to make it more clear.
Comment: @KitKarson Do you only want to get the one word in between or the full match? Meaning `abc --- zxc` or just `---` works for you?
Comment: @AhmedAbdelhameed even just finding all in between words ll also do. in this case they are `abc` and `xyz`
Answer: If you just need the one word in between and not the full match as you stated in the comments, you can use a positive Lookbehind and a positive Lookahead, like this:
(?<=abc\s)[a-z]+(?=\sxyz)

Here's a demo.

If you do need the full match or you expect to have multiple spaces before/after the word, you might want to check Andreas's answer.
Comment: *FYI:* This cannot handle multiple spaces between words. It also only returns the word (e.g. `abc`), not the entire match (e.g. `abc abc xyz`), as requested in the question.
Comment: @Andreas I agree with the first point. For the second point, check the comments above.
Comment: You should answer the question. If you answer a comment, you should clarify that in your answer, e.g. with a quote of and/or link to the comment.
Comment: @Andreas Done :)
Answer: Perhaps you need some modifications while matching:
public static void main(String... args) {
    String s = "abc abc abc xyz xyz xyz";
    Pattern pattern = Pattern.compile("(abc\\s+\\w+\\s+xyz)");
    Matcher matcher = pattern.matcher(s);
    while (matcher.find()) {
        System.out.println(matcher.group(1));
        s = s.substring(matcher.start() + 1); // ignore the just-matched and move on;
        matcher = pattern.matcher(s);
    }
}

Output:
abc abc xyz
abc xyz xyz

Answer: Here is a regex that can handle multiple spaces, can tell you where the full match was found, where the words itself was found, and doesn't require resetting the Matcher to continue the search.
String input = "abc  abc  abc  xyz  xyz  xyz";

Pattern p = Pattern.compile("abc(?=(\\s+([a-z]+)\\s+xyz))");
for (Matcher m = p.matcher(input); m.find(); ) {
    String match = m.group() + m.group(1);
    String word = m.group(2);
    System.out.printf("%d-%d: %s%n", m.start(), m.end(1), match);
    System.out.printf("  %d-%d: %s%n", m.start(2), m.end(2), word);
}

Output
5-18: abc  abc  xyz
  10-13: abc
10-23: abc  xyz  xyz
  15-18: xyz

It works by only matching the leading abc directly, then matching the rest in a zero-width positive lookahead, capturing the entire look-ahead match, so the "full" match can be built. This allows the second search result start matching with the word previously matched.
For extra bonus points, it also captured just the word itself.
You can then choose whether you want the full match, or just the word.
Answer: You forgot delimiters and repeating the inner element. Here's an link for online demo
^abc\s+(?:([a-z]*?)\s+)+?xyz$

And making the inner element finder less greedy

Java - regex - find all matches


httpd won't start on boot

Question: I have some problemes with apache on CENTOS...
When I reboot the system, httpd won't start
I have to execut my-self "service httpd start"
chkconfig  httpd --list
httpd           0:off   1:off   2:on    3:on    4:on    5:on    6:off

Any ideas ?
Thank you!
Comment: What run level are you running in?

Based upon that output of `chkconfig` it looks like it should be starting the service if you're in run level 2, 3, 4 or 5.
Answer: Open a terminal window an enter the following:
/etc/init.d/httpd start

This will start apache
then
tail /var/log/httpd/error_log

This will give you the last 10 entries in the apache log. There, you should find the error. Get it and paste it here.
Comment: I got
[notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[notice] Digest: generating secret for digest authentication ...
[notice] Digest: done
[notice] Apache/2.2.3 (CentOS) configured -- resuming normal operations
Comment: He's already stated that he has to execute a `service httpd start` - that has the same effect as /etc/init.d/httpd start.

httpd won't start on boot


Problema com as urls e views dentro do servidor

Question: Estava estudando python e django, e resolvi fazer o site do meu casamento em django. O projeto roda perfeitamente no meu pc local, o problema é quando eu faço o deploy no digital ocean e ele da esse erro aqui.

O admin funciona certinho. O problema é a página principal ou qualquer outra pagina que eu tento acessar do meu site.
Meu urls.py principal:
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [ url(r'^admin/', admin.site.urls),
                url(r'', include('casamento.urls'))] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urls.py do app casamento:
from django.conf.urls import include, url
from . import views

urlpatterns = [
    url(r'^$', views.tela_inicial),
    url(r'^local', views.local_casamento),
    url(r'^listapresentes', views.listapresentes),
    url(r'^presenca', views.presenca),
]

Já procurei esse erro no google e nenhuma das soluções funcionaram :(
Comment: Vocês está usando Nginx? E qual a linha de comando que você usa pra iniciar sua app, ex.: `./manage.py runserver 0.0.0.0:8000`
Comment: Consegui resolver o problema. Era a versão do django. Estava usando a versão 1.10 que vem como padrão pip install django. instalei a versão 1.9 e funcionou. Muito obrigado pela ajuda.
Comment: Recomendo você postar uma resposta a sua própria pergunta, de forma a ajudar outras pessoas que possam encontrar o mesmo problema. Você pode fazer isso quando tiver 15 ou mais pontos de reputação.
Answer: Consegui resolver o problema. Era a versão do django. Estava usando a versão 1.10 que vem como padrão pip install django. instalei a versão 1.9 e funcionou. Muito obrigado pela ajuda.


What is meant by a "multi-forest environment"?

Question: In my continuing adventures with LDAP, I keep coming across the phrase "multi-forest environment".
Whilst I'm pretty certain it doesn't apply to me, I'm very curious to know what it means.
Answer: In short, it means that you have two or more forests that need to interact.  It implies that you are either using Trusts between the forests, setting up Federated Services, or manually inputting your credentials for every single connection.
In my experience, this comes about in one of three ways:
-Your company has acquired or been acquired by another company (and have yet to merge them), or
-You have a Prod and Test environments that you really do want completely separated, or
-The person filling the Architect role in your company doesn't know that you can have more than one domain per forest.
Comment: +1 for the last point
Comment: Yea...  Walk into a place with 12 forests and 12 domains.  Ask "why".  Prepare to be stunned.
Answer: LDAP functional integration gets looser as you go from domain -> forest -> multiple forest levels of trust. Within a domain everything by default is trusted (but possibly not authorized), within a forest transitive trusts allow all member domains to have visibility and to trust objects in other member domains while keeping things like replication traffic and administrative boundaries under control.
Domains that have a close organisational relationship but that need to be kept distinct for any reason belong to a forest in order to simplify large scale administration\organisation. So you might have production.acme.com, test.acme.com, Tokyo.acme.com etc. as separate domains in a single forest. You will have a consistent name space, and schema and (in general) easy mechanisms for accessing or providing access to objects across domains because, by default, you have transitive trusts between all domains within a Forest.
If your organisational structure requires that certain domains have a different schema, or you require that multiple IT groups need direct ownership of their directory services, or you have a need to have more complete administrative separation between some domains then you need a multi-forest design with some trusts between the forests (or possibly just between specified domains).
The above is based on Active Directory but the same principles should apply to any LDAP environment.


Behrens–Fisher problem on Wikipedia

Question: In the opinions of the denizens of this forum, how good is this article?
It makes a big point of the unsolved mathematical problem, and says little about the fact that just which math problem is to be solved may be philosophically controversial.  It does say "One difficulty with discussing the Behrens–Fisher problem and proposed solutions, is that there are many different interpretations of what is meant by 'the Behrens–Fisher problem'."  But it doesn't say that the "different interpretations" are philosophical points of view on the question of which math problem should model it, rather than different interpretations of whether it's the problem of inference about the difference between the means of normally distributed populations with possibly different variances.
Comment: There looks like an interesting question here, but "how good is this article" isn't it, because it's too vague and subjective. Could you please reformulate your query?
Answer: It seems like the truncated citation censored the relevant part:

These differences involve not only what is counted as being a relevant solution, but even the basic statement of the context being considered.

Different approaches have been employed to solve this problem, and they seem to had been discussed in one your questions. A simple an important difference appears by comparing the classical and the Bayesian formulation of the problem since, from a Bayesian perspective, point hypothesis are not of interest given that the probability of any point is zero for continuous random variables (this also applies to $P(\mu_1=\mu_2\vert \text{data})=0$). This implies a different formulation of the problem for each framework.
The references in the wikipedia article are too selective (there is an immense amount of literature on this topic) and they are not up to date. However, I think it represents a good starting point (which might be closer to the spirit of wikipedia, since it does not aim to be an exhaustive reference).

Behrens–Fisher problem on Wikipedia


Can I specify Node.js command line options in AWS Lambda?

Question: I'm using AWS SAM and running against Node 10.x.
Would love to pass in the flags for experimental modules and top level await.
Thanks!
Comment: I am interested in this too now. AWS Lambda is getting more proactive at supporting the latest versions of Node.js and being able to use "Harmony" flags at some point would be useful. Especially with Optional Chaining and Nullish Coalescing now supported Node 13 and Node 14 with --harmony-optional-chaining and --harmony-nullish.
Answer: You can add Node.js command line options to lambda by setting the NODE_OPTIONS environment variable.
https://nodejs.org/api/cli.html#cli_node_options_options
Comment: I tried doing this in template.yaml file, It didn't work for me.

`Type: AWS::Serverless::Function
    Properties:
      CodeUri: functions/stock-checker/
      Handler: app.lambdaHandler
      Runtime: nodejs12.x
      Environment:
        Variables:
          NODE_OPTIONS: "--experimental-modules"`


Rearrange regression equation that includes a dummy variable

Question: This is my regression equation:
$10 = 5.44 + 0.26X_1 - 3.19X_2$
$X_2$ is a dummy predictor with two levels. Assume that the value of $X_2$ is 1 therefore regression equation is:
$10 = 5.44 + 0.26X_1 - 3.19$
How can I rearrange the equation to find $X_1$? This isn't homework, it's my own data collected as a hobby.
Comment: Are you solving for $X1_i$ for a given point $Y_i$ and $X2_i$?
Comment: How come the "dependent variable" is a fixed number, $10$?
Comment: Dependent variable isn't fixed, it's just the value of $Y$ for which I want to know the value of $X_1$
Answer: The thing with an equation is that at each step you do things that preserve the equality*
* (loosely expressed as "do the same thing to both sides" - which is accurate if you don't do things that remove solutions nor add solutions that don't solve the original). For example, you can add some number to both sides.
$ 5.44 + 0.26X_1 - 3.19=10$
... now  add or subtract the same numbers on both sides to isolate $X_1$:
$ 5.44 - 5.44 + 0.26X_1 - 3.19=10-5.44$  gives
$0.26X_1 - 3.19=10-5.44$
$0.26X_1 - 3.19+3.19=10-5.44+3.19$
$0.26X_1=10-5.44+3.19$ ... now divide both sides by the same (non-zero) quantity
$0.26X_1/0.26=(10-5.44+3.19)/0.26$
$X_1=(10-5.44+3.19)/0.26 = 29.80769$
You can do similar manipulations when $X_2$ takes a different value. Or you can keep $X_2$ just as $X_2$ until after it has been rearranged to make $X_1$ the subject.


Drawing random vectors from multivariate normal distribution with limited deviation

Question: In the one-dimensional case it is easy to obtain random numbers that are not too far away from the mean by checking if they are within one or two standard deviations. Is there some similar way to obtain random numbers that are not to far away from the mean vector of a multivariate normal distribution?
Thank you very much
Comment: Draw vectors from this multivariate normal as you usually would, and then check the Mahalanobis distance.
Comment: What software are you using?
Answer: The Mahalanobis distance is the natural distance measure as Max said. But maybe you are really interested in a more general question that doesn't have a unique answer.  The similar sounding question is "In one dimension outliers are defined by being much larger or smaller than the bulk of the distribution that the data was drawn from.  For multivariate data how are outliers defined."  One answer is to define a distance and say that outlier are observations with large distances.  But the distance function should depend on the shape of the multivariate distribution.  So there are many distance functions that can be defined. In more that one dimension there are other ways to look at outliers.  One way is in terms of using the data for inference.  Outliers adversely effect parameter estimates but in different ways depending on what parameter we are interested in.  Each parameter has a functional defined which is called the influence function.  It measures how points in the multidimensional space can chnage the estimate when comapring including the point versus leaving it out.  Outliers can be defined in terms of the magnitude of their influence on the parameter.  In two dimensions the pearson correlation has contours of constant influence determined by hyperbolae. So as you move out in teo dimensions along these hyperbolae you increase the influence of the pointand do it most rapidly.  So an outlier with respect to correlation can be defined as any point beyond a hyperbolic contour that is considered to have high influence.  Other parameters would have different contours and hence a different definition for the outlier.


Adjusting P-values in ANOVA

Question: I am working with an experiment on several genes (#41350) based on two factors: Lcells (levels: "pos", "neg"), microbe(levels: "CR", "GF"). I have implemented ANOVA test (aov) for each individual gene separately comparing Lcells*microbe. The result is different p-values of Lcells, microbe and the interaction for each individual gene (a matrix of 41350*3). Now, how should I adjust p-values? What is the vector I should feed into p.adjust()? Shall I adjust all Lcells p-values of all genes together, then microbe p-values of all genes separately and ...?
Thanks for your help!
Answer: What you suggest is what is usually done. You typically adjust all the p-values for each factor and their interaction separately.
I do not know what test you are using, but for example, this method is what is used inherently in the functionality of the limma package from the Bioconductor project.
Comment: Is your aim to validate the findings, also? If so, the top n genes are still the ones that you would like to use for validation, because FDR does not change the ranking of the genes. In addition, not having any significant p-values left does not (necessarily) mean that you do not have any differences between the conditions, you just have a low power to detect these differences.
Comment: but that's strange, since before adjusting p-values, for each individual factor I have more than 1500 significants. but after adjusting no significant p-value would remain?!
Comment: Well, this often happens, especially if the conditions you are comparing are biologically only slightly different, or if you have a low number of replicates.
Comment: What method of adjustment are you using?
Comment: I am using 'fdr' method
Comment: ANd I should say that yes I have low number of replicates. only 3 replicates!
Comment: Depending on the test that you are using, you might consider filtering your data set using e.g. standard deviation of low expression before running the tests and adjusting the p-values. That is, if haven't already. This typically leaves you with more DEG genes.

Adjusting P-values in ANOVA


Inequality in number theory

Question: Prove that:
(i)$5<5^{\frac{1}{2}}+5^{\frac{1}{3}}+5^{\frac{1}{4}}$
(ii)$8>8^{\frac{1}{2}}+8^{\frac{1}{3}}+8^{\frac{1}{4}}$
(iii)$n>n^{\frac{1}{2}}+n^{\frac{1}{3}}+n^{\frac{1}{4}}$ for all integer $n\geq9$
Can raising both sides to exponent $12$ help
Answer: (i) $5<2.2+1.7+1.4<5^{1/2}+5^{1/3}+5^{1/4}$.
(ii) $8>2.9+2+1.7>8^{1/2}+8^{1/3}+8^{1/4}$.
(iii) $n\ge3\sqrt n>n^{1/2}+n^{1/3}+n^{1/4}$ because $n \ge 9$.
Answer: The last one is equivalent to showing
$$1 > \frac{1}{n^{\frac{1}{2}}}+\frac{1}{n^{\frac{2}{3}}}+\frac{1}{n^{\frac{3}{4}}}$$
and
$$n\geq 9 \Rightarrow \frac{1}{3}\geq \frac{1}{n^{\frac{1}{2}}}$$
$$n^2\geq 9^2 > 3^3 \Rightarrow \frac{1}{3}> \frac{1}{n^{\frac{2}{3}}}$$
$$n^3\geq 9^3 > 3^4 \Rightarrow \frac{1}{3}> \frac{1}{n^{\frac{3}{4}}}$$
and the result follows.
Answer: HINT: For (ii) we have to prove that
$$6>2\sqrt{2}+\sqrt[4]{8}$$
This can be written as
$$6-2\sqrt{2}>\sqrt[4]{8}$$
Raise to the power $4$
we have
$$3080>2112\sqrt{2}$$
Squaring we get
$$565312>0$$
For (i) we get by $$AM-GM$$
$$\frac{5^{1/2}+5^{1/3}+5^{1/4}}{3}\geq \sqrt[3]{5^{13/12}}$$ so we have to Show that
$$3\sqrt[3]{5^{13/12}}>5$$ this is equivalent to $$27^{12}>5^{23}$$ and this is
$$150094635296999121>11920928955078125$$

Inequality in number theory


Broken modules are not rolled back

Question: I try to develop a D8 module with entities. A lot of them ^^. But there is an issue with the way D8 handles the creation of tables during the installation process. If the definition of the entities is not correct D8 can't create the table. But the module is enabled anyway.
Now D8 is not able to uninstall the module. I have tried drush pm-uninstall, drush cr, drush dre on the module. The uninstall process fails every time because D8 cant find the table and is obviously not aware of the failed installation of the module.
The only way I figured out was to create the tables with the primary key and then to uninstall the module. That works, but is very time consuming. How can I force uninstall my module even if the corresponding tables doesn't exist? And why is D8 ignoring the fact that the module was not installed correctly in the first place?
Answer: This is a known bug: https://www.drupal.org/node/2563515
As a workaround, remove the entity type definition (e.g. by removing the @ so it doesn't parse it as an annotation), clear cache, then uninstall.
Comment: Is there no way for Drupal Core to recognize the failed installation and then perform a rollback rather then enabling a broken module and (in worst case) make the whole site unaccessable?
Comment: Recognize maybe, rollback is almost impossible. Mysql doesn't support transactions for things like created tables, so you can't reliably roll that back. And changes might have been made that outside of the database as well that can't be tracked.
Comment: If you have a hook_entity_type_alter() in your module you may have to disable that (such as by changing the function name to not trigger the hook) before uninstall will work.
Answer: You can uninstall the module from database from config.extension and remove blob there.
I know that is very silly but till now we have this resolution.

Broken modules are not rolled back


Jquery .after() add image

Question: I'm running a small website. I have an ajax shoutbox.
I have 3 different user class on my website, and on the shoutbox they have a different colors so people know whos who.
I made a supporter class too but thats not an user class, I can select if the user a supporter by checking a radio button yes or no.
And I would like to if the radio is checked yes a small image would appear after the users name.
With php I made it like this for just a test:
if(isset($GLOBALS['user']['supporter'])) {
 $support = 'the image here';
}

My question is: is it possible to make this in jquery?
For like:
if($('global here') == 'supporter') {
  $('class here').after('the image');
}

Can some one please give me a hint?
Comment: your can use  `.after(');`
Comment: yes i know that, my problem is how can i make a global vairablie in jquery like in php
Comment: in javascript global variable is not prefaced with 'var' while local variable is. HOWEVER I strongly reccomend that you do NOT use global variables in either programming language as it's bad practice.
Comment: sorry i don't know PHP but it is simply javascript you can make `js` and link to HTML thus it would be globaly. and as @kissmyface said your can make `var global_` something different that local have not at most.
Answer: Well first you would need to get the value of your checked radio.
supporter = $('#radioButton:checked').val();

Then just execute the code as you have written it assuming that the value of the yes checkbox is '1'...
if($(supporter == '1')) {
  $('.myClass').after('your markup');
}

Is this what you are looking for?
Comment: works like a charm, thanks for your help and thank you for spending time on me
Comment: No problem, but do look into not using global variables (a.k.a Scope Abuse) you'll have a much better time :-)
Answer: Yes of course you could do:
<input type='radio' name='supporter' value='1'>Yes
<input type='radio' name='supporter' value='2'>No

$('input[name=supporter]').change(function(){
    var value = $(this).val();
    if (value == 1){
         $('#support').show();
    }else{
         $('#support').hide();
    }

});

Jquery .after() add image


How to add to cart or wishlist without Logged in

Question: I want to add  a product to my cart But for that i want to logged in the user.Means after he logged in only he can see his cart. But after logged in if he sees the cart, he should see the the product just he added to cart but he saw the old one.Though I put the url on session in controller.How do i make it correct?
Here is show Login form :
     public function showLoginForm()
        {
            Session::put('url.intended',\URL::previous());
            return view('cart.login');
        }

Add to Cart controller :
public function addCart(Request $request)
    {
        if(Auth::check())
        {
        $name = $request->name;
        $product = Product::where('name' , '=', $name)->first();
        $product_id = $product->id;
        $product = DB::table('carts')
                ->where('carts.product_id','=',$product_id)
                ->where('carts.status','=',1)
                ->select('carts.product_id')
                ->first();

        if(!$product){
            $cart = new Cart();
            $checkBox = Input::get('additionals');
            if (is_array($checkBox)){
            $cart->additionals = array_sum($checkBox);
        }
        else {
            $cart->additionals =0;
        }
            $cart->user_id =Auth::user()->id;
            $name = $request->name;
            $product = Product::where('name' , '=', $name)->first();
            $cart->product_id = $product->id;
//          $product = Product::find($cart->product_id);
            $cart->price =$product->price;
            $cart->status = 1;
            $cart->save();
            return redirect('shop-cart');
        }
        else {
            return redirect('shop-cart');
            }
        }

        else{
            return redirect('/login');
        }
    }

And Login controller :
protected function login(Request $request)
    {
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (auth()->attempt(array('email' => $request->input('email'),
             'password' => $request->input('password'))))
        {
            if(auth()->user()->is_activated == '0'){
                 Auth::logout();
                return back()->with('warning',"First please active your account.");
            }

            else{
                return Redirect::to(Session::get('url.intended'));

            }

        }
        else{
            return back()->with('error','your username and password are wrong.');
        }
    }

Add to Cart Route:
 Route::get('add-to-cart/{name}','CartController@addCart');

Answer: public function addcart(Request $request)
{
    $id=$request->id; $time=60*24*14; /*60 * 24 * 14 = 14 drays 60=minutes 24=hours 14=days*/
    $value=0;
    if( Cookie::get('cart')!==null ){
        $anonim=Cookie::get('cart');
        DB::table("cart")->insert(["anonim"=>$anonim,"product_id"=>$id]);
        return 0;
    }else{
        $value=DB::table("cart")->max("anonim")+1;
        if(empty($value)){
            $value=0;
        }
        DB::table("cart")->insert(["anonim"=>$value,"product_id"=>$id]);
        $cookie = cookie('cart', $value, $time);
        return response()->cookie($cookie);
    }

}


Creating custom CSS for a book

Question: Using Drupal 7 and creating a number of books with the Books module. They each have their own specific design, so specific CSS needed per book. I know I could create specific content types for each book but I think that would become unmanageable as the number of books grow.
We are using the Code Per Node module, we could make use of the Context module to detect which book it is, and then insert a block somewhere on the page with some associated CSS. In theory that would work but is there a better way to do this?
Answer: In Drupal 7, you can add a CSS class to the  tag for your book. For nodes, you have the class added by default. For example page-node-2056, for the /node/2056 path.
For Book nodes, you might add the book ID inside your template.php theme file, in the theme_preprocess_html function:
function MYTHEME_preprocess_html(&$vars) {
  // If on an individual node page, add the book ID to body classes.
  if ($node = menu_get_object()) {
    if (isset($node->book['bid'])) {
      $vars['classes_array'][] = drupal_html_class('book-id-' . $node->book['bid']);
    }
  }
}

You can then take the ID for each book and add all the style definitions in a single CSS file. Something like the following:
.book-id-xxx {
  /* Style for book xxx. */
}
.book-id-yyy {
  /* Syle for book yyy. */
}
... and so on

Would it make sense for what you need?
Comment: @pingin, you are completely right! I assumed the book ID was added too. I have just updated my answer explaining how you can add the book ID to the body classes. I hope it can be useful.
Comment: I would just add another class 'book' as well so as to target CSS used for all books.
Comment: Maybe I misunderstood but I don't think it adds the ID for the book but for the node — so if you had a book with 500 pages, you'd need 500 selectors (per rule). It would be very hard to maintain…
Comment: @dinopmi — brilliant, that's exactly what I need! Solves my problem perfectly. Many thanks.

Creating custom CSS for a book


Solve the exponential equation

Question: Find the number of roots to $e^x = ax^2$ for all values of $a$. (x is real and so is $a$). I have tried some things but I am stuck.
Comment: Why don't you tell us what you have tried?
Comment: @Henrik just basic things like applying log on each side but I dont get anywhere.
Comment: These sort of equations are in general hard to solve. Often there isn't a closed form of the solution.
A possible numerical strategy is to assume that one solution is close to 1. So you can expand $e^{x}$ in a Taylor series around 0. $e^{x} \approx 1+x+0.5x^2$.
Comment: One thing that should be clear is that for $a \leq 0$, there are no roots. So you can at least focus on the case of $a>0$.
Comment: Easy enough with calculus, since they just want a count of the solutions $x.$ Without calculus, no.
Comment: See [the technique](http://math.stackexchange.com/questions/571398/exact-solution-for-logarithmic-equation/571431#571431).
Answer: For $a>0$ the roots can be expressed in terms of Lambert $W$ function:
\begin{align}
a x^2&=\exp(x) \\
x^2\exp(-x)&=\frac{1}{a} \\
x\exp(-\frac{x}{2})&=\pm\frac{1}{\sqrt{a}} \\
-\frac{x}{2}\exp(-\frac{x}{2})&=\mp\frac{1}{2\sqrt{a}} \\
-\frac{x}{2}&=\mathrm{W}\left( \mp\frac{1}{2\sqrt{a}} \right)\\
x&=-2\mathrm{W}\left( \mp\frac{1}{2\sqrt{a}} \right)
\end{align}
So, $\forall a>0$ there is always one negative real root
$x_1=-2\mathrm{W_0}\left(\frac{1}{2\sqrt{a}} \right)$.
And since the Lambert $W(u)$ function has two real branches
for $-\exp(-1)<u<0$, it would be two more (positive) real roots (three total):
\begin{align}
x_2&=-2\mathrm{W_0}\left(-\frac{1}{2\sqrt{a}} \right), \\
x_3&=-2\mathrm{W_{-1}}\left(-\frac{1}{2\sqrt{a}} \right)
\end{align}
for $a>\exp(2)/4$.
Also, when $a=\exp(2)/4$ then $x_2=x_3$ and there are two real roots total.
Summarizing, the number $n$ of real roots to $\exp(x) = a x^2$:
\begin{align}
n&=
\begin{cases}
0,\quad a\le0 \\
1,\quad 0<a<\exp(2)/4 \\
2,\quad a=\exp(2)/4 \\
3,\quad a>\exp(2)/4 \\
\end{cases}.
\end{align}
Comment: +1, but you left out the answer for $a\le 0$ and $0<a\le exp(2)/4$. I know these are obvious, but they should be stated.
Comment: @Rory Daulton: Thanks, summary added.
Answer: I am guessing you are looking for the roots over the whole real line. Note that
$f(x)=e^x-ax^2$ is a continuous function on its domain but more importantly that the domain is a connected set. Does it sound like  Intermediate value theorem?

Solve the exponential equation


Kähler differential and higher derivations (geometric interpretation of diagonal here)

Question: I am studing Kähler differentials and I tried to understand the geometric motivation behind these settings. What I do not understand is the role which plays the diagonal in all these theory. The cotangent sheaf is later defined in terms of the diagonal map. Why is this geometrically interesting? I tried to write a short introduction to Kähler differential to make the geometric nature more available, but I do not now if it make sense. Here it is:

Differential $ 1 $-forms are linear transformations $ \omega_{p}:T_p X\mapsto K $  assigning an element in $ K $ to a tangent vector of the tangent space $ T_p X $ of a point $ p\in X $ in some differential manifold $ X $. Differential $ 1 $-forms can be viewed as \textit{infinitesimal} direction vectors $ \triangle p $. This means in physical terms, that the scalar $ \omega_p(\triangle t)\in K $ with $ \triangle t $ a tangent vector represents the \textit{work} required to move from $ x_i $ to $ x_{i+1} $ with $ p\in (x_i,x_{i+1}) $ along some curve. In other words, differential forms are cotangent vectors over some field $ K $, which give information about the work which is locally required to move along some curve. However, they can be generalized and captured by sheaf theory. For this attempt, we observe first that $ \triangle p $ is related to Taylor expansions. Indeed, let $ f $ be a smooth function, that is $ f\in C^{\infty}(\mathbb{C}) $, on a differential manifold $ X$ and let $\mathfrak{J}$ be the ideal of smooth functions vanishing at the point $p\in X$. The zero order part of the Taylor series of a smooth function $f$ is the value of $f$ at the point $ p $, let us say, $ f(p)=c $, so that $ f-c\in\mathfrak{J}$. Now the first order derivatives of $f-c$ correspond to the first order terms in the Taylor series and these are given by the image of $f$ in $\mathfrak{J}/\mathfrak{J}^2$. Let us denote this map by $ d(f) $ with $ d: \mathcal{O}_X\rightarrow \mathfrak{J}/\mathfrak{J}^2 $ and where $ \mathcal{O}_X $ denotes the ring of smooth functions on $ X $. Moreover, if $ f $ is constant, this means a fixed vector, then $ d(f)=0 $. Another important input is that $ \triangle p$ is required to be non zero, as there is no direction available for the zero vector. But $ \triangle p=0 $ is satisfied if and only if the two endpoints of the tangent vector $ \triangle p $ are choosen to be the same, which happens if and only if the point $ p\in X $ correspond to an element on the diagonal of $ X\times X $. So we demand that we just consider elements in $ X\times X $ vanishing on the diagonal (or in the complement of the diagonal).

Summarizing up, my two questions are the following:
1) which geoemtric interpretation have the diagonal in these context?
2) Higher derivations seemed to me a generalization of Kähler differentials, but what is their motivation or geometric nature (analogy to differential geometry), since I cannot see any connection between Kähler differentials and higher derivations ?
Answer: This is an old question, but the question may have interest for others on this site.
Question 1. "Which geometric interpretation have the diagonal in these context?"
Answer. If $\phi:A \rightarrow B$ is a map of commutative rings and $I:=ker(m) \subseteq B\otimes_A B$ is the ideal of the diagonal, we get a closed immersion
D1. $\Delta:X:=Spec(B) \rightarrow Spec(B\otimes_A B):=X\times_S X.$
The sheafication $\Omega:=\Omega^1_{X/S}$ of the module of Kahler differentials $\Omega^1_{B/A}$ is a sheaf of $\mathcal{O}_{X\times_S X}$-modules with support on $\Delta(X)$. The two projection maps $p,q:X\times_S X\rightarrow X$ induce a left and right $\mathcal{O}_X$-module structure on $\Omega$, hence $\Omega$ is a sheaf of left and right $\mathcal{O}_X$-modules with the property that $a(\omega b)=(a\omega)b$ for all local setions $a,b,\omega$. The following formula holds:
D2. $a\omega = \omega a.$
hence the left and right structure coincide. There is an isomorphism of $B$-modules
D3.  $Hom_B(\Omega^1_{B/A},B) \cong Der_A(B)$
where $Der_A(B)$ is the set of $A$-linear maps $\delta:B\rightarrow B$ with $\delta(ab)=a\delta(b)+\delta(a)b$. At the level of sheaves you get an ismorphism
D4. $\Omega^* \cong \Theta_{X/S}$
hence the dual of the module of Kahler differentials is the "tangent bundle" $\Theta_{X/S}$.
Let $k\subseteq A$ be a map of commutative unital rings. A "higher derivation of $A/k$" is constructed as follows: Let $B:=A[t]/(t^{n+1})$
and let $D:A \rightarrow B$ be a map of $k$-algebras. It follows
D5. $D(a)=\sum_{i\geq 0}D_i(A)t^i$
where $D_i:A \rightarrow A$ are $k$-linear maps and
$D_k(ab)=\sum_{i+j=k}D_i(a)D_j(b)$. The map
D6. $D_1: A\rightarrow A$
is a derivation, but the other maps $D_i$ are not. See Matsumura's book "Commutative ring theory" for some applications to the study of local rings.
Question: "Higher derivations seemed to me a generalization of Kähler differentials, but what is their motivation or geometric nature (analogy to differential geometry), since I cannot see any connection between Kähler differentials and higher derivations?"
Answer: If $k$ is a field of characteristic zero it follows for any derivation $\delta \in Der_k(A)$ we get a higher derivation $D^n(\delta)$
$$D^n(\delta)\left(\sum_{i=0}^n a_it^i\right):=\sum_{i\geq 0}\frac{1}{i!}\delta^i(a_i)t^i$$
where $\delta^i:=\delta \circ \cdots \circ \delta.$ This construction and it's relation to smoothness is studied in Matsumura's book Chapter 27.
They also go under the name "Hasse-Schmidt derivations". In some cases (over a field of charateristic zero) they are related to the notion "flat connection".
You may find some results on this on the arXiv preprint server.
Answer: I believe that you are interested to the algebraic geometry setting: if yes then I suggest you Vakil's FOAG (available at http://math.stanford.edu/~vakil/216blog/FOAGdec2915public.pdf); exactly the chapters 12 (sections 1, 2, 3 and 6) and 21 (sections from 1 to 5).


Duvida sobre JPQL

Question: sinceramente tenho uma certa dificuldade com BD, e preciso de uma JPQL que retorne apenas um registro. Tenho uma entidade Preço e uma entidade Produto. Preciso trazer o ultimo preço cadastrado pelo usuário. Coloquei uma data e um ID, imagino que poderia ser o ultimo ID ou mesmo a ultima data cadastrada (tenho uma dataLancamento). Mas como faço isso ? Meu BD é o MYSQL e estou usando Hibernate,CDI e JSF.
Tabela preço:
id | dataLancamento | valor | .... produto_id |
public Preco findByIdProdutoUltimoPreco(Integer produtoId) {
    TypedQuery<Preco> query = em.createQuery(
            "????",
            Preco.class);
    query.setParameter("pid", produtoId);
    return query.getSingleResult();
}

Answer: Para saber o ultimo registro baseado no id e no parâmetro, bastaria usar:

ORDER BY id DESC: ordenar registros em ordem decrescente baseado no id
LIMIT 1: limitar para que retorne somente 1 registro:
WHERE produto_id = :pid: retornar registros com o produto específico

Então sua query ficaria desta forma:
SELECT id, dataLancamento, valor, produto_id FROM nameTable
WHERE produto_id = produtoId ORDER BY id DESC limit 1

Adaptando no seu código ficaria desta forma:
public Preco findByIdProdutoUltimoPreco(Integer produtoId) {
    TypedQuery<Preco> query = em.createQuery(
            "SELECT id, dataLancamento, valor, produto_id FROM nameTable
    WHERE produto_id = :pid ORDER BY id DESC limit 1",
            Preco.class);
    query.setParameter("pid", produtoId);
    return query.getSingleResult();
}

Duvida sobre JPQL


Script that open an url then close the browser

Question: I'm writing a PowerShell script that need to do the following task :

Open an url then close the windows that got open

Start-Process -FilePath msedge http://127.0.0.1:62354/now
Start-Sleep -Seconds 1
get-process msedge | %{ $_.closemainwindow() }

I'm facing 2 issues :
-First one : is I actually force to open the url with Edge so I could close it without any issue for knowing what default browser the user may use.
-Second one : When I close the window it's actually close all Edge process instead of the one that just got open which is troublesome since user may also use this browser to work on webapp
The first one would not be an issue if I could solve the second issue honestly
Hope you guys can help me
Comment: Why do you want to do this?
Comment: @Julia I use a solution to do an inventory for my asset in my internship and I need to deploy agent on every asset then force the agent to contact the main server with the url http://127.0.0.1:62354/now and since I don't want to bother user with a browser that open and make them close it  , I would like to close it with the script. The solution is GLPI if you happen to know it
Comment: Do you have to use MS Edge? Probably you could try a "chrome.sessions".
Comment: @harper Hi , no I don't need to use Edge but since I was sure it was by default on each asset , I said to myselft instead of check every default browser let's just use Edge instead , how should i use chrome.sessions then?
Answer: Think about it like this, when you open internet explorer, edge or chrome and browse to a URL, it sends an HTTP GET to the URL, which responds with an html file.  It then does a GET for each script and file embedded on the page.
All you want to do is load this page for a second so you can register it on some server.
With that in mind, you don't really need to browse to this webpage, you could just send a webrequest instead.
Try this instead!
Invoke-WebRequest http://127.0.0.1:62354/now

Comment: A huge thanks for your answer , not only you gave the solution but you explained the reason behind it. thanks a lot.  NB: I tried it and worked fine for me


Help with proof by induction problem

Question: Any input on this problem I'm working on?
I want to prove by induction that for all natural $n$ we have that
$\sum_{i=1}^n -1^jj^2 = (-1)^n\frac{n(n+1)}{2}$
So far I have:
1) Proved the base case, n = 1, which gives me:
$\sum_{i=1}^n -1^jj^2 = (-1)\frac{2}{2}$
$\rightarrow\sum_{i=1}^n -1^jj^2 = -1$
Which makes sense.
2) For the induction step, I assume n = k is true, I get:
$\sum_{i=1}^n -1^jj^2 = (-1)^k\frac{k(k+1)}{2}$
Then I want to find out if this is true for n = k+1. I insert for k+1.
$\sum_{i=1}^n -1^jj^2 = (-1)^k+1\frac{k+1((k+1)+1)}{2}$
I know you guys usually ask for me making an effort at it, but I am literally stuck, and have been so for some time. Any tips?
BTW I have read this guide, which was a good read, but didn't really help me figuring out how to solve these. Please share other links if you have any.
Comment: Possible duplicate of [Sum of alternating sign squares of integers stuck with proof by induction](http://math.stackexchange.com/questions/411302/sum-of-alternating-sign-squares-of-integers-stuck-with-proof-by-induction)
Comment: Please post your problem here with appropriate formatting in MathJax (tutorial: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) instead of linking to an image of the problem.
Comment: Split into 2 cases: n odd , n even.
Answer: Hint:
$$\sum_{j=1}^{k+1}(-1)^j j^2 = \left[\sum_{j=1}^{k}(-1)^j j^2\right] + (-1)^{k+1}(k+1)^2.$$
Now you can use the assumption on the bracketed term.
You may need to consider even and odd $k$ separately.
(Note:  I'm not sure $-1^k$ and $(-1)^k$ are the same thing.  The second one makes it clear what you mean.)
Answer: Here you are,
Assume:
$\sum_{i=1}^k -1^jj^2 = (-1)^k\frac{k(k+1)}{2}$
Using the hypothesis show that:
$\sum_{i=1}^{k+1} -1^jj^2 = (-1)^{k+1}\frac{k+1((k+1)+1)}{2}$
the part you are missing:
$\sum_{i=1}^{k+1} -1^jj^2 = (\sum_{i=1}^{k} -1^jj^2) + (-1)^{k+1}(k+1)^2$
Now substitute based on the inductive hypothesis.  Apply your algebra skills and take it home.
Answer: $$\sum_{j=1}^{k+1}(-1)^j j^2=(-1)^{k+1}(k+1)^2+\sum_{j=1}^{k}(-1)^j j^2=(-1)^{k+1}(k+1)^2+(-1)^k\frac{k(k+1)}{2}$$
therefore
$$\sum_{j=1}^{k+1}(-1)^j j^2=(-1)^{k+1}\left((k+1)^2-\frac{k(k+1)}{2}\right)$$
$$\qquad=(-1)^{k+1}\frac{(k+1)(k+2)}{2}$$
Answer: When dealing with induction proofs, the usual strategy is to try to find some way to reduce the expression we get when inserting $n=k+1$ to the expression when $n=k$ so we can apply the assertion given by the inductive step and then work from there.
If the expression in question is a sum (as it is the case) it is straightforward to to just that, as we can pop the last term of the summation to get the expression when $n=k$.
Thus:
$$
\sum_{i=1}^{k+1} (-1)^jj^2 = (-1)^{k+1}(k+1)^2 + \sum_{i=1}^{k} -1^jj^2= (-1)^{k+1}(k+1)^2 + (-1)^k\frac{k(k+1)}{2}
$$
Now it is a matter of applying algebra.

Help with proof by induction problem


Não apanha id no full calendar?

Question: Eu tenho um código bem estruturado do fullcalendar onde eu consigo fazer tudo menos uma coisa. Quando carrego no event, eu queria que ele apagasse e removesse do calendario. Ele apaga da base de dados mas não remove do calendário.
Isto é o código que tenho
events: [
                <?php
                $data = date("yy-mm-dd");
                $select=mysqli_query($db, "SELECT * from aulas");
                while($mos=mysqli_fetch_assoc($select)){
                    $id_cat=$mos['id_categoria'];
                    $sel_cat=mysqli_query($db, "SELECT * from categorias where id = '$id_cat'");
                    $mos_cat=mysqli_fetch_assoc($sel_cat);
                    $titulo=$mos_cat['nome'];
                ?>
                {
                    title: '<?=$titulo; ?>',
                    color: '<?=$mos_cat['cor']; ?>',
                    start: '<?=$mos["data"]; ?>T<?=$mos["inicio"]; ?>',
                    ini_hour: '<?=$mos["inicio"]; ?>',
                    id: '<?=$mos["id"]; ?>',
                    fin_hour: '<?=$mos["fim"]; ?>',
                    end: '<?=$mos["data"]; ?>T<?=$mos["fim"]; ?>',
                },
                <?php } ?>
            ],

Como podem ver, eu defino ali o id e tudo é apresentado corretamente.
eventClick: function(event, delta, revertFunc) {
    swal({
          title: "Deseja apagar este evento?",
          text: event.title,
          type: "warning",
          showCancelButton: true,
          confirmButtonClass: "btn-danger",
          confirmButtonText: "Apagar",
          cancelButtonText: "Cancelar",
          closeOnConfirm: true,
          closeOnCancel: true
        },
        function(isConfirm) {
              $.ajax({
                  type: "POST",
                  url: "cod_ajax/apaga_event.php",
                  data: "id="+event.id,
                  cache: false,
                  success:function(e){
                    $("#calendar").fullCalendar( 'removeEvents' [ event.id ] )
                    $("#pop").hide(0);
                    $("#pop").fadeIn("fast");
                  }
              })
        });

},

Com o código acima, ele apaga da base de dados mas não remove o evento, mesmo referindo event.id que penso ser assim que deva por como tem AQUI mostrado.
Alguém sabe o que está errado?
Answer: Descobri o que tinha errado. O código que tinha escrito apanhava bem o event.id mas onde fui buscar o código, tem um erro que é no .fullCalendar( 'removeEvents' [, idOrFilter ] ). The "," is wrong in there, it needs to be out of "[ ]" and now it's working fine.

Não apanha id no full calendar?


Quarkus reactive client MySql client is not inserting records

Question: I am doing a poc for Quarks-Mysql reactive client using Quarkus 1.1.0.Final. The code is like the below :
public void put() {

        mysqlPool
            .begin(ar ->{
                if(ar.succeeded()) {
                    Transaction tx = ar.result();
                    tx.preparedQuery(
                        "insert into Book(categoryType, description, isbn, name, price, totalBuyers) values(?, ?, ?, ?, ?, ?)",
                        Tuple.of(1, "Fresh one", "ISBN-0", "Fresh", 100.0, 0),
                        qr -> {
                            if(qr.succeeded()) {
                                tx.commit(txr -> {
                                    if(txr.succeeded()) {
                                        System.out.println("Successful !!!");//Is not printing
                                    } else {
                                        System.err.println("Failed !!!");//Is not printing
                                    }
                                });
                            }
                            tx.close();
                        });
                }
            });
    }

After calling tx.commit, no async result is coming back (either success or failure) and no new record is inserted into database. inspire of that the auto id is getting incremented after each call. I am checking it using this.
My application.properties is :
quarkus.datasource.url = vertx-reactive:mysql://localhost:3306/ebs_book
quarkus.datasource.username = xxx
quarkus.datasource.password = xxx

I am using mysql official image with latest tag.
Am I missing something here ?
Also if anyone can provide and equal code with reactivex extension would be better. I don't like composite callbacks !
Answer: you should not call tx.close() after the commit() since it will schedule a ROLLBACK query, for how to use transaction APIs please take a look at the official documentation.
As for reactiveX extension code you may go to the page, it's in the PostgreSQL client documentation but I think the APIs are the same for MySQL client and I believe it could be improved to be included in the MySQL documentation too.
Moreover I'm not able to reproduce the problem you met, if the problem still exists could you please provide a reproducer and open an issue in https://github.com/eclipse-vertx/vertx-sql-client/issues?
Comment: I want to add if you prefer ReactiveX extension APIs you should use `io.vertx.reactivex.mysqlclient.MySQLPool`
Comment: Thanks it worked fine :), I also managed to do the same functionality with mysqlPool.getConnection().
Comment: Note if you're going to use `pool#getConnection()` you need to take care of the lifecycle of the connection so you need to call `conn#close()` to release it back to the pool when you're finished using it.


Listagem em sistema de indicação

Question: estou com uma dificuldade.
Estou criando um sistema de indicação em PHP e estou com dificuldade para listar os clientes e a quantidade de indicações que ele fez.
O sistema tem duas tabelas, a tabela 'clientes' que é onde se encontra os dados do mesmo junto ao código de indicação dele gerado automaticamente, e a tabela 'indicados' onde nela se encontra o id do cliente que acabou de se cadastrar e o código da pessoa que o indicou.
Agora eu estou sem saber qual logica utilizar para fazer a listagem do cliente que tem mais indicados.

Fiz uma tentativa, mas ainda não deu muito certo.
<?php
                    $PDO = conectar();
                    $sql = "SELECT * FROM clientes,indicados WHERE cod_cli=codcli_indic ORDER BY id_cli ASC";
                    $stmt = $PDO->prepare($sql);
                    $stmt->execute();
                    while($resultado = $stmt->fetchAll(PDO::FETCH_ASSOC)){
                        foreach($resultado as $user){
                            $qtd = count($user['codcli_indic']);
                        echo "

                        ".$user['id_cli']."
                        ".$user['nome_cli']."
                        ".$user['loja_cli']."
                        ".$qtd."

                        ";}
                    }
                ?>

O resultado ficou assim:

Mauricio indicou 2 pessoas, então ali em indicados deveria aparecer 2 e não aparecer duas vezes Mauricio na tabela.
Bom pessoal, tentei diversas formas e cheguei a um resultado satisfatório, vou deixar aqui como ficou o código, caso alguém tenha a mesma dificuldade.
<?php
                    $PDO = conectar();

                    $sql = "SELECT *, count(*) as count FROM clientes,indicados WHERE cod_cli=codcli_indic GROUP BY codcli_indic";

                    $stmt = $PDO->prepare($sql);
                    $stmt->execute();
                    $resultado = $stmt->fetchAll(PDO::FETCH_ASSOC);

                    //$qtd = count($resultado);

                   foreach($resultado as $user){
                       if ($user['cod_cli'] == $user['codcli_indic']){
                        $qtd = count($user['id_indic']);
                       }

                        echo "

                        ".$user['id_cli']."
                        ".$user['nome_cli']."
                        ".$user['loja_cli']."
                        ".$user['count']."

                        ";
                    }
                ?>

Comment: Poderia [edit] a pergunta e adicionar as estruturas das tabelas?
Comment: Perdão, esqueci de incluir
Comment: As tabelas possuem chave estrangeira?
Comment: Sua pergunta não está bem clara, mas ve se ajuda `select max(sum), nome_cli from (Select count(c.id_cli) as sum, c.nome_cli from clientes c join indicados i on i.idcli_indic = c.id_cli group by c.id_cli, c.nome_cli)`
Comment: Editei com um teste que fiz, mas não deu muito certo.
Answer: Pois então, no seu caso, acho que seria bom você usar um INNER JOIN, para que seja o caso de haver um resultado positivo em sua query... Que ficaria no caso assim:
SELECT *
FROM clientes t1
INNER JOIN indicados t2
ON t1.cod_cli = t2.codcli_indic
ORDER BY t1.id_cli ASC

Sugerindo a você também dar uma lida na ilustração de como ocorre as consultas JOINS para que haja um maior entendimento sobre tais consultas! :)

A duplicação de resultados se deve ao fato de ter um foreach dentro de um while, onde não tem a mínima necessidade, sendo que seu código poderá ficar assim:
while($resultado = $stmt->fetchAll(PDO::FETCH_ASSOC)){
    $qtd = count($resultado['codcli_indic']);
    echo "

    ".$resultado['id_cli']."
    ".$resultado['nome_cli']."
    ".$resultado['loja_cli']."
    ".$qtd."

    ";
}

Comment: Ainda assim continua aparecendo a repetição da coluna, mas obrigado pela ajuda.
Comment: Eu vi onde você errou e arrumei o teu código, tente agora... Visto que você não necessita ter um `foreach` dentro de um `while`, pois o **while** já irá fazer o loop de resultado e se colocar o **foreach** ele irá duplicar esses resultados! :)
Comment: A repetição desapareceu, muito obrigado!! Agora, os números de indicados está com o valor 1 para os dois usuários, sendo que um deles tem dois indicados
Comment: Você já tentou fazer o `count()` apenas do `$resultado`? Pois dentro da query ele já faz a verificação, e ali você está fazendo a contagem apenas de **1 coluna**. Tente fazer o seu **count()** apenas do **$resultado** e retorne aqui para demais dúvidas! :)
Comment: Tentei sim, quando faço o count apenas do $resultado, ele apresenta o numero 2 em ambos os usuários :(

Listagem em sistema de indicação


How to check if value is equal to container ID in Vue?

Question: I want to check if a property is equal to the ID of a div container.
And add a condition to show the container when the check is equal.
In this example below, I just want to check if the activeWindow property is the same as the div id. When it's equal then I want to show the div container.
I have tried to add id in the if check, but that didn't work.
When I add the string directly in the if check, like:
v-if="activeWindow === activeWindow"
then it works, but this time I have defined the ID at two places and it's not dynamic.
private activeWindow = 'activeWindow';

This window is active

This window is active

How can I solve this?
Comment: surely it's `v-if="activeWindow === 'activeWindow'"` since a variable will always be equal to itself (in most cases)
Comment: The `id` in the if expression is not the `id` attribute, you need to add it as a prop, or get it from a refence of the element etc.
Comment: @JaromandaX but in this case, I have defined the ID at two places as I stated in my post.
Answer: You can also bind id and make it both dynamic:

This window is active

in data function:
data() {
  return {
    id: 'active',
    activeWindow : 'active'
  }
}

Comment: But I have multiple div containers with all unique ID's. If I define it like this in the data function, then it will not work for the other containers.
Comment: @Can hey mate, that was just example, of course you need to pass id to every container


Theorem 5.11 in Hungerford Algebra $f^{-1}f(K) = K$ if and only if $\ker f < K$.

Question: Let $f \colon G \to H$ be an homomorphism,
in the proof of the theorem 5.11, Hungerford states that $f^{-1}(f(K)) = K$ if and only if $\ker f < K$ for $K$ is a subgroup of $G$.
I proved the forward direction which is rather straightforward.
But Im struggling with the backward direction.
Suppose $\ker < K$, how to prove that $f(f^{-1}(K)) = K$?
Comment: $\ker f < K$ or $\ker f \subset K$?
Comment: @the_candyman its equivalent
Comment: well, maybe you mean $\dim \ker f < \dim K$ ("<" is used between numbers, "$\subset$" between sets)
Comment: @the_candyman This is just the notations from the Hungerford....he uses $H < G$ to denotes subgroups. I thought its pretty common to use $H \leq G$ for subgroups, both Hungerford and Dummit&foote do this.
Comment: Ok Ok, I got it.
Comment: More generally, $f^{-1}(f(K)) = \langle K, \ker f \rangle $. See https://math.stackexchange.com/a/955413/589
Answer: Hint:
Show $f^{-1}\bigl(f(K)\bigr)=K\,\ker f$ (in multiplicative notation), and use the $2^{\textit{nd}}$ isomorphism theorem.
Answer: Elementary proof.
You already proved that if
$f^{-1}(f(K)) = K$, then $\ker f \subseteq K$.
Suppose now that $\ker f \subseteq K$ and let $x \in f^{-1}(f(K))$. Then $f(x) \in f(K)$ and hence there exists $y \in K$ such that $f(x) = f(y)$. It follows that $f(xy^{-1}) = f(x)f(y)^{-1} = 1$ and thus $xy^{-1} \in \ker f$, whence $xy^{-1} \in K$. Since $y \in K$, it follows that $x = (xy^{-1})y \in K$. Thus $f^{-1}(f(K)) \subseteq K$. The opposite inclusion $K \subseteq f^{-1}(f(K))$ is trivial, and thus $f^{-1}(f(K)) = K$.


$X,Y$ be locally compact spaces , then is $X \times Y$ also locally compact?

Question: Let $X,Y$ be locally compact spaces , then is $X \times Y$ also locally compact ? (one might assume $X,Y$ to be Hausdorff also if necessary )
Comment: Definitions are your friends.  What do you need to show to prove $X\times Y $ is locally compact?
Answer: Hint: the product of compact sets is compact.


Notation for Double differentiation

Question: I am asking this question simply out of curiosity.
Why the double differentiation is denoted by $\frac{d^{2}f(x)}{dx^2}$ and not by $\frac{d^{2}f(x)}{d^2x}$ or $\frac{d^{2}f(x)}{(dx)^2}$. Is there any mathematical reasoning behind it?
It seems like a similar question has been asked before here. But then the same discussion happened there, i.e., why $\frac{d^{2}f(x)}{(dx)^2}$ is not the correct notation :/
Comment: I believe it also relies on the fact that $dx$ is considered independent of $x$. In original notation, it actually referred to an infinitesimal, so $dx^2=(dx)^2$ irrespective of x.
Comment: It's shorthand for $\frac d{dx}\,\frac{df}{dx}$ with the "like terms" "combined" when "multiplied".  Your second suggestion would be the "correct" way to multiply the "denominators" together, but the founders of the notation evidently liked simplicity more than correctness.
Comment: @InuyashaYagami I would say that $(dx)^2$ in the denominator is not technically incorrect but so overwhelmingly uncommon that it is wrong "by convention" because using it makes people wonder if you mean something different.
Comment: I believe that it relies on the fact that you can also take a double derivative on two variables, where it looks like ${d^2f(x,y)\over dxdy}$. I believe the second example expression is actually equivalent to the conventional notation.
Comment: @MatthewDaly Ahh! Mathematics should believe more in the correctness than simplicity
Comment: @HansLundmark Thanks!. But it did not answer the question. I am wondering why $\frac{d^{2} f(x)}{(dx)^2}$ is not the correct usage? The same discussion took place there also.
Answer: There is a reason for the notation, but the present notation has its own problems.
The reason for the notation is that the derivative is a differentiation followed by a division by $dx$.  Historically, we didn't always deal in derivatives but often used differentials (Newton was primarily derivatives, Leibniz was primarily differentials).  So, the differential of, say, $x^2$ is $2x\,dx$.
You get a derivative by taking the differential of a function and dividing by $dx$.  You get the second derivative by doing it again.  So, you'll be dividing by $dx$ twice, so $dx^2$ is on the denominator.
However, this doesn't quite match with what we have in the present notation.  A fuller notation can be found by actually taking the derivative of the derivative - i.e., treating the derivative $\frac{dy}{dx}$ as a fraction, differentiating (using the quotient rule since it is a quotient), and then dividing by $dx$.
This yields:
$$y'' = \frac{d^2y}{dx^2} - \frac{dy}{dx}\frac{d^2x}{dx^2}$$
Where $du^2$ is a shorthand for $(d(u))^2$ and $d^2u$ is a shorthand for $d(d(u))$.  Using the form above, you can actually treat the second derivative in an algebraic manner (canceling denominators, multiplying "both sides" by something, etc.).  With the traditional notation, you can only really manipulate it using the "chain rule for the second derivative."
Here's a more full derivation.  We will use the full notation $d(u)$ so that everything is more clear:
$$ y'' = \frac{d\left(\frac{d(y)}{d(x)}\right)}{d(x)} \\
 = \frac{\frac{d(x)\, d(d(y)) - d(y)\, d(d(x))}{(d(x))^2}}{d(x)} \text{ (quotient rule on top)} \\
 = \frac{d(x)\, d(d(y)) - d(y)\, d(d(x))}{(d(x))^3} \text{ (simplifying denominators)} \\
 = \frac{d(x)\,d(d(y))}{(d(x))^3} - \frac{d(y)\,d(d(x))}{(d(x))^3} \text{ (splitting the fraction)} \\
 = \frac{d(d(y))}{(d(x))^2} - \frac{d(y)}{d(x)}\,\frac{d(d(x))}{(d(x))^2} \text{ (simplifying)} $$
Note 100% sure, but I think the "normal" notation came about because, if you imagine the independent variable moving at a constant rate (so $d(x)$ is constant), then, by definition, the differential of a constant is zero, which wipes out the second term.  However, this fails if $x$ is a function of some other variable, and therefore the notation typically used doesn't generalize. I think it gained popularity in physics because they generally used time as the independent variable, and, in the time before we knew about relativity, the flow of time was considered constant.  If you were working with something whose independent variable wasn't so independent, you can still manipulate it using the chain rule for the second derivative.  In the expanded notation here such a rule isn't strictly necessary, as you can simply do algebraic manipulations to do the same thing (but the chain rule can help you remember what manipulations to do!).
For more information, see my paper "Extending the Algebraic Manipulability of Differentials".  It's available on arXiv.
Comment: Thanks! It was helpful.

Notation for Double differentiation


On the derivative of Dirac delta

Question: Let $\delta(x)$ be the Dirac's delta, i.e. the "strange object" characterized by the two properties $\delta(x)=0$ for all $x\neq 0$ and $\int \delta(x) f(x)\text{ d}x= f(0)$ ($\int f$ is the integral over $\mathbb{R}$).
Now, let's define the derivative of $\delta(x)$ as
\begin{equation*}
\dot{\delta}(x)\triangleq \lim_{\tau \to 0} \frac{\delta(x+\tau)-\delta(x)}{\tau}
\end{equation*}
For simplicity, I'm considering the univariate case $x\in\mathbb{R}$. Now let's try to see what happens when we compute a weighted integral of $f(x)$ involving $\dot{\delta}(x)$. I would write naively
\begin{equation*}
\begin{aligned}
\int \dot{\delta}(x) f(x)\text{ d}x&= \int \left(\lim_{\tau \to 0} \frac{\delta(x+\tau)-\delta(x)}{\tau}\right)f(x)\text{ d}x\\
&= \lim_{\tau \to 0} \frac{1}{\tau}\left[\int \delta(x+\tau)\,f(x)\text{ d}x - \int \delta(x)\,f(x)\text{ d}x\right]\\
&= \lim_{\tau \to 0} \frac{1}{\tau}\left[f(0-\tau) - f(0)\right]=-\dot{f}(0)\\
\end{aligned}
\end{equation*}
provided that we can push the limit sign outside the integral (if I'm not wrong, here Lebesgue help us to see when this can be done); the difference between the two integrals is not in the form $\pm \infty \mp\infty$; the derivative of $f(x)$ exists in $x=0$.
If I'm not missing anything else, we can say that, just like $\int \delta(x) f(x) \text{d}x=f(0)$, we have $\int \dot{\delta}(x) f(x)\text{ d}x=-\dot{f}(0)$.
Question
Since the $\delta(x)$ is a "strange object", I'm not 100% sure about my conclusions. So, my question is: am I right? If not, where I'm wrong?
Comment: Yes, though in general manipulation of weird things like this is easy to mess up. See https://en.wikipedia.org/wiki/Dirac_delta_function#Derivatives
Comment: You are wrong by a sign:  $\lim_{\tau \to 0} \frac{1}{\tau}\left[f(0-\tau) - f(0)\right]=-\dot{f}(0)$, hence $\int \dot{\delta}(x) f(x)\text{ d}x=-\dot{f}(0)$.
Comment: You have missed one important properrty of Dirac Delta: $\delta(a x)=\frac1{|a|}\delta(x)$. This thing exactly makes it the most strange
Comment: where do we use $\delta(ax)$?
Answer: Your argument shows that the derivative of the delta distribution, let's denote it by $\delta',$ is given by a limit of difference quotients, i.e. your $\dot{\delta}.$
We need to know three things about distributions to make it rigorous:

For a distribution $\phi,$ its derivative $\phi'$ is defined by the relation
$$\int \phi' f:=-\int \phi f'$$ for any test function $f.$ The motivation behind this definition is that when $\phi$ is a (continuously differentiable) function, this identity is just integration by parts.
The limit $\lim_{n\to \infty} \phi_n$ of a sequence of distributions $\phi_n$ is characterized by
$$\int(\lim_{n\to \infty} \phi_n) f=\lim_{n\to \infty}\int \phi_n f$$
for any test function $f.$ This can either be taken as a definition of convergence for distributions or proven as a theorem.
For a distribution $\phi$ and $\tau\in \mathbb{R}$ there is its shift $\phi(\cdot+\tau),$ which is again a distribution given by the identity
$$\int \phi(\cdot+\tau) f=\int \phi f(\cdot-\tau)$$
for any test function $f.$ Similarly to 1., for functions this is just a change of variables.

Using these facts, your proof shows
$$\delta'=\lim_{\tau\to 0} \frac{\delta(\cdot+\tau)-\delta}{\tau},$$
an equality of two distributions, which is exactly the result we would expect from the corresponding equality for functions.
Comment: (+1) You might consider correcting the OP's assertions about the "properties" that characterized the Dirac Delta.  Namely, $\delta(x)=0$ for all $x\ne0$ is not at all correct.  And $\int_{\mathbb{R}}\delta(x)f(x)\,dx=f(0)$ is only a notation, and not an integral (unless the Dirac Delta is regarded as a measure, in which case its derivative is not).

On the derivative of Dirac delta


If the boundary of a bounded open set is a manifold, what is its dimension?

Question: Let $\Omega \subseteq \mathbb R^n$ be a bounded open set and suppose that the topological boundary $\partial \Omega = \bar \Omega \setminus \Omega$ has the structure of a topological manifold. In particular, $\partial \Omega$ has a dimension $m$. Can we say anything about $m$; is it $m=n-1$, as intuition suggests?
Comment: Maybe related [Hausdorff dimension of the boundary of an open set in the Euclidean space - lower bound](https://mathoverflow.net/q/40593)?
Comment: @Invisible The discussion there is promising, what it shows is that $\Omega$ has Hausdorff dimension at least $n-1$. However, Hausdorff dimension is generally $\geq$ topological dimension. Is there any way to conclude something about the topological dimension?
Comment: An open set in $\Bbb R^n$ always has dimension $n$, this is well-known. Its boundary has dimension $\le n-1$.
Answer: In the case where your set is convex, you may want to take a a look at chapters 6 and 18 of 'Rockafellar, Ralph Tyrell. Convex analysis.' Essentially you can show that the relative boundary of a convex set $A$ is also the union of all proper faces of that set and that proper faces are convex subsets of $A$ that are exactly the intersection of $A$ with an affine space of lower dimension. Finally if the interior of $A$ is non empty, the relative interior and the interior match and so the relative boundary is actually the boundary.
Not sure if that can help for the general case.


How to not capture vertical bar in regex?

Question: I have this regex
([=|"| |_|\w]*), but regex101.com is telling me that | is one of the characters that's included in the group to be able to match, but I just want the characters = or " or  or _ or \w to be matched.
Does anyone know whats wrong?
Thanks
Comment: No need for the `|`. `[..]` contains all the relevant characters, not a literal.
Comment: Use character class: `[=" _\w]*`
Answer: Inside a character sets ([]) | has no special meaning (it will match literally). In fact character sets have implicit or on their members. Just use [=" _\w]*
Answer: You just need to use ([="\s_\w]*). It will match any of the combination of the elements.

[] :  Matches a single character that is contained within the brackets

There is no need for | inside []
Comment: I believe a character class will do this without the explicit `{1}`.
Answer: (?:=|"| |_|\w)*

You can use this.| inside [] is just a character without special meaning.
Comment: Characters sets are defined for this sole purpose. The fact that the accepted answer is one that explicitly enumerates makes for a terrible future reference...
Answer: no need for the |, inside of [] it is already implied
([="\s_\w]*)

^is basically the exact thing you are trying to do.
unless you meant this:
([=]|["]|[\s]|[_]|[\w]*)


To know what theme functions are available

Question: I wonder if there is any method to obtain all available options for theme() function in Drupal installation? (I mean those one that are declared through HOOK_theme()). Or at least a resource where the most common uses are noted.
P.S. This is not trivial question for me, because almost every module introduces its own hooks for theming and if I don't know about them I can not leverage from theming opportunities. For example if I don't know about theme('table', ....) or theme('fieldset', ....) I have to write my own hooks that, e.g., another developer in his turn will  not be heard of, etc.
Thank you.
Answer: The default theme implementations for Drupal core can be found listed here:
http://api.drupal.org/api/drupal/modules%21system%21theme.api.php/group/themeable/7
If you want the theme functions for contrib as well, you could use hook_theme_registry_alter on your install and dump out the theme registry with devel to list all the theme implementations.
e.g
/**
 * Implements hook_theme_registry_alter
 */
function mymodule_theme_registry_alter(&$registry){
  dpm($registry); // requires devel module
}

Comment: be prepared to welcome a massive array of at least 300 items in it :)
Answer: There are over 200 theme hooks in Drupal 7 core, you should not need to know all of them, since most of them will never need to be called, or overridden.
Think about the markup you would like to produce, and then either search the drupal API for a function that provides that markup, or look at a module that already produces something similar, and use the function they use.