How would I notate this custom repeat scenario with sheet music?

Question: I am composing a song.  It has 8 measures in the verse and 8 in chorus.  I also have an 8 measure instrumental section that I would like to include, after the second verse and before the second chorus.
For the life of me I can't figure out a way to make this work without just notating flat.  It seems like there should be some combination of D.S., D.C., or Coda, but I don't see it.
Any suggestions?  Feeling like the novice I am!
Basically, I would like to insert measures 20-27 after the second verse (measure 8) and return to measure 9 after the instrumental.
I hope that makes sense.
Any suggestions, or should I just flatten it?
Comment: I have seen this notated as "instrumental bridge" or simply "bridge" and at the end of the bridge: "final time to chorus."
Comment: Personally I don't like repeats, DS, DC, etc. Not sure why you're opposed to writing it all out.
Answer: You can use DS, DSS, coda, double coda but why? The song as is is only 27 bars. Eliminating a road map would add 16 bars (an extra verse and chorus if I'm reading it right) and avoid any possible confusion of missed signs, repeats or repeat endings. Write it out from top to bottom, you're better off, especially if others will be sight reading the song. Plus, it's already computer generated, no elbow grease required.
Comment: @Curto One other suggestion: eliminate the rests in the first bar and just have it be a single 8th note pickup bar, it's cleaner that way.
Comment: I hink you are probably right. Asking the question help me learn.  Not familiar with DSS and double Coda.  I will likely flatten it after reading up.  Thank you.
Comment: @Curto The doubles function just like regular ones, they are just placed in different locations. They are basically two signs or codas side by side. Just something else to add to the confusion, lol.
Comment: And if it all fits onto just one sheet, that's a bonus!
Answer: Hypothetical Italian repeat markings answer:
If and only if  codas, segnos, etc. were the only tools at one's disposal,
I would suggest D.C. al Coda ("Da Capo al Coda"; roughly "from the head (beginning) to the tail (ending)" in measure 17, which jumps the piece to the beginning. This could also be accomplished with "D.S. al Coda" instead if one places the segno symbol  at the very first measure. Then additionally place a "to Coda" (or keeping with the Italian, "al Coda") in measure 8 and a coda symbol  in measure 20. This will ensure that on the repeat, the music skips from the end of measure 8 to the start of the measure 20 coda. Remember that "D.C." always stands for "Da Capo", never "Da Coda".
In order to get back to measure 9 from the end of the instrumental coda section, many possible notation options can be utilized. One such option would be rewriting measures 9 through 19 out again after (as part of) the coda. However, if the song were to continue after this point, that could end up being a lot of recopying.

Keep in mind that the traditional usage of the term "coda" was for the coda to be a special ending segment to the piece, so this is not conventional implementation of the notation. Knowing this, I'm about to suggest something even more outlandish and impractical:

Hold onto your hats, because Multiple Codas is a hypothetical solution in the general case of complex repeats. This would involve changing the first "D.S. al Coda" into "D.S. al Coda 1" and the "to Coda" into "to Coda 1", then placing a segno symbol at measure 9, and finally at measure 27, the end of the first coda, adding the words "D.S. al Coda 2". After all of this, the reader is directed from the end of what is now coda 1 to jump into the segno symbol at the 9th measure to play the second chorus.
(If there has already been a segno mark used to get to the second verse from the first chorus, then number this segno as segno 2 in the same manner as the codas. It may be wise to spell out all abbreviations for clarity.)
The reader will now continue from there into the 19th measure for the first time: here, should the song hypothetically continue beyond measure 19, another marking must guide them to either a second coda or an additional segno. "To Coda 2" could take the reader out beyond the first coda section (past measure 27) into whatever new material is up next, or another "Dal Segno" could drop the poor reader off at a previous section for more repeats: if a third verse is required, write "D.S." at measure 19 and place another segno mark at the beginning of the third verse in measure 1. If the piece is to end at measure 19, change measure 27 to "D.S." and no further repeat markings will be necessary.
This process can be repeated indefinitely with sequentially numbered segnos and codas for any complex series of repeats and jumps. Whenever the music needs to skip backwards to an earlier measure, place a segno mark at the destination and use "D.S." at the outgoing measure. When the music needs to skip ahead to an upcoming measure, use "to Coda" at the point of departure, set up another coda marker at the point of arrival, and add "al Coda" to the previous "D.S." or "D.C." marking.

I do not at all recommend the notation system that I just laid out.
This is too convoluted to be optimal for most conceivable modern notation - it took me somewhere in the neighborhood of two hours to puzzle out and type up all of this madness and I still may have made some mistakes (I've already had to fix one). Using repeats like this, the reader will probably not appreciate the saved space; rather, they would in all likelihood be frustrated at the unnecessarily difficult repeat scheme. Musicians care about efficient use of space, but not at the expense of legibility! I have heard only rarely of the idea of multiple codas and might own one bit of contemporary sheet music that uses it - if memory serves -, but a quick search returned only a Musescore forum discussion where the main answerer strongly cautioned against the idea (good on them).
There may also be some stuff about double segnos and double codas somewhere out there, but I don't know enough about them to answer. Honestly, I think a modern musician could probably live their whole life without learning any of the "D.S. al Whatever" notation. It seems far too dated in the face of accepted modern sheet music practices, and it was optimized for composition forms that are no longer in contemporary style. But that's just me. For curiosity's sake, I'd love for someone to point me to some info on the double segno and the likes.
It would be far wiser to use the strategies given in the other answers to notate this piece; I simply decided to attempt a full answer detailing the difficulties of using only the Italian repeat notation schemes. Hopefully this answer serves as a strong argument to "get with the times" and use more modern repeat notation where appropriate (or simply bite the bullet and write it all out).
Comment: Not just optimised for forms that are no longer in contemporary style, but used where music was engraved by hand and saving eight bars might actually reduce the price. With computer typesetting that motivation disappears too.
Answer: You can notate it this way:

Verse
First ending, marked "to chorus"
Jump over instrumental section
Chorus, with D.C.
Second verse
Second ending leads into instrumental, then chorus
End
Answer: Easiest way I can think of is to simply treat your instrumental break as the third verse.  You could simply add "instrumental" underneath the lyrics for the second verse.  Unless I am mistaken, the chords are the same.  This is a simple solution, and it shows to the musicians that the form of the solo break is identical to the verse.


Advice on Structuring a Comment System

Question: I am a beginner at database design and I would like to create a comment system with the ability to reply to user comments and to display potentially all comments a user has made. Furthermore, there will be many pages that will each have a section for commenting.
So far I have come up with two potential database designs to structure the comment system. The first will have a table for each pages' comments and a table for each users' comments. The page comment table will have user_id and page_id fields for table linking purposes.
The second potential design structure is to have one large partitioned table of comments that just has comment_id and user_id fields for table linking. I haven't thought about how to approach the reply feature yet; I wanted to get some input on which design approach, if any, would perform efficiently before I tackled that problem.
Answer: comments
   id
   user_id
   comment_text
   page_id
   parent_id

Use this to store comment for a page. parent_id is a comment that is a reply of another comment. For a comment on the page the parent_id will be zero (no parent comment), but for a reply the parent_id will be non-zero and it will be the ID of the comment which the reply belongs to.
For example, you will have data like this
id user_id comment_text page_id parent_id
1  6         sdh          1       0          <-- comment on the page
2  9         gfdf         2       0          <-- another comment on other page
3  4         reply xzy    1       1          <-- reply to comment id 1 by user id 4 on page 1

You may consider having timestamp, flagged, deleted etc fields that can help you in sorting, ordering, filtering, monitoring and soft-deleting a comment. You can group by page, by user, by parent.
Comment: too hard to query,,this approch
Answer: I'd go with two tables: one for comment threads and another for the comments. The comment threads would look something like this:
id
/* Other bookkeeping things like created time and such */

and comments:
id
thread_id
user_id
comment
parent_id
/* Other bookkeeping stuff */

Then attach the thread to the page by adding a comment_thread_id column to the page table.
Having a separate distinct comment thread gives you a convenient place to attach access control or similar extensions in the future, it also allows you to attach comment threads to things. Attaching the comment threads to the page rather than the other way around makes it easy to add comment threads to other objects in your system later on.

Advice on Structuring a Comment System


Where did the $i$ go in the second order differential equation solution?

Question: Let $a\ddot{y}+b\dot{y}+cy=0$ such that $b^2-4ac<0$, we then have a solution of the form
$y=e^{\alpha t}(A\cos(\beta t)+B\sin(\beta t))$
Where $\alpha$ is the real part, and $\beta$ the absolute value of the imaginary part of the solutions of the following polynomial equation:
$ax^2+bx+c=0$
However, when I try to prove this general solution, I find
$y=Ae^{(\alpha+i\beta)t}+Be^{(\alpha-i\beta)t}$
$y=e^{\alpha t}(Ae^{i\beta t}+Be^{-i\beta t})$
$y=e^{\alpha t}(A(\cos(\beta t)+i\sin(\beta t))+B(\cos(-\beta t)+i\sin(-\beta t)))$
$y=e^{\alpha t}((A+B)\cos(\beta t)+i(A-B)\sin(\beta t))$
Could anyone please explain to me how we get rid of the $i$ to find the general solution?
Comment: How did your attempt to prove the general solution yield the second expression for $y$?
Comment: Note that the general solution admits constants $A, B\in\mathbb C$.
Comment: But isn't y supposed to be real?
Comment: It doesn't have to be.
Comment: Note that the $t$ is missing in the beginning of your derivation.
Answer: Note that the constants $A, B$ that you write in the first version of $y=\ldots$ are not the same that you use in your derivation.
Renaming the second pair to $A\to C$ and $B\to D$, your proof would start out with $y(t) = Ce^{t(\alpha + i \beta)} + D e^{t(\alpha-i\beta)}$. Now we make the following observations:

If $C,D\in\mathbb R$, then $y(t)\notin\mathbb R$ in general, because you always have the term $i(C-D) \sin(\beta t)$, which is nonzero whenever $C\neq D$.
If you want to reproduce the original expression, you would have to match the coefficients:
$$A = C+D,\quad B = i(C-D),$$
and you can solve this for $C,D$ if you want.

Point is, $A,B$ and $C,D$ may be complex, and won't be real simultaneously. Both formulations of the general solution that you mention are equivalent. Since your ansatz using $e^{\alpha + i \beta}$ will carry you out of the real numbers, you can't expect every solution to be real - you have to choose the coefficients accordingly to achieve that.
Comment: What ansatz would one need to use to always get real solutions?
Comment: Use this directly: $y=e^{\alpha t}(A\sin\beta t + B\cos\beta t)$, and plug it in your ODE to see that it satisfies it.


Distances inducing the same topology but with different balls

Question: I'm looking for two different metrics $d,d'$ on the same underlying space $X$, such that
1) $d$ and $d'$ induce the same topology on $X$;
2) there exists $x \in X$ such that small balls for $(X,d)$ and for $(X,d')$ with center $x$ are not homeomorphic.
This might be a trivial question, but I can't find an easy example.
EDIT: I'm mostly interested in the case $X = \mathbb{R}^n$ and $d$ is the Euclidean metric.
Comment: Do you know that (1) and (2) are compatible? It seems like they shouldn't be, but my intuition could be off here.
Comment: So, you want to find two metrics that induce the same topology, and a point $x$ in the space, such that for any $\epsilon>0$ there is an $r<\epsilon$ such that the $r$-ball around $x$ in the $d$ metric is not homeomorphic to the $r$-ball around $x$ in the $d'$ metric.
Answer: Let
$$
X=\bigcup_{n=1}^\infty\{(x,y)\in\mathbb{R}^2:x^2+y^2=n^{-2}\}.
$$
$X$ is a union of circles of radius $1/n$. Consider the distances $d_1$ and $d_2$ coming from the equivalent norms $\|(x,y)\|_1=|x|+|y|$ and $\|(x,y)\|_2=\sqrt{x^2+y^2}$. The topologies induced by $d_1$ and $d_2$ on $X$ are the same. Balls of $d_2$ are a union of circles. Balls of $d_1$ are union of circles and pieces of other circles.
Comment: Thanks! Do you have an example where $(X,d)$ is fixed and is the standard Euclidean space?
Comment: I can't think of one right now.
Answer: I think this is an example. Define
$$f(x)=\begin{cases}
Ax\sin(\ln|x|)\ \text{ if }\ x\ne0,\\
\quad\quad\quad0\quad\quad\ \ \text{ if }\ x=0,\\
\end{cases}$$
where $A$ is a sufficiently large constant. (If I figured this right, $A=e^{3\pi/2}$ is big enough.) Since $f$ is a continuous function, its graph
$$X=\{(x,f(x)):x\in\mathbb R\}$$
is homeomorphic to $\mathbb R.$ The topology on $X$ is induced by the standard metric on $\mathbb R^2;$ since $X$ is homeomorphic to $\mathbb R,$ there is a funny metric $d'$ on $\mathbb R$ which induces the standard topology of $\mathbb R$ and is metrically isomorphic to $X;$ namely,
$$d'(x_1,x_2)=\sqrt{(x_1-x_2)^2+(f(x_1)-f(x_2))^2}.$$
The point is that, in $X,$ the balls $B(0;r)$ are disconnected sets. To see this, consider any radius $r\gt0.$ Define $n\in\mathbb Z$ so that
$$e^{-n\pi}\lt r\le e^{-(n-1)\pi}.$$
Then $(0,f(0))=(0,0)\in B(0;r)$ and $(e^{-n\pi},f(e^{-n\pi}))=(e^{-n\pi},0)\in B(0;r),$ but $(e^{-(n+\frac12)\pi},f(e^{-(n+\frac12)\pi})\notin B(0;r),$ because
$$|f(e^{-(n+\frac12)\pi})|=Ae^{-(n+\frac12)\pi}\ge e^{-(n-1)\pi}\ge r.$$
Answer: Given any injective function $f:\mathbb R\to\mathbb R$ you can define a metric $d_f$ by
$$d_f(x,y):=|f(x)-f(y)|.$$
Consider the function $f$ qualitatively pictured below:

A possible analytic expression could be
$$f(x)=x+\sum_{n\in\mathbb Z} 4^{-n}\chi_{(4^{-n},2\cdot4^{-n})}+\sum_{n\in\mathbb Z} 2\cdot 4^{-n}\chi_{[2\cdot 4^{-n},4^{-(n-1)}]}$$
where the important thing is the alternation between open and closed intervals.
Consider then
$$d:=d_f\qquad \text{and} \qquad d':=d_{2f}=2d_f.$$
They induce the same topologies because the collection of all balls is exactly the same, since $B^d(x,r)=B^{d'}(x,2r)$.
However if you choose any $r$ not in $\overline{f(\mathbb{R})}$ (which you can do for arbitrarily small values of $r$), the ball of center zero and radius $r$ for one metric will be a right-open interval, while for the other metric it will be a right-closed interval, therefore they are not homeomorphic.
Comment: I wanted to make an example where balls are connected, which is a consequence of $f$ being monotone.
Comment: Re-reading the title I don't know if this is kind of cheating for the OP...I understood the request as in the interpretation by Akiva Weinberger in the comments.


When does a guitar neck bend happen and how to prevent it?

Question: We all know guitar necks bend and it is the worst thing that can happen to a guitarist but I would like to know what all the reasons that can cause it are? Some that I have heard are: (please explain why and preventive steps that can be taken)

Changing of string gauges
Not playing guitar for a long time
using floyd rose
Change of season
Comment: Do you mean damage to the neck, like warping?
Comment: yes warping is what i want to know about.
Answer: All of those can put adverse pressure on the truss rod of the guitar and cause bowing. the reason being that the temperature change with the seasons, in combination with the humidity, can cause the wood to expand and contract causing bowing.

when adjusting to a new string gauge go have your truss rod adjusted to the new tension.
my best recommendation is to store it in a temperature controlled room where it has a stable humidity when storing for a long time. also playing your guitar every once and a while never hurt (:
Floyd Rose seems to be a product that would place a strange type of pressure on the guitar
Change of season causes expansion, and contract of the guitar so keeping in properly air conditioned as much as possible is key. The other side of the seasons coin is humidity the guitar is going to have the possibility of warping with too  much moisture of drying out if there is not enough moisture.

I hope this helps you be kind to your instrument (:


Configuring RemoteApp for external users, how does RDS Gateway work?

Question: I feel I must be just missing something obvious here. I have a working RDS deployment with two RDSH hosts. It's not perfectly architected, but this came from a PoC and will be re-engineered in a few months so I'm not worried about that. We have three systems - the RDS Gateway, one RDSH box, and another RDSH box (which is the original one) which also has RDWeb/Broker/Licensing on it. It's probably easiest to just ignore the second RDSH box in this equation so I'm going to do that.
What I'm trying to do right now is to make the RemoteApp software available off-net, so that users don't have to VPN in to access applications. I had been working under the premise that RDS Gateway was the piece in this puzzle, but it seems clear now (especially now that I have RDS Gateway configured) that users don't connect to it directly.
We're not distributing .rdp files or giving users RDP access to other systems. I only want to publish applications to them. I'm given to understand that I should be using RDS Gateway for authentication here, but I'm really unclear on what the architecture is supposed to look like. It makes sense to me that I could just open 443 direct to the Internet and then folks could just log in without SSO. If that's the case, and I'm only publishing RemoteApp software, do I need the gateway at all? I'm totally fine with deploying it if I need it, but I just don't understand where it fits in and how to make it work the right way.
Answer: So, I think I understand now, I've got the setup working. I see now that RDWeb is basically just a launcher platform, but the connections are actually going through the Gateway. Once the .RDP has been downloaded from RDWeb, the web server isn't involved anymore.


How to find difference in means at particular points in a by-factor GAMM?

Question: This is a bit long but I wanted to give enough photos and code to explain what I'm doing and the issues I'm having. The main question is in the last paragraph.
I'm examining differences in male and female growth in a wildlife species using GAMMs, and while the GAMM output compares male and female growth across the curve (via the parametric coefficient telling me the significance of the partial effect of sex), I am wondering how I can compare the difference at different ages/x values. It was suggested I use this method because I have some repeat measures of individuals but not all repeats (we captured and measured whoever we saw on measurement day each year, so some animals are measured once in their life and some are represented in >5 age categories).
I've tried a few methods but all are giving me a different answer than my GAM is, and I'm wondering which is correct.
 My code is as follows:
gamm(data = data, Weight ~ Sex + s(Age, by = Sex), random = list(SubjectID = ~1), method = "REML")

This is the output:

And here are the effects plots:
(Note that some of the graphs and outputs say "AgeReset10Up", this is just because I have a few age categories, I changed it to "Age" in a few graphs and in this description for ease of reading but they're the same thing).
The parametric coefficient and partial effects plot tells me that there is a significant effect of sex, saying that over the growth curve females weigh more than males, but I want to know at what ages this is actually true, so that I can say for example females are significantly bigger than males at age x but not age y. I tried to find this out in three ways, but all say that there are no differences.
First, when I make a ggplot of the raw data and the GAM line overlapping, the CIs overlap at all points, which seems to indicate there is no significant difference in weight at any age.

Second, when I run a linear regression
lmer(Weight ~ Sex*Age + (1|SubjectID), data = data), there is no point at which the age*sex interaction that is significant, see below. Running the LMER was suggested to me as a way to find difference in means at each age, kind of like running individual t-tests (the reference age is age 10 btw).

And third, I had used Gavin Simpson's awesome function and tutorial to find the differences in the smooths, and when I posted a question about it he kindly suggested that I modify that code by not zeroing out the intercept and parametric lines and that that would give me a difference in means when the CI excludes 0, like in the post. I ran that, and there is no point at which the CI excludes 0, suggesting the means are the same at every point.
How is it that there's an overall significant effect of sex, with females bigger than males in the GAM, but when examining the actual mean at each age using several different methods there's no difference? A friend who specializes in GAMs said that the GAM output saying there's a significant difference is right, and that the other methods must be off. So am I just misunderstanding something? Is there a better way to find means?
Answer: I believe this

... and there is no point at which the CI excludes 0, suggesting the means are the same at every point

is one source of confusion.
On the face of it, the data and smooths suggest that the difference of means is not exactly zero. Put another way, whatever difference in means there is between the two groups is small relative to the uncertainty in the estimates of those mean. You observed a difference but cannot say with any level of confidence that this observed difference is a real difference in the population of subjects you might have sampled.
Why are each of the model terms significant but the difference not significant? This comes from propagating the uncertainty in all of the things you estimated into the computation of the difference of means as a function of age.
Controlling for the smooth effect of Age by sex, you detect a small difference between the two groups in the mean response. The two smooth terms were assessed to be unlikely to have arise if the true functions were flat constant functions.
Computing a difference of means as a function of age requires you to bring together all these estimated effects and propagate their uncertainties into your estimates of the difference in the response between the two groups as a function of age.
You could try a more direct estimation of the thing you are interested in by using the ordered-factor method.
data <- transform(data, oSex = ordered(Sex))
m <- gam(Weight ~ oSex + s(Age) + s(Age, by = oSex) + s(Subject, bs = "re"),
         method = "REML"

where s(Age) is the smooth effect of Age for the reference level of Sex, while s(Age, by = oSex) is the smooth difference between the smooth effect of Age in the reference level and the other level of Sex.
This shouldn't change the outcome much though; I suspect you'll see a small effect of Sex overall once you condition on the smooth effects of Age in both groups, but you won't find large ("significant") differences when you ask the more specific question of "At what ages are the groups different?".
Comment: As I wrote in my response, you shouldn't expect the `s(Age):oSexM` to be significant as there is no real difference in the shapes of the curves for Male and Female (even visually - just look at the curves in your original post). So what `s(Age):oSexM` is telling you about is a difference of shapes and the test says the estimated difference is not distinguishable from 0. This is the **shape** of the curve only. The parametric term controls the vertical position of the curve and there you do see a difference that is unlikely under H0 of no difference of means.
Comment: thank you for your explanation! So basically, there is a weight difference overall between the sexes, but it's not significant when I zoom in to any particular age due to the uncertainty/confidence intervals? Would I be correct in saying that there's a significant difference overall because of the significance of the gam, or can I not say that due to the uncertainty? Additionally, of the 3 methods, which would you say is best? In other measurements they gave me different answers, and I'm not sure which to trust.
Comment: I also tried out the ordered factor (ran out of space in last comment). The results are a bit different--now for smooth terms, s(Age) and s(SubjectID) are significant, but s(Age):oSexM is not. The parametric coefficient of sex is still significant. Not quite sure what to make of this!


Bijection between rectangles and quadrilaterals

Question: I understand that the set of rectangles is a proper subset of the set of quadrilaterals. So, in some sense the number of elements of the set of rectangles should be less than the number of elements of quadrilaterals.
However, if we take the set of integers and the set of even numbers, we can construct a bijection irrespective of the fact that one set is a proper subset.
So, I was wondering whether such a bijection exists in between the set of rectangles and quadrilaterals. If so, what about the cases like, set of squares vs set of rectangles. And so on...
Appreciate your thoughts.
Comment: Quadrilaterials are a subset of $\mathbb{R}^8$ ( EG take their lengths and angles), hence there is a bijection of Rectangles $- \mathbb{R}^2 - \mathbb{R}^8 - $ quadrilaterals. If desired, you can involve Cantor-Schroder-Beernstein to construct the bijection.
Comment: @Charith Right, there exists a bijection between polygons with $n\geq 3 $ sides and polygons with $m \geq 3 sides$ (Being pedantic with the phrasing as "any two sets of polygons" could mean "set A = this triangle, set B = those 2 squares".)
Comment: Congrats! You've just rediscovered the concept of Dedekind-infinite sets, which are those that can be put into a bijection with its proper subsets, as is the case with the naturals and the even naturals. All squares are rectangles but not all rectangles are squares, so yes, you can construct a similar bijection between them. I'm fairly certain that you could generalise this to just about any shape
Comment: @CalvinLin Ah so that means, you can construct bijections between any two sets of polygons with finite number of sides. Am I correct?
Comment: @H.sapiensrex Thank you.!
Comment: @CalvinLin That's pretty cool! Thank you!
Answer: There are two ways to think about this. Firstly, we can consider cardinality. In this case there is a bijection between them since quadrilaterals can be defined using four points and a rectangle can be with two. Both of these sets will have cardinality the same as $\mathbb{R}$ since they're proper subsets of $\mathbb{R}^n$ and uncountable.
However there is a second way we can consider this problem. Rather than considering cardinality we can consider measure. Measures are an abstraction of area where we can prove more intuitive results such as that a line is somehow smaller than a plane because it has area $0$ while the plane has infinite area.
To do that here we consider the four point definition of the quadrilateral. If we assume all points have the same probability of being selected we ask what the probability of picking four points at random and those four points forming a rectangle or quadrilateral respectively. However since parallelograms are defined by two non-colinear points once we select two points at random we must get lucky enough to pick two precise points out of all the points in the plane. The probability of doing this is $0$.
However picking four point at random the probability that any of three of them them will be colinear is $0$ and the probability that fourth is colinear with either of the other two is also $0$. This is because two intersecting lines have no area. This means they have a center of mass and if we set that as the origin and rotation counterclockwise we can label the four points in such a way as to form a valid quadrilateral. That means that every four random points forms a valid quadrilateral so the probability of picking one is $1$. This gives us a meaningful way to say that there are more quadrilaterals than rectangles.
Comment: @Charith the second argument doesn't prevent a bijection from existing. It's like how a line and the plane have the same cardinality but the line has area $0$ so it's "smaller" in that way.
Comment: Thank you for the answer. I'm a bit confused... Now with the cardinality argument mentioned in your first paragraph, I understand that we have a bijection. But with the next argument are you saying such a bijection cannot occur.. ?
Comment: I see. Thank you!


P(x) of degree at most 5 leaves remainders -1 and 1 on division by $(x-1)^3$ and $(x+1)^3$ respectively, then the number real roots of P(x)=0 are?

Question: This is an interesting question I came across. My attempt to do this is for a 3 degree polynomial is given below, but I don't know how to proceed further $$Let\space  g(x) \space be \space the \space quotient \space when \space P(x) \space is \space divided \space by \space (x-1)^3 \space then, $$
$$P(x)=(x-1)^3g(x)-1$$
$$Let \space g(x)=k $$
$$P(-1)=(-2)^3k-1$$
$$1=-8k-1$$
$$\frac{2}{-8}=\frac{-1}{4}=k$$
$$\frac{(x-1)^3}{-4}-1=0$$
On differentiating we see it's an increasing function and can only have one root. Can someone help me when P(x) is a 4  degree or 5 degree polynomial, since I'm getting too many unknown variables.
Comment: I think that $(x-1)^3$ and $(x+1)^3$ both divide $P(x)+P(-x)$, which implies that $P$ is odd, which in turn implies that $x$ divides $P$.
Answer: If $\deg P(x)=5$, then let $a$ be the coefficient of $x^5$ in $P(x)$. Then$$P(x)=(ax^2+bx+c)(x+1)^3+1\quad\text{and}\quad P(x)=(ax^2+dx+e)(x-1)^3-1,$$for some numbers $b$, $c$, $d$, and $e$. It follows from$$(ax^2+bx+c)(x+1)^3+1=(ax^2+dx+e)(x-1)^3-1$$that$$\left\{\begin{array}{l}6a+b-d=1\\3b+c+3d-e=0\\2a+3b+3c-3d+3e=0\\b+3c +d-3e=0\\c+e=-2\end{array}\right.$$and the only solution of this system is$$a=-\frac38,b=\frac98,c=-1,d=-\frac98,\text{ and }e=-1.$$So,\begin{align}P(x)&=\left(-\frac38x^2+\frac98x-1\right)(x+1)^3+1\\&=-\frac38x^5+\frac54x^3-\frac{15}8x\\&=-\frac x8(3x^4-10x^2+15).\end{align}Since the quadratic equation $3X^2-10X+15$ has no real roots, $P(x)$ has one and only one real root, which is $0$.
If $\deg P(x)=4$ similar (but simpler) computations show that there is no such polynomial.
Answer: Since $\deg(P)\leq 5$ and $(x-1)^3(x+1)^3$ is a divisor of $P(x)+P(-x)$, it yields that $P(x)=-P(-x)$ for all $x\in\mathbb R$. (At this point we know 0 is a root.) Hence, we have
$$P(x)=ax^5+bx^3+cx.$$
Now from $P(1)=-1$, we get $a+b+c=-1$. Further 1 is a triple root of $P+1$, we have $P'(1)=P''(1)=0$. It yields $5a+3b+c=0$ and $20a+6b=0$. By solving the system of linear equation, we have $a=-\frac 38$, $b=\frac 54$ and $c=-\frac{15}{ 8}$.
edit: i corrected the mistake.
Comment: Thank you a lot but just so you know, there is a small error in your solution P(x)=(-1)P(-x).
Comment: Yes, thank you :)
Answer: $(x-1)^3$ and $(x+1)^3$ both divide $P(x)+P(-x)$ which has degree $\le 5$, hence $P$ is odd.
Similarly, $(x-1)^2$ and $(x+1)^2$ both divide $P'(x)$, which has degree $\le 4$. Hence for some constant $\lambda$ we have
\begin{equation}
P'(x) = \lambda(x-1)^2(x+1)^2 = \lambda (x^2-1)^2 = \lambda (x^4 - 2 x^2 + 1)
\end{equation}
Hence by integration
\begin{equation}
P(x) = \lambda (x^5/5 - 2 x^3/3 + x)
\end{equation}
Using that $P(1)=-1$ we get $\lambda =-15/8$ hence
$P(x) = -3 x^5/8 + 5 x^3/4 - 15 x /8$
Observe that $P'(x)\le 0$ hence $P$ decreases, which means that its only root is $x=0$.


What do crescendo/diminuendo marks mean when no accompanying text?

Question: In the first page we have a solo verse. It starts mpand then builds to mf over one bar. But then in the bottom line we drop to p... But then the bottom line and top of page two we drop and build when we're already in p. Does that mean

Snow... on snow

Is dropping from p to pp then crescendoing back up to p?
Also since this is a solo, when it says mp does that mean I am singing mp or that the overall volume is mp relative to the whole choir ie I need to be quite loud?
Answer: I guess there's nowhere much to go below 'p' other than 'pp', so we can excuse a bit of sloppy notation.  It really should have been marked though, if only to avoid queries such as yours!
At the beginning, the piano is marked 'p', the voice 'mp'.  That's meticulously correct.  It would have probably been OK to mark both the same.  I don't think there's much chance that the pianist would try to dominate.
I don't see a 'mp' where the choir are singing?  When they enter, everyone has 'f'.  When the melody is in the top part, we probably don't have to over-think this, it will 'come through' automatically.
All dynamics are relative.  Yes, it's a 'solo mp'.  Treat it as a feeling as much as a reading on a dB meter!  The actual power you use will vary with the size of room and other factors.
We sometimes have to be over-meticulous when notating for computer playback.  Live performers listen to each other (hopefully).
Comment: But broadly speaking if I see mp for a solo verse, I am aiming to produce the same volume as the choir at mp? Because pp for a solo singer is going to be very quiet otherwise!
Comment: I've never sung a solo, or in a big church room (un-micced) - no idea how to gauge my volume so anyone can actually hear ;)
Comment: A choir at 'mp' is going to sound very different to a soloist at 'mp'.  But the measured volume might not be much different.  Partly because volume isn't simply additive - two singers are not twice as loud as one, or twenty singers twenty times as loud.  Partly because real musicians aren't computers who see 'mp' and pump out a fixed level - they LISTEN and do what is required to deliver the desired effect.   In this case you need to 'fill the room' but with a 'mp' feel.  Yes, all very subjective!  Your choir director will soon tell you if you're not judging it well.  Let him help you. Enjoy!
Answer: I don't believe we should attach paramount importance to all the dynamic marks. It may well be that they are put in by the publishers, rather than the writer, and as such, are whimsical.
More to the point, they're only advisory. It's your solo, so you must sing as you feel fit. As long as you are audible above the choir and accompanist, the job is yours. Can you honestly expect anyone afterwards to say ' that crescendo/rall. etc. wasn't the best'?!
That apart, as Laurence says, it's more dependent on the acoustics and balance in the room concerned on the day concerned. And do not forget that during any rehearsal prior, lack of absorbent bodies will give a very different dynamic to it all anyway.


Question about Riemann Integrable function

Question: If $f \in R[a,b]$, then the function $F:[a,b] \rightarrow \mathbb{R}$ defined as $F(x)= \int_a^x f$ is differentiable almost everywhere in $[a,b]$

I'm guessing this assertion is false because, if $f$ is the Weierstrass function, $f(x) =\sum_{n=0}^\infty \frac{1}{2^n} \cos(3^n\pi x)$ for all $x \in [a,b]$ is known to be a function that is continuous everywhere, hence Riemann integrable, but $F'(x)$ is differentiable nowhere. Where is my mistake? Thanks.
Comment: You want to know about the differentiability of $F$, not $F'.$ In fact, if the statement wasn't true for a continuous function, we'd have a contradiction to the fundamental theorem of calculus.
Comment: Use the fundamental theorem of calculus combined with the the criterion for Riemann integrability. Since $f$ is Riemann integrable, then it is continuous a.e. on $[a,b]$. Now $F$ is differentiable wherever $f$ is continuous.
Answer: If $f$ is Riemann integrable, then it is continuous almost everywhere. The fundamental theorem of calculus guarantees that $F$ is differentiable almost everywhere on $(a,b),$ and hence on $[a,b].$
Comment: I know that if $f$ is continuous then f is Riemann integrable, I thought that the reciprocal was not true, why did you assert that?
Comment: I assumed since you used the terminology "almost everywhere" that you were familiar with Lebesgue's criterion, which states that a function on $[a,b]$ is Riemann integrable if and only if it is bounded and continuous almost everywhere.
Comment: Oh okay, I understood your argument. So you are saying that since $f$ is Riemann Integrable then by the Lebesgue criterion we know that $f$ is continuous almost everywhere which implies by the Fundamental Theorem of Calculus that $f$ is differentiable almost everywhere in $[a,b]$?
Comment: Yup, that's it, except we get that $F$ is differentiable almost everywhere, not $f$ (I think that's what you meant, though)!
Comment: Oh yes, typo mistake. Thank you!


accessing a registry key throws an exception?

Question: I am trying to access a key in the following path in registry on widows 8:

Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run

and I am using the folowing in code to do that:
using (RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default))
{
    using (RegistryKey key = baseKey.OpenSubKey(startUpRegistryPath))

But this throws an exception:

SecurityException: Requested registry access is not allowed.

How do i gain write acccess to that path with C# code?
Thanks!
Comment: you do not have write access or no access?
Answer: Probably need an Application Manifest requesting administrator privileges so your application can access the registry.
<requestedExecutionLevel level="requireAdministrator" uiAccess="true"/>

The UAC disables applications from having rights to specific areas that are deemed "harmful"; among those are the registry and Program Files/Windows directories.
Comment: @user1202434: It's going to, unless you have UAC disabled. The warning is intended to protect the end-user. If you want to short-circuit it through development, run Visual Studio under administrator privileges so, while debugging, you won't be repeatedly confronted.
Comment: thank you, i did try that...but when i launch the exe it always gives a prompt saying " The requested operation requires elevation"
Comment: Just right click on application and choose Run as Administrator, If the exception still thrown, then manifest file can't help.


Replace value in xlsx file using pandas

Question: I have looked at other examples and implemented them, but I'm not getting the right results.
I have several dataframes that looks like this
Player_Name

  0 J.T. Poston

Player_Name

  0 J.T. Poston

I'm trying to change the names to match another excel file I have so I don't have do it manually with excel index. Here is my code.
import json
import pandas as pd
import os

year = 2018

path_to_excel = '/Users/aus10/Desktop/PGA/PGA_Tour_Stats/Tournament_Results_Excel/'+str(year)+''
excel_files = [pos_json for pos_json in os.listdir(path_to_excel) if pos_json.endswith('.xlsx')]

for files in excel_files:

    df = pd.read_excel('/Users/aus10/Desktop/PGA/PGA_Tour_Stats/Tournament_Results_Excel/'+str(year)+'/'+files+'')
    df['Player_Name'].replace(to_replace='J.T. Poston', value='JT Poston')
    print(df)
    writer = pd.ExcelWriter('/Users/aus10/Desktop/PGA/PGA_Tour_Stats/Tournament_Results_Excel/'+str(year)+'/'+files+'', engine='xlsxwriter')
    df.to_excel(writer, sheet_name='Sheet1', index=False)
    df.style.set_properties(**{'text-align': 'center'})
    pd.set_option('display.max_colwidth', 100)
    pd.set_option('display.width', 1000)
    writer.save()

However, when I open up the excel file after running the code the name isn't changed. Is there something I'm missing or a specific way I need to do it because I'm using a .xlsx file instead of .csv?
Comment: I also tried ```df.replace(to_replace='J.T. Poston', value='JT Poston')``` but it didn't work either.
Answer: The important parameter in this case is inplace. Check this question or find the note on this topic directly in the documentation of replace.
It should be enough for you to use this update:
df['Player_Name'] = df['Player_Name'].replace(to_replace='J.T. Poston', value='JT Poston')

Otherwise you are doing replace on the copy, not the original dataframe.
Option with inplace=True should be valid as well:
df.replace(to_replace='J.T. Poston', value='JT Poston', inplace=True)

Replace value in xlsx file using pandas


How to send Private Message using privatemsg_services module?

Question: I am using privatemsg services module to create REST API of privatemsg using Services Module in Drupal 7.
I need to know how to send message and how to reply to a message ? Please tell me URL where i should send POST request and the Body of request ?
Answer: Here you go
To send new  message
Endpoint: http://example.com/services/privatemsg
Content to Send (JSON Format) :
<code>{
   "recipients": "xxx",
   "subject":"xxx",
   "body":"xxxx"
}
</code>
To reply a message for particular chat thread
Endpoint: http://example.com/services/privatemsg
<code>{
"thread_id": "xxx",
"subject": "xxx",
"recipients":"xxx",
"body":"xxx"
}
</code>
Comment: Thank you. It worked but can you please tell me how to get recipients name ? For example I am trying to send message to Krishna and I don't know complete name so when I enter "@kri" it should give me suggestion of user names starting with "kri" ?
Comment: I have asked a new question with more explanation hope I can get answer from you. Here is URL :
http://drupal.stackexchange.com/questions/207180/how-to-load-username-to-send-private-message-using-privatemsg-services-module


CSS rules for webkit based browsers

Question: I have the next CSS code:
<code>#mgheader .letters {
  display: inline-block;
  margin-left: 55px;
  margin-top: -45px;
  position: absolute;
}

#mgheader .letters {
  display: inline-block;
  margin-left: 10px;
  position: absolute;
}
</code>
Now I want to execute the first just in Google Chrome and Safari, and the second in other browsers.
I tried this, but second code seems to be executing always:
<code>@media screen and (-webkit-min-device-pixel-ratio:0) {
  #mgheader .letters {
    display: inline-block;
    margin-left: 55px;
    margin-top: -45px;
    position: absolute;
  }
}

#mgheader .letters {
  display: inline-block;
  margin-left: 10px;
  position: absolute;
}
</code>
How can I fix that?
Answer: The problem is that you're overriding your webkit styling with the non-webkit styling.
Reversing the order should fix this:
<code>#mgheader .letters {
  display: inline-block;
  margin-left: 10px;
  position: absolute;
}

@media screen and (-webkit-min-device-pixel-ratio:0) {
  #mgheader .letters {
    display: inline-block;
    margin-left: 55px;
    margin-top: -45px;
    position: absolute;
  }
}
</code>
You may also want to check that your <code>-webkit-min-device-pixel-ratio</code> fires on all webkit-using devices, but it probably does.
For reference, Cascading Style Sheets are read from top to bottom. The key word is Cascading. If one CSS rule is given before an identical CSS rule, the latter one will take precedence. In your example you were styling specifically to webkit browsers but then overriding it with the general styling rules. Reversing the order means that the webkit styling here will override the general styling (without affecting non-webkit browsers).

CSS rules for webkit based browsers


ignorar cache em determinada pagina .php

Question: estou com um codigo php onde pego um link . so q esse link expira umas 10 vezes por dia, meu codigo verifica se o link expira e tras um novo.
//o arquivo é single.php wordpress
<video id="player" poster="<?php echo $thumb; ?>" controls style="width: 100%; height: 400px;">
<source src="<?php echo $mp4;?>" type="video/mp4" />
</video>

a variavel que armazena a url é $mp4 , ela sempre traz o link correto
so que pra muitas pessoas que visitam o site aparece o link expirado, por conta do cache.
como fazer para esta pagina ou trecho de codigo nao entre em cache de maneira nenhuma?
detalhe. estou usando um plugin de cache para wordpress e cloudflare .
abraçaos
Comment: Coloque parte do código para facilitar entendimento do seu problema
Comment: editei no lugar certo agora... hehe
Answer: Em uma versão resumida:

Usando PHP:

header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.

Usando HTML:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

Isso dirá ao navegador para sempre renovar o cache. Fazendo assim com que "nunca" tenha cache salvo para a página.
Reposta original em: https://stackoverflow.com/questions/49547/how-to-control-web-page-caching-across-all-browsers
Comment: obrigado pela resposta, mas eu ja tentei isso e nao funcionou, sera que algo em htaccess n seria mais indicado? eu estou usando um plugin para cache wordpress e cloudflare.


Why do I get uninitialized constant Spree::Admin::CheckoutsController (NameError) for my decorator?

Question: I have an existing decorator which looks like this:
app/controllers/products_controller_decorator.rb
  1 module Spree
  2   Admin::ProductsController.class_eval do
  3     def update_stock_location
            # my custom code

^ That works.
But when I'm trying to create a new decorator for the CheckoutsController, I get this error:
app/controllers/checkouts_controller_decorator.rb:2:in
`<module:Spree>': uninitialized constant Spree::Admin::CheckoutsController (NameError)
        from /Users/martins/Work/SolidusApp/app/controllers/checkouts_controller_decorator.rb:1:in `<top (required)>'
        from /Users/martins/.rvm/gems/ruby-2.2.3@solidus/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'
        from /Users/martins/.rvm/gems/ruby-2.2.3@solidus/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'
        from /Users/martins/Work/SolidusApp/config/application.rb:24:in `block (2 levels) in <class:Application>'

This is what my Spree::Admin::CheckoutsController looks like:
app/controllers/checkouts_controller_decorator.rb
  1 module Spree
  2   Admin::CheckoutsController.class_eval do
  3
  4     def complete
            # my custom code

I don't understand why it get an uninitialized constant Spree::Admin::CheckoutsController (NameError). The files looks identical to me.
This is the original class:
solidus/api/app/controllers/spree/api/checkouts_controller.rb
  1 module Spree
  2   module Api
  3     class CheckoutsController < Spree::Api::BaseController

Answer: You want Api::CheckoutsController not Admin::CheckoutsController
module Spree
  Api::CheckoutsController.class_eval do
    # ...

Others who find this answer may be looking for Admin::CheckoutController (singular, no 's' after checkout)
Comment: No, I'm sorry, that's not correct. I've updated the post with some excerpts from the original class.
Comment: @martins then you want `Api::CheckoutsController` not `Admin::CheckoutsController`
Comment: THAT'S IT! :-D Can't belive I didn't see that myself. Thanks!
Comment: Please update your answer to reflect the correct solution.


Windows command line mark current directory

Question: On the Windows 7 command line I am in directory A and I will issue a command which will move me to directory B.
I want to quickly go back to A though.
How can I mark A in the command line and then go back to it from B?
I want to do something like:
mark .
cd mark

Answer: You'll want to use the pushd/popd commands:
c:\> pushd c:\future
c:\> cd some\where\else
c:\some\where\else> popd
c:\future>


Guitar not holding tension

Question: I've recently come into a problem with my guitar. Simply enough, I'm having trouble keeping one of the guitar strings in tune.
I've played flamenco guitar for about four years and blues guitar for a further three or so. I've always found a classical guitar to be the best fit for me.
There seems to be a fault with my guitar. The issue is with the high E string. Whenever I attempt to add a new string, I can get the string to a certain tension, before it just drops out and the string detunes several octaves. I then tighten it back up again, only for it to do the same thing. I assume it's because the string is losing tension, only if I keep turning the machine head, eventually the string will snap.
This tells me that somewhere on the string tension is being maintained but the string itself isn't holding the note at all. I can't get it anywhere near the correct note. Has anyone experienced this before and has any solutions?
Answer: I have seen and experienced similar things.  This is typically indicative of a tuning machine head being broken or worn out.  A lot of times the gears will wear out and slip as the tension gets too high, causing the pitch/tension to drop considerably, usually to a place that the tuning gear is capable of holding, though not a couple octaves in my experience.  The only thing about your question that makes me think otherwise is that you are saying that the string will eventually break.  Often times the slipping gear will not allow the string to get up to proper tension, let alone enough to break the string.  It is possible that the stress caused by the tension changing repeatedly is wearing the string to a point of breakage, perhaps encouraged by the nylon material (assuming this is on your Classical guitar).  I would recommend replacing the tuning mechanism.  It may be a good idea to replace all the machine heads, since one getting to a place of improper function will likely indicate that the others are on their way out.
Comment: I expected it was a problem with the machine heads. I'm currently attempting to get a string to the correct tension and I'm keeping my eye on the machine head (not too close because I don't want to lose it). It doesn't appear to be slipping out of place. This is definitely a good analysis though and I will keep it in mind. +1
Comment: I've just had another look, and I'm fairly sure this is the problem. The cog on the outside isn't slipping but I think the peg that the string wraps around is what is slipping. It was a relatively cheap guitar (~£150) so I guess I had this coming. Frustrating when I've just restrung, cleaned and oiled the whole guitar! But thankyou for your answer.
Answer: This usually happens with lower end or cheaper guitars. If it comes with friction pegs (old flamenco guitars) or when the machine head is of low quality or is worn out/broken.
When this happens, the string will lose tension as you play it, as you store it, or even as you tune it (in order of severity). Although it should not change pitch by a magnitude of octave(s)...
The string is likely undergoing cyclic/repeated stresses and fatigue will cause it to lose strength and break.
Try to get new geared machine heads.
Comment: I'll be taking my guitar to store today to see what they say. Will keep you guys updated. Thanks for the answer though, this explains it very well. +1

Guitar not holding tension


Link two content types by mutual value

Question: I have two content types: man and food;
The man content type contains the man's name several more fields and a unique id field created by the serial module.
The second content type is created by the users via an external form.
The results from the form are set as the food content type. One of the fields is equal to the unique id field at the man content type.
My question is:
1. I want to create a view that will show me all the man values, But when the value is clicked, it will lead me to a table that contains all the food content type entries where the unique id in food is equal to the man unique id value.
It so easy to do this in php but I am new to drupal.
Any help of lead will be great.
Answer: Create a views page and list all food results with a contextual filter on the unique id. Give it a path with a wildcard % . In another block or page list the man names. Include the unique id and put that field on top and exclude it from display. Rewrite the output of the name as a link to the views path but replace the wildcard with the token of the unique id.
Comment: Thank you, How do i include the token of the unique id at the views path?
Comment: As I was saying: you add it as a field in your view. Then you have to excluded it and move it to the top: click on the `add` button next to fields and `rearange`

Link two content types by mutual value


adding an error band on a graph when having errors in both x- and y-direction

Question: I have a dataset with x and y values which are both calculated averages from three values and consequently they also have an associated error.
I have about 100 x,y points which I want to plot. Adding both horizontal and vertical error bars is a good method, only there are too many points and it doesn't look nice. In this graph (excel example below) I can see that in some zones the vertical error reaches the furthest and in some zones the horizontal error reaches furthest.
To make a nicer graph I want to use the largest error and make an error area (instead of error bars). But I am quite puzzled by the mathematics and how I should write a script or use a graphical tool to create such a graph.
I would think there should be some kind of solution with a loop going through each x and y value and looking for the min and max for each original xy point, but I couldn't get the maths right to do this.
Is there anybody familiar or sees a solution to this problem, preferably implementable in R.
Answer: A couple of options:
If the main objective is to de-clutter your plot, one option is to assign different colors to the x- and y-error bars and removing the crossbars at the ends of the error bars. Using ggplot you can accomplish this by setting the color aesthetic for each set of error bars individually. Also, use geom_linerange to remove the crossbars for the y-error bars. For some reason, the default behavior for geom_errorbarh is to not plot crossbars.
library(tidyverse)

# simulate some data
df <- data_frame(x = seq(0, 3, length.out = 100)) %>%
  mutate(y = 400 - 25*x^2,
         xerr = .05 + .1*x,
         yerr = .1*y,
         xmin = x - xerr,
         xmax = x + xerr,
         ymin = y - yerr,
         ymax = y + yerr)

# plot using different colors
ggplot(df, aes(x, y)) +
  geom_linerange(aes(ymin = ymin, ymax = ymax)) +
  geom_errorbarh(aes(xmin = xmin, xmax = xmax), color = 'blue') +
  geom_line(color = 'red')

Otherwise, if you truly want a band instead of individual error bars, could plot polygons that encompass the greatest extent of the x- and y-error of each point. In ggplot this is accomplished by defining a path around each x, y pair. Overplotting will produce the band you're trying to create.
I do have some misgivings about suggesting this, however. Presumably the error bars are some sort of confidence interval on the means of x and y. The corresponding confidence region on the joint distribution of x and y is not the rectangle spanned by the error bars but an ellipse.
# calculate path for polygons
mutate(df, group = 1:nrow(df)) %>%
  select(-x,-y, -xerr, -yerr) %>%
  gather(xtype, x, xmin, xmax) %>%
  gather(ytype, y, ymin, ymax) %>%

  # sort rows so that we get rectangles and not bow-ties
  mutate(order =
           ifelse(xtype == 'xmin' & ytype == 'ymin', 1,
                  ifelse(xtype == 'xmax' & ytype == 'ymin', 2,
                         ifelse(xtype == 'xmax' & ytype == 'ymax', 3, 4)
                         )
                  )
         ) %>%
  arrange(order) %>%

  # plot
  ggplot(aes(x,y)) +
  geom_polygon(aes(group = group), fill = 'grey') +
  geom_line(data = df, color = 'red')


Qual é o erro nesse exercício de retorno: Orientação a objetos

Question: public class Matematica {

    /*
     * @param um
     * @param dois
     * return o maior dos dois numeros
     *
     */
    int maior(int um, int dois){
        if( um  > dois) {
            return um;
        }
        else {
            return dois;
        }
      return 0;
    }
}

public class MatematicaTeste {
    public static void main(String[] args) {
    }
    Matematica m = new Matematica();
    int maior = m.maior(10, 20);
    System.out.println(maior); //Da Error Aqui, alguém poderia me dizer porque?
}

Comment: Leandro, só acertei a formatação para mostrar tudo como um bloco de código (http://pt.stackoverflow.com/editing-help). É legal deixar o código com indentação organizada e sem excesso de linhas em branco. É mais fácil para você visualizar a lógica e melhor para quem vai analisar seu código. . . . . Quando fizer uma pergunta, diga exatamente o que e onde não funciona. Mensagens de erro geradas? Saída esperada e saída obtida. Vide [ask].
Comment: Desculpa, sou novo na Zona
Comment: *No problemo*, esqueci de dar as boas vindas ao [pt.so] :) [ps] você é livre para [edit] a pergunta sempre que necessário.
Answer: São dois erros:
1º - Na sua classe Matematica, tire o return 0.
Não tem porque ele existir ali, uma vez que, se um > dois, irá retornar um. Se não, retorna dois
2º - O outro erro é na sua classe de Teste.
A chamada aos métodos está fora do void main.
Tente assim:
public class MatematicaTeste {
    public static void main(String[] args) {

        Matematica m = new Matematica();
        int maior = m.maior(10, 20);
        System.out.println(maior);
    }

}

Sempre que for usar uma classe de teste, coloque as instruções dentro do void main.
Answer: Você colocou os comandos fora da main. Corrigindo isso e retirando o return 0 da função maior(), rodou normal aqui.
public static void main(String[] args) {
      Matematica m = new Matematica();
      int maior = m.maior(10, 20);
      System.out.println(maior);
}


Toggle (show or hide) visibility of content type field in view depending on relationship with other content type

Question: I have a member content type that displays info about a company's member. One of the fields is named member publications, and it's a link to a blog view where the publications of the member (another content type) are displayed.
I want to show or hide the member publications field depending if the member has any publications.
I tried this using the hook_page_attachments using this snippet
function MYMODULE_page_attachments(array &$page) {
  //This line works the first time i open the node page, but not after is cached
  $entity = \Drupal::routeMatch()->getParameter('node');

  if( $entity !== null && $entity->bundle() == 'member'){

    $publications = Drupal::entityQuery('node')
      ->condition('type','publication')->condition('field_publication_author',$entity->id(),'IN')->execute();

    $numberOfPublications = sizeof($publications);

    if($numberOfPublications !== null){
      $page['#attached']['drupalSettings']['MYMODULE'] = [
        'memberPublications' => $numberOfPublications
      ];
    }
  }
}

And then i just show the field or not in js depending on the value attached
let memberPublications = settings.MYMODULE.memberPublications;

        if(memberPublications == 0){
          $('.field--name-field-member-publications').css('display','none');
        }

This works fine the first time i open the member node page, but when i remove all the members publications, the button still shows, the page gets cached and the value doesn't change, when i remove all cache if works again.
Is there a way to have a dynamic field inside a node, that appears or dissapears based in a condition that involves a relationship with another content type? And can it be done without having to reload the cache every time for it to work?
Answer: The hook you are using is only for global attachments. If you have an attachment specific to nodes attach it to nodes:
/**
 * Implements hook_ENTITY_TYPE_view_alter() for node entities.
 */
function mymodule_node_view_alter(array &$build, EntityInterface $node, EntityViewDisplayInterface $display) {
  if ($build['#view_mode'] == 'full' && $node->bundle() == 'member') {
    ...
    $build['#attached']['drupalSettings']['MYMODULE'] = [
      'memberPublications' => $numberOfPublications,
    ];
    // add list tag for the content type publication
    $build['#cache']['tags'][] = 'node_list:publication';
  }
}

This solves most caching issues because nodes are already setup to be cached properly. In this case you need to add a cache tag for the other content type, though, to recalculate the entity query in case a publication is added or deleted.
There are of course other solutions without javascript, but this would be a too broad for an answer. So I'm focusing on why the solution you've found so far doesn't work.
Comment: Danke schön! Do you know where to find other resources to learn more about other solutions to achieve the same result?
Comment: Now that you are in this entity view alter hook you could try to hide the field in PHP.


AxesSubplot has no attriute xticks

Question: Hello I have this code using Python which allows to de some plots :
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax1 = fig.add_subplot(211)
x1 = np.array(np.arange(9))
y1 = x1
ax1.plot(x1,y1)
ax2 = fig.add_subplot(212)
x2 = np.array(np.arange(9))
y2 = x2
locs, labels = ax2.xticks()
ax2.plot(x2,y2)

And the problem is that this line locs, labels = ax2.xticks() does not work. I don't understand why because usually I used this : locs, labels = plt.xticks() and it works.
Do you have a solution with ax which works ?
Thank you very much !
Comment: `locs = ax2.get_xticks()` and `labels = ax2.get_xticklabels()`
Answer: When you are using axes to make plots you have to use ax2.set_xticks() method to set the xticks.
And it returns a single list of xticks' location. So using
locs, labels = ax2.set_xticks(x2)  # I pass x2 as the ticks here.

will raise a ValueError unlike plt.xticks() which returns the locations and labels of the ticks.
You have to use
locs = ax2.set_xticks(x2)

Comment: use `set_xtickslabel`

AxesSubplot has no attriute xticks


dictionary keys() and values() relationship

Question: I have some dictionary d.
k = d.keys()
v = d.values()

Is there a guarantee that k[n] and v[n] are related, for every n?
Comment: can you explain what relationship means according to you?
Comment: What is `n` in your hypothetical? As far as I know, `keys` and `values` don't return anything indexable.
Comment: They are both views over the same dictionary, so they will iterate in corresponding order, if that is what you are asking. You cannot index either of them though.
Comment: But this question really requires details/clarity.
Comment: This looks like XY problem. Could you elaborate what you are trying to do? You know there is also `dict.items()`, right?
Answer: According to this answer on a related question, dictionaries maintain insertion order as of Python 3.6. Here is a link to Guido's decree to "make it so".
Here is an example I did in the Python3 console to test that the relationship for every n is related:
>>> a = dict()
>>> a['yes'] = 'no'
>>> a['blah'] = 'beeper'
>>> a['foo'] = 'bar'
>>> a.keys()
dict_keys(['yes', 'blah', 'foo'])
>>> a.values()
dict_values(['no', 'beeper', 'bar'])
>>>

Edit: After reading some of the comments above, you would need to make these into lists to access them as indexes. So following that from the previous example:
>>> keys = list(a.keys())
>>> keys
['yes', 'blah', 'foo']
>>> values = list(a.values())
>>> values
['no', 'beeper', 'bar']

Answer: Yes. Corresponding entries from .keys() and .values() represent the same key/value pair within the dictionary. (In older versions of Python, the orders may vary if you add or remove items, but they correspond if no such modifications are made between calls.)
d = {"answer": 42, "unlucky": 13, ...}
assert list(d.items()) == list(zip(d.keys(), d.values()))

This was made explicit in previous versions of the Python documentation. In recent versions of Python, where items retain their insertion order regardless of changes to the dictionary, they apparently didn't feel it needed to be made explicit, but it's still true.
Python dictionary: are keys() and values() always the same order?
Comment: I think [the docs](https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects) still make this fairly explicit: *"Keys and values are iterated over in insertion order. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). Another way to create the same list is pairs = [(v, k) for (k, v) in d.items()]."*
Comment: @kaya3 Aha, they changed the wording enough that my haphazard "Find in Page" didn't find it.  :-)
Answer: a = dict()
a["sas"] = 10
a["ase"] = 90
a["ing"] = 98
print(a)

And the keys on its own!
print(a[0])
print(a[1])
print(a[2])


Live web server migration

Question: I need to replace an aging webserver which runs a busy website. I have the new hardware up and running, all software is installed. There's only one problem left where I'm looking for a solution:
When I change the A record for the
   domain in DNS, it takes a while for
   the change to propagate through the
   internet due to DNS caching. During that
   time, some users will hit the new
   server, and some will hit the old
   one, leading to data inconsistencies because there are now two databases.
   How can I switch everyone over
   instantly? I do not run the DNS server and cannot change anything but the A and CNAME records, but I could setup my own if that helps.
I can probably have an hour or two of downtime when moving overnight.
Thanks, Simon
edit: Thank you for all your answers. I'm accepting SmallClanger's answer because it's a viable solution, and I'm upvoting Brian because his answer gave me a new idea: Follow SmallClanger's solution up to the database migration, and then replace the old apache with an HTTP proxy which proxies all requests to the new server. I'd configure the proxy to address the new server by IP address, and it does not involve a temporary subdomain which might (despite the 302 code) end up in some bookmark directory, social network or browser cache.
Comment: the way the questions is formulated suggests that the old and the new server are not 'side-by-side' - but for clarification: you really need to switch DNS entries rather than re-assigning the old server's IP address to the new one?
Comment: These are two dedicated servers with two different providers, so no, they are not side-by-side and I cannot take IP addresses with me.
Answer: You could configure the old web server to redirect all requests to the new IP. This can be done with mod_rewrite in apache.
Answer: The fundamental problem you have is of maintaining database consistency during the switch. To have zero downtime, you'll have no choice but to set the two servers up in an active/active cluster. (even assuming, for the moment, that the cluster setup would involve no downtime itself, which is a bit of a stretch.).
Given that you can't change the TTL, you best step is to minimise downtime:

Set the new site up on a second domain name (eg: www2.example.com), but make it answer to www.example.com, too. Point the DNS for www2 at the new server only.
Have the site files replicated and locked down from edits on both sides.
Then in an advertised maintenance window, replace the live site with a 'down for upgrades' notice.
Sync or copy the database across as required, and then start the new server.
Then (and only then) make your DNS changes to the www record.
Replace the old site config with a simple 302 redirect to www2.example.com
Wait for the full TTL to expire (and then a bit) before taking the old server down.

This will make sure all traffic goes to the new site during the DNS propagation,  regardless of which server they go to initially, though it assumes your site is capable of being served from multiple domain names at the same time.
For a single-server LAMP stack (if that's what you've got), then this is your route to minimal (but not zero) downtime.
Answer: You could lower the TTL of your zone one or two days before the migration to a small value. After you've changed the A resource record you can raise the TTL again to its old value.
Answer: You  have to  migrate  first   all data files on the new server (apache and mysql files)  . After that  when  you have 2   houres to stop server     you can synchronize all datafiles  with rsync.
LIke that  rsync  -avz  /var/www/sites (old-server)   user@hosts2:/var/www/sites  (new-servers)    . And  export import all datafiles on sql server from server 1 to new server . Then swich server 2
and stop old server   if  you have some problem start again server 1  and repear  errors on newserver .
But before  you start new server check for  errors  make own test.
Answer: lower the TTL, and put up under maintance sign on old page?
Answer: I thing  TTL is bad idea. Becouse  if  old server is alive  , some user  meybe will connect on  old server and another users meybe will use new server. If  you really have 2 hours    use syn and export inport all from sql to sql then swich on new server Am sure all will be  fine with mu solutions
Answer: You could use the old server IP for your new server.

Live web server migration


Passing a bool variable as a parameter to a function expecting a BOOL parameter in Visual Studio 2019

Question: Take this sample code:
void CChristianLifeMinistryDiscussionsDlg::SetControlStates()
{
    if (m_pEntry == nullptr)
        return;

    bool bClass1 = false, bClass2 = false;
    m_pEntry->GetAuxiliaryClasses(bClass1, bClass2);

    m_cbBrothersC1.EnableWindow(bClass1 ? TRUE : FALSE);
    m_cbBrothersC2.EnableWindow(bClass2 ? TRUE : FALSE);

}

EnableWindow expects a parameter of type BOOL. It is never clear to me if it is acceptable to just pass the value of my bool variable in this situation.
Answer: A BOOL is a type alias for an int. A value of type bool can be implicitly converted to a value of type int. This is called integral promotion, and well defined: The value false becomes 0 and the value true becomes 1.
Passing a value of type bool to a function that expects an argument of type BOOL (i.e. int) is safe and well defined.


Do I need to give a complete copy of my site's source code to a themer?

Question: I want to get my sites themed from expert themers ( for example at Freelancer etc). I need node, views etc be themed along with site look and feel.
I've done little themeing till now and I tested with my site source.
What I want to ask is it necessary to give complete site source code to the themer which i don't want to do? What minimum they'd need?
Answer: The minimum they need depends on what you are having them theme.
Basically they have to have everything they need to do their job.
If you exclude something that affects any visual part of the site it could impact their ability to do their job.
If they are making the whole theme for your site I feel you really should give them everything, because if you don't it is possible that some things will not get themed.
If I was the one implementing the theme and I was not given the whole code I would definitely specify that any problems with the theme that relate to not having all the parts are not covered by warranty.
In the end though it depends on your specific site and what you are having themed.
Maybe on your site there are pieces of functionality/code that could be excluded without impacting the parts of the site being themed.
If your worry is them seeing your code, because there are specific things regarding your code that are very sensitive then you either need to find a themer you can trust, and have them sign legal NDA agreements or whatever else is required.
If you are worried about them doing bad things to your code, use version control.
Have everything in version control before you give it to them so that when you get their work back, you can see exactly what has been changed, so if they are changing things they shouldn't be you can more easily know about it.
You could also try to get someone to review their work (or you review it yourself if you have the knowledge).
Another thing you could do is host the site somewhere on the internet where the themer can work on it, but only give them access to the theme directory. So they are allowed to FTP to the theme directory only, and not have access to the rest of the site, but they still get to use the fully functioning site.
The harder you make things for them though, the more chance you have of getting an inferior result or having the work take longer than expected.


CNN training in bfloat16

Question: Are there any efforts so far for training CNNs end-to-end with bfloat16 format? especially the convolution part, i.e. both multiplication and addition is done in bfloat16. Can this scale to large datasets such ImageNet? Intel has a published white paper about supporting bfloat16 in their next-generation FPGAs, where they claim that accumulating in FP32 format is essential to avoid losing accuracy on an application level. Would people building custom hardware for training have to stick with the FP32 accumulation?
Answer: Most robust low-precision training frameworks rely on a hybrid of low-precision and high-precision calculations. I think the jury is still out on whether or not you can consistently train networks at purely lower precision (and achieve comparable accuracy). It becomes especially difficult if you try to train these networks on different hardware, because of the different ways in which precision is treated and optimized for.
Perhaps you're familiar already with NVIDIA's TensorRT framework, designed to train networks in 8 and 16 bit precision. The "catch" is that it starts with a 32bit trained network and fine tunes it in lower precision. However, this tends to be considerably more robust than training in 16bit precision from scratch.

CNN training in bfloat16


Prove that $\lim_{x \to a} x^4 = a^4$ using epsilon-delta definition

Question: This is an exercise in Spivak's calculus:

Let $f: \mathbb{R} \to \mathbb{R}: x \mapsto x^4$. Prove that $\lim_{x \to a} f(x) = a^ 4$

Is my proof correct?
Proof: Let $\epsilon > 0$. If $|x-a| < 1$, it follows that $|x| < 1 + |a|$
and hence: $$|x^3 + x^2a + xa^2 + a^3| \leq |x|^3 + |x|^2|a| + |x||a|^2 + |a|^3 $$$$< ((1+|a|)^3 + (1+|a|)^2|a| + (1+|a|)|a|^2 + |a|^3$$
Choose $\delta =  \min\left\{\frac{\epsilon}{(1+|a|)^3 + (1+|a|)^2|a| + (1+|a|)|a|^2 + |a|^3},1\right\}$
Then, for $x \in \mathbb{R}$ satisfying $0 < |x-a| < \delta$, we have:
$$|x^4-a^4| = |x-a||x^3 + x^2a + xa^2 + a^3|
<|x-a|((1+|a|)^3 + (1+|a|)^2|a| + (1+|a|)|a|^2 + |a|^3)$$
$$< \delta((1+|a|)^3 + (1+|a|)^2|a| + (1+|a|)|a|^2 + |a|^3) \leq \epsilon$$
Hence, the result follows.
Comment: It's just fine.
Comment: Yes, that works.  A little precise but ... why not?
Comment: Isn't it the goal of these exercises to be precise?
Comment: The goal is to be rigorous and clear.  Showing that $\delta$ exists in a clear and concise way may be better than finding the largest possible $\delta.$
Answer: As mentioned in the comments, while this is correct, in such contexts, simpler bounds are generally preferred over sharp ones. So for instance, in this case, you can do
|(a+h)4-a4| = |4a3h+6a2h2+4ah3+h4|
From here, you can replace all the coefficients with 6. If a<1, you can replace each  of its powers by 1, and if a>1, you can replace each of its powers by a3. We can assume h<1, so we can replace all of its powers by h. Hence,
|(a+h)4-a4|<|6*max(a3,1)h|
We can therefore take $\delta$ to be any number < $\epsilon$/[6*min(a3,1)]


Httpd Directory read permissions only issue

Question: In my scenario ,I need the 'httpd' directory in '/var/log/' to be readable by the users in 'devs' group (Amazon Linux 2) Could anyone guide me how to accomplish this?
We have a few developers who maintain the system and I want them to easily read the log files in /var/log/httpd without needing root access.
can this will help ??
chmod -R go+r /var/log/httpd

or chmod -R go+rX /var/log/httpd
or do i need to go with :
chmod 644 /var/log/httpd

chgrp -R apache /var/log/httpd
chmod 02750 /var/log/httpd
chmod 0640 /var/log/httpd/*
create 0640 root apache

ls
[root@ip-10-0-10-165 httpd]# ls -la
total 48
drwx------ 19 root   devs   4096 Apr  3 03:42 .
drwxr-xr-x 11 root   devs   4096 Apr  8 07:45 ..
-rw-r--r--  1 root   root      0 Feb 15 14:55 access_log
drwxr-xr-x  2 root   devs     41 Mar  1 20:44 u1-dev.qwerty.com
-rw-r--r--  1 root   root   1648 Apr  3 03:42 error_log
-rw-r--r--  1 root   root    883 Mar 13 03:41 error_log-20220313
drwxr-xr-x  2 root   devs     41 Mar  1 20:44 u4-dev.qwerty.com
drwxr-xr-x  2 root   root     41 Mar  1 20:44 langs.qwerty.com
drwxr-xr-x  2 root   devs     41 Mar  1 20:44 u8-dev3.qwerty.com
-rw-r--r--  1 root   root      0 Feb 15 14:55 ssl_access_log
-rw-r--r--  1 root   root    314 Apr  3 03:42 ssl_error_log
-rw-r--r--  1 root   root    157 Mar  6 03:50 ssl_error_log-20220313
-rw-r--r--  1 root   root      0 Feb 15 14:55 ssl_request_log
drwxr-xr-x  2 apache apache  253 Apr  3 03:42 www.qwerty.com
drwxr-xr-x  2 root   devs     41 Mar  1 20:44 u13-dev.qwerty.com
[root@ip-10-0-20-173 httpd]#

How to modifying those permission set? what is the best approach here ?
Answer: You can use acl for this directory and grant permissions for devs group. For example:
setfacl -m g:devs:rx httpd/

You can set file access list for a directory. In your example you have httpd directory with permissions set for user/group root only.
# ls -la| grep httpd
drwx------   2 root     root        4096 Apr  8 10:11 httpd

You can check that this directory have no acl list:
getfacl httpd/
# file: httpd/
# owner: root
# group: root
user::rwx
group::---
other::---

We set permissions for the devs group with read and execute permissions:
setfacl -m g:devs:rx httpd/

After setting the permissions, it will look like this:
getfacl httpd/
# file: httpd/
# owner: root
# group: root
user::rwx
group::---
group:devs:r-x
mask::r-x
other::---

Note the extra sign (+) about any existing acl on the ls command.
# ls -la| grep httpd
drwxr-x---+  2 root     root        4096 Apr  8 10:11 httpd

It might be a good idea to repeat the setfacl command with the -b switch to set the default permissions. I usually do that.
-d, --default
           All operations apply to the Default ACL. Regular ACL entries in the input set are promoted to Default ACL entries. Default ACL entries in the input set are discarded. (A warning  is  issued
           if that happens).

Regards
Comment: just for better understanding , can you describe a bit with example ?
Comment: I expanded the answer above.
Comment: KuchnMar ,  setfacl -m g:devs:rx /var/log/httpd , will grant my  'devs' group to provide the desire permission without root access right  ?                                                  [root@ip-10-0-10-165 httpd]# getfacl /var/log/httpd
getfacl: Removing leading '/' from absolute path names
# file: var/log/httpd
# owner: root
# group: devs
user::rwx
group::---
other::---
"
Answer: According to how you tagged the question, you are using a Redhat-style environment. Assuming you are using the stock Apache httpd installation, you are probably, behind-the-scenes, dealing with logrotate. Out of the box, logrotate executes daily out of /etc/cron.daily. It will move your current log files out of the way, create new ones and restart httpd such that it will begin to use the newly created, empty log files.
Check /etc/logrotate.d/httpd. For example, the stock version shows:
/var/log/httpd/*log {
    missingok
    notifempty
    sharedscripts
    delaycompress
    postrotate
        /bin/systemctl reload httpd.service > /dev/null 2>/dev/null || true
    endscript
}

If you add a line like this within the curly brackets, logrotate will properly rotate and re-create your log files with the correct owner and group memberships:
    create 0640 root devs

This instructs logrotate to create the new log files with root as the owner, devs as the group, with permissions being owner read/write and group read.
You can then set your httpd log directory with permissions and ownerships like so:
chown root:devs /var/log/httpd
chmod 0750 /var/log/httpd

For the first day, you may also want to manually set the permissions on the log files and logrotate will pick up on the following days:
chown root:devs /var/log/httpd/*log
chmod 0640 /var/log/httpd/*log

You can get fancy with ACLs as demonstrated by @KuchnMar above, but this solution keeps things simple and compatible across various *nix and filesystem types.
This may be similar on a Debian-style host, but your logrotate configuration file may be called apache2 instead.
More information can be found here:

logrotate: https://linux.die.net/man/8/logrotate
mod_log_config: https://httpd.apache.org/docs/current/mod/mod_log_config.html


Is custom coding faster than Rules when reacting on user creation?

Question: I'm granting an avatar to the users on my website, based on their gender (cf. this answer). I've been able to achieve this both programatically and with 3 Rules.
This is my custom module:
<code>function custom_user_presave (&$edit, $account) {
    $tid = $edit['field_geslacht']['und'][0]['target_id'];
    if ($account->is_new OR !isset ($account->roles[3])) {
        $avatar = taxonomy_term_load($tid);
        }
        else {
            $avatar = taxonomy_term_load(8);
        }
    $edit['field_avatar']['und'][0]['fid'] = $avatar->field_avatar['und'][0]['fid'];
    $edit['field_avatar']['und'][0]['width'] = $avatar->field_avatar['und'][0]['width'];
    $edit['field_avatar']['und'][0]['height'] = $avatar->field_avatar['und'][0]['height'];
    $edit['field_avatar']['und'][0]['alt'] = $avatar->field_avatar['und'][0]['alt'];
    $edit['field_avatar']['und'][0]['title'] = $avatar->field_avatar['und'][0]['title'];
}
</code>
This is one of my exported rules (the second only differs in the action part and the third one checks whether the user has a certain role):
<code>{ "rules_avatar" : {
    "LABEL" : "Avatar",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "avatar" ],
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_insert" : [], "user_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_geslacht" } },
      { "data_is" : { "data" : [ "account:field-geslacht" ], "value" : "Man" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "account:field-avatar:file" ], "value" : "35" } }
    ]
  }
}
</code>
I'm wondering which method is the fastest/most efficient. Can you help me?
Comment: Next time, you just need to edit your original question when it is on hold (see http://meta.stackexchange.com/questions/10582/what-is-a-closed-or-on-hold-question).  I am going to delete the other one.
Comment: @MPD: Okay, I was about to do that too. :) I don't like to edit questions on hold too much, because most of the time, they aren't reopened again.
Answer: I wouldn't focus too much on speed in situations like this because it's extensibility you will care about as the site grows in function. While your custom code is probably "faster" it's not the measure you should be deciding by since it'll be nanoseconds you're talking about and any good caching strategy will nullify most of that concern.
But to answer your question, your code would likely be faster especially if you're not defining as many hooks as the Rules module.
However, I'd advise using rules for the following reasons.

Rules are exportable
Rules are integrated with all the "big" modules out there.
Never program something you can borrow. :)

Hope this helps.
Comment: I agree with your answer in general, but the the fact that "Rules are exportable" is not a reason to choose Rules over custom code. A custom module doesn't even need to be exported, since it's code already, and deploying a custom module is usually even easier than export-and-feature-revert.
Comment: Thanks, that will certainly help! I'd like to see some more opinions, but I'll upvote your answer it the meantime.
Comment: No problem. Happy to contribute! Thanks for the upvote. :)
Comment: I'm a best practices snob but you're not wrong, for sure.
Comment: @marcvangend: Feel free to post a different answer if you don't agree! :)
Comment: @Jeroen I definitely would, but as you can tell by the first two words of my comment, I *do* agree with the answer. I only added some nuance to the reasoning behind it.
Comment: @marcvangend: That's okay. Thanks for your extra information!


Composer shows "nothing to update" but there is a new version of the module

Question: I am managing a Drupal 8 site in Composer.  Commerce 2.0 was just released; I currently have 2.0-rc2 installed on my site.
This is my composer.json
"drupal/commerce": "^2.0@RC",

"minimum-stability": "dev",
"prefer-stable": true,

To update, I ran composer update drupal/commerce --with-dependencies, which gave me this result:
Gathering patches for root package.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating optimized autoload files
Warning: Ambiguous class resolution, "Drupal\Component\Utility\Random" was found in both "$baseDir . '/web/core/lib/Drupal/Component/Utility/Random.php" and "/mnt/c/Users/x/d/mysite/vendor/drupal/drupal-driver/src/Drupal/Component/Utility/Random.php", the first will be used.
Removing packages services cache file:
/mnt/c/Users/x/d/mysite/vendor/drupal/console/extend.console.uninstall.services.yml
Creating packages services cache file:
/mnt/c/Users/x/d/mysite/vendor/drupal/console/extend.console.uninstall.services.yml
> DrupalProject\composer\ScriptHandler::createRequiredFiles

So Commerce does not get updated to 2.0 (I already updated all the dependencies to their latest versions.)
I thought it might be a caching issue so I ran composer clearcache and then attempted to update commerce again, but I got the same result (nothing to update).
I thought it might be an issue with the composer module list being out of date, but Commerce 2.0 was released more than 48 hours ago.  So what can I do to get composer working in this case?
EDIT
My repo is based on the Drops 8 Composer repo from Pantheon, which is in turn based on drupal-composer/drupal-project.
Deleting the /vendor directory and running composer update gives me this error:
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Changing composer.json to "drupal/core": "^8.4@RC" "symfony/css-selector": "~3.2" also results in the same error.
But, running composer install or running composer update drupal/modulename allows me to install the site and update individual modules (except Commerce) without any problem.
Comment: Is it based on the `drupal-composer/drupal-project`? I had some issues as well (though not the same output as yours), but I've managed to get it to work by updating the require section to include `"drupal/core": "^8.4@RC"`, `"drush/drush": "~9.0",` and set `"symfony/css-selector": "~3.2"` in require-dev.
Comment: Try this, delete the vendor directory `rm -rf vendor/` and then run `composer update`
Comment: @NoSssweat  It didn't work, unfortunately.  Got a "Your requirements could not be resolved to an installable set of packages."
Comment: @Neograph734 It's based on a Pantheon repo that is in turn based on `drupal-composer/drupal-project`.  I tried what you suggested but then I get Your requirements could not be resolved to an installable set of packages."
Answer: Thanks to @Neograph734 for pointing me in the right direction.
I needed to require Drupal 8.4-rc2 and drush 9, and then Commerce 2 arrived automatically.
Drush 9 appears to be a requirement for the 8.4 core update.


Remove features without lose functionality

Question: I'm working on a project where in the past was added a lot of features and was did in a way where right now a lot of them has a lot of circular dependencies and conflicts.
I want to start again, delete all the features, create new ones and avoid to each of them make conflicts with another.
My question is, how i can "remove" the features but not lose the changes to they did it on the project?, in other words how i can move the configuration "in code" into the database? for i able to remove the feature but preserve the configuration in the site?
I'm using Drupal 6
Answer: You can use the Features Tools Module to disable a features module while leaving the functionality that was provided by the feature in place.
Instructions provided by autopoietic here.

First BACKUP YOUR DATABASE
backup your feature (files) if you would like to use it again.
Once installed, go to the 'recreate' page for a feature, uncheck all of the features
  components
In order to save the elements to the DB you need to go to the admin/build/features/unlink
  page, check the element you need to import and submit.
Now click on the 'Safe autocreate' button to recreate and replace the feature with an empty
  version.
You can now disable the module without affecting your site configfuration.

These instructions note that "if you are using D6 there is an extra step" which I have added (step 4 above).


Prove $x^{p-1}−1=(x−1)(x−2)···(x−p+1)$ in $\Bbb Z_p[x]$.

Question: If $p$ is a prime, prove that $(x − a)\mid (x^{p−1} − 1)$ in $Z_p[x]$ for all nonzero $a$ in $Z_p$. Hence prove that
$x^{p-1}−1=(x−1)(x−2)···(x−p+1)$ in $Z_p[x]$.
I originally thought that I could prove these using the Rational Roots Theorem but I couldn't figure out how to do it. Any help would be great, thank you in advance!
Answer: The little fermat theorem implies that $a^{p-1}=1$, this implies that $a$ is a root of $x^{p-1}-1$, if you divide $x^{p-1}-1$ by $x-a$ you obtain $(x-a)p_a(x)+b$ this implies $b=0$.
The polynomial $(x-1)...(x-p+1)$ divides $x^{p-1}$ and have degree $p-1$ the euclidean division implies that $(x-1)....(x-p+1)=c(x^{p-1}-1)$ since the coefficient of degree $p-1$ of $x^{p-1}-1$ and $(x-1)...(x-p+1)$ is $1$ you deduce that these polynomials are equal.
Comment: It is not true in general rings that if $\,a,b\,$ are roots of $\,f(x)\,$ then $\,(x-a)(x-b)\mid f(x),\,$ so this requires *proof* in this special case - see the Remark in my answer.
Answer: Hint: Prove that for $f\in\Bbb{F}_p[X]$ you have $\frac{f}{X-a}\in\Bbb{F}_p[X]$ if and only if $f(a)=0$.
Answer: For the second part of the problem, use the result from part one which implies $x^{p-1}-1$ has the $p-1$ roots $1,2,\dots,p-1$. After this, use the factor theorem coming from the fact that $\mathbb F_p$ is a field, and then, consider the degrees of the decomposition you end up with.
Comment: Do you mind elaborating on the second part (using the factor theorem) @YiFan?
Answer: Hint $ $ By little Fermat and the Lemma below $\,x^{p-1}-1 = (x\!-\!1)(x\!-\!2)\cdots (x-(p\!-\!1))g(x)\,$ so comparing degree and lead coefficient shows $\,g(x) = 1.\,$ [Beware: it is not generally true that if $\,a\neq b\,$ are roots of $\,f(x)\,$ then $\,(x\!-\!a)(x\!-\!b)\mid f(x),\, $ so it requires proof - see the Remark below].
Lemma $ $ If $\,f(a_i)=0\,$ and $\,a_i-a_j\,$ is cancellable for $\,i\neq j\,$ then $\,(x\!-\!a_1)\cdots(x\!-\!a_n)\mid f(x)$
Proof $ $ Induct on $\,n.\, $ If $\,n=1\,$ then $\,f(a_1)=0\,\Rightarrow\, x\!-\!a_1\mid f(x)\,$ by the Factor Theorem. Else by induction $\, f = (x\!-\!a_1)\cdots(x\!-\!a_{n-1}) g(x)\,$ so $\,0 = f(a_n) = (a_n\!-\!a_1)\cdots(a_n\!-\!a_{n-1}) g(a_n)\, $ thus $\, g(a_n)=0$ by cancelling all $\,a_i-a_j,\,$ so $\,x\!-\!a_n\mid g(x)\,$ by the Factor Theorem, yielding the claim.
Remark $ $ In a field (or domain) we have $\,c\,$ is cancellable $\iff c\neq 0\,$ so the above hypothesis reduces to $\,a_i\neq a_j\,$ if $\,i\neq j,\,$ i.e. the $\,a_i\,$ are distinct roots. The cancellability hypothesis is necessary, e.g. over $\,\Bbb Z_{\large 8}\!:\  x^2-1\,$ has roots $\,3,1\, $ but is not divisible by $\,(x\!-\!3)(x\!-\!1).\,$ Note $\,3-1 = 2\,$ is not cancellable since $\,2\cdot 4= 2\cdot 0\,$ but $\,4\neq 0,\,$ so the Lemma does not apply.
Alternatively we could use  $\,x-a\,$ and $\,x-a'\,$ are nonassociate primes if $\,a\neq a',\,$ so since $\,x^{p-1}-1\,$ is divisible by those nonassociate primes it it is also divisble by their lcm = product.
Comment: See also the [Bifactor Theorem.](https://math.stackexchange.com/a/2049882/242)


Is more than a virtual dedicated server needed initially for a user-generated video sharing site?

Question: I'm building a hybrid flash and HTML5 user-generated video site. I'm a novice but have some more knowledgeable developers helping me. I've bought a virtual dedicated server with 30 GB of disk space and 500 GB of bandwidth. My expectation is that we'll get 1000 videos uploaded and 10,000 downloaded year 1. Each video will be 3-5 minutes long - not high def for the most part. We don't have much money to spend. Do I need to get a storage solution like S3 and a content delivery network like Cloudfront or will I probably be ok that first year just using the VDS?
Answer: Ok, let's work this out.
You don't mention what codec or bit-rate you're going to use so I'm going to assume you pick something like H.264 at around 1.5Mbps (as that's what I do for SD content incidentally).
So 1.5Mbps works out at around 187.5KBps, multiply this by 60 for 60 seconds in a minute, then by 4 for the average between a 3 and 5 minute clip means each played back clip will need a bare minimum of 45MB of downstream bandwidth each - not including any signalling or general site usage (catalogue, front page etc.).
Multiply this by your 10k playback estimate and you get 450GB per year or, if extremely evenly distributed across the year, 35.5GB per month.
Now you don't state what your 500GB allowance really is, is that per month? if so then you should be fine as you'll be using less than 10% of your allowance but be aware that your estimate may be very wrong, what if 10M users come to your site, what are your plans then? also the other thing to consider is that your users WON'T be smoothly distributed across the year, you'll see huge bubbles of super busy periods and then nothing at all - you need to have worked this out.
Given you have no money I'd go ahead with what you have but you need to start designing your next phase, where do you go once this server is overused, how do you migrate to this next phase, where is your data at this point, how do you ensure catalogue coherency, how will you load-balance etc.
Video delivery is just about one of the most complex IT problems we face today, I know, it's my job, and I'm pleased you're giving it a go but you need to think about tomorrow today.
Comment: Your points are well taken. I appreciate it and will look into S3 and Cloudfront as phase 2 options. I neglected to mention that we're reencoding the videos, will use ffmpeg and will offer them in HTML5 and Flash. Does that impact the calculus?
Comment: the reencoding bit makes no difference as that's CPU rather than bandwidth intensive.
Answer:
I've bought a virtual dedicated
  server

Lets stick to reality here. You RENT a virtual server. No buy. Nothing dedicated here, either.
What you say is like saying "I purchased a dedicated taxi for a trip".

My expectation is that we'll get 1000
  videos uploaded and 10,000 downloaded
  year 1. Each video will be 3-5 minutes
  long - not high def for the most part.
  We don't have much money to spend. Do
  I need to get a storage solution like
  S3 and a content delivery network like
  Cloudfront or will I probably be ok
  that first year just using the VDS?

Well, depenmds totally on what you do on the server and how the load distributes. If you reencode you may be in for a bad surprise CPU wise.
500gb a month (that is per month, right)? can and can not be good enough - depends on how large a video file is (which you do not say - but it depends on resolution and bit rate, which you possiobly control). You also dont say whether you can up the VPS or not.

If you do not reencode CPU will likely not be an issue.
If you do you are dead when people mass upload unless you can handle that and people are willing to wait.
Bandwidth should be easy to scale. As should be RAM, CPU for low CPU cenarios (no reencoding). VPS can go quite high, thoug not all providers support that.

Finally: noone cares what money you ahve or not. Saving is nice, bubut if you can not run a site, you can not.
In general: a site like you describe is not even worth metioning from the CPU / Memory point of view, bandwidth may be. Very small. 10.000 downloads a year, over 365 days are on average 27.4 per day. About 1.1 per hour. Say peak is 5 times - that is 6 downloads per hour. The server may send you an email about boring jobs and falling asleep.
OTOH make that bleu ray level discs which you want to reencode and you arein for pain CPU wise.
You have to say - our crystal balls are broken.
Comment: +1 - my crystal ball went on strike the other week, something about being insensitive? I dunno I wasn't listening.
Comment: Thank you for the advice. We do reencode and we can upgrade the virtual server easily. With regard to reencoding, given that will be necessary, how would that impact our needs? In other words, what else do I need to do to account for the reencoding? Thanks in advance for your help!