Is the meter of this bar 3/4 or 6/8?

Question: Sorry if this is a really basic question but I'm really confused about the difference between 3/4 and 6/8 and was hoping to get some explanation about this bar in particular:

This bar can be read both as 3 quarter notes or 6 eighth notes, so I'm not sure whether it is in 3/4 or 6/8.
Appreciate any help, thanks!
Answer: From the notation alone we can already see that this is at least thought to be 3/4 by the composer. Even more in 3/4 the rhythmic distrubution is quite uncomplex. If we were to take this as 6/8 this would become much more complicated, as you can see here:

I'd say the 6/8 one would be quite hard to perform ...
Answer: Simply put: 3/4 is three quarter-note beats and 6/8 is two dotted quarter-note beats. ...Leaving aside the variety of exceptions....
The way to know (presume) this bar is 3/4 is the way the beams are placed. They clearly delineate three beats. Were the bar intended as 6/8, it would be written as a dotted quarter-note tied to a sixteenth note. That sixteenth note would be beamed to a sixteenth note, an eighth note tied to another sixteenth, and a final sixteenth, as shown below. Note how the beaming divides the bar into 2 halves.

The difference between 3/4 and 6/8 is a common topic here. For example:

Does 3/4 time signature differ from 6/8?
How can you tell the difference between 3/4 time and 6/8 time? Or 3/2 time and 6/4 time?
Why is 3/4 a simple meter while 6/8 is a compound meter?

Note
Elaine Gould's Behind Bars does not directly address this situation, and the closest examples could be interpreted either way in terms of using a tie versus a dotted note. However, IMO, the dotted version (see @Lazy's answer) is preferable.
Comment: I don't have *Behind Bars* hand, but I'll double check on whether the center tie or a dotted eighth should be used, and update as appropriate.
Comment: My money's on the dot.
Answer: Sometimes taking one bar in isolation isn't enough to decide what the time signature is (or should be - take 'America').
However, as a basic premise, the fundamental difference is the feel. 6/8 is duple time, so can be counted both as a six time, or a slower two. And will be written as such, to help the reader. So, the bar can be seen to be split into two equal halves, each containing three quavers. 3/4 time will be written in values equal to three separate parts - three crotchets, so there won't be a  sectioning into two halves.
Since this example is obviously split into three separate crotchet parts, so to speak, then it will come under the 3/4 time signature 'ruling' rather than 6/8, which it certainly doesn't align to.
Comment: If someone were asked to transcribe an expressionless recording of a piano playing the vocal melody for the chorus of "America", I don't think anything within that part would reveal whether it should be 3/4, or alternating 6/8+3/4, since both interpretations would make sense.  Lyrics come to the rescue, though, since "I want to BE in a-MER-I-CA, SO much to SEE in a-MER-I-CA" fits normal speech patterns much better than would "I want TO be IN a-MER-I-CA, SO much TO see IN a-MER-I-CA".
Comment: "Lyrics come to the rescue..."? I come to rescue the lyrics! "I like to be in America,
O.K. by me in America". They are **already** in America :-)

Is the meter of this bar 3/4 or 6/8?


JavaScript no meio do código?

Question: Gostaria de saber em que situações práticas um script JS seria escrito no meio do código HTML e não declarado num arquivo à parte no head ou no fim do body.
Obrigado desde já.
Comment: Às vezes eu uso apenas por questões de praticidade, para facilitar a manutenção. Se é bom ou ruim, nunca procurei saber. Em outros casos quando envolve back-end, onde eu quero executar um script numa determinada posição dependendo de uma variável back-end, o que eu não conseguiria fazer em um .js a parte.
Answer: eu conheço por exemplo o EJS, é um engine do JavaScript e serve para quando você quer trazer dados do back end para o front end, e exibir em um campo, label, entre outros. Isso você consegue fazer no meio do HTML.

JavaScript no meio do código?


How to edit the color of attribute values in XML Doc comments?

Question: I've made my own Visual Studio theme in the 2013 version and now I'm migrating to 2015. Since the font and color settings on XML Doc comments changed, I had to reconfigure the color for the XML comments. However, the color is not applied for the attributes values.
Here we can see it's black but supposed to be green.

Here's what the options look like:

Pretty much all the options starting with "XML" are set to green, so I suppose there's another manipulation to do ?
Answer: The value you are looking for is under Tools -> Options -> Fonts and Colors -> Identifier. This will unfortunately change all class names, methods names, and variable names. You cannot change the attribute color without on its own. Please see Visual Studios for a full list of how the items relate to color changes.
Answer: I know this is an old question, but I fell here and so will more people.
The selected answer is correct. However, there's an easy way to "have your cake and eat it too!" i.e., have that XML Doc Attribute whatever color you want without surrendering color options for the other items.
The Identifier indeed sets the XML Doc Attribute color. However, you can use a free extension, such as SemanticColorizer (at VS Marketplace) which allows you to override the rest of your code item's colors, as I did:

I manually configured the colors like the Monokai theme. As you can see here, the XML Doc Attribute ("typeOfTrade") is grey, which is set by the Identifier. By using the extension, I can give any color I want to other items that otherwise would've inherited that grey from the Identifier.
From their marketplace page:

A Visual Studio 2015, 2017 & 2019 editor extension for semantic syntax
highlighting.
It uses the Roslyn APIs to highlight the following syntax types in
distinctive colors to make them easily recognizable.
To change the colors use the regular Visual Studio "Font and Colors"
Options. Look for Semantic * in the "Display items".
This extension works for the first final version of Visual Studio 2015
and all sucessors.

From my config:


JQuery Fullcalendar display full title despite being merely 30 minutes event

Question: If I set an end time to an event, then the plugin draws the event rubric in accordance with it. Problem is, if event is too short, user can't read the title...

How can I make it "override" the end time in these cases and display the full title?
Answer: In Agenda view you can use agendaEventMinHeight to get your desired result. You won't actually override the end time, but directly override the size of the event-box.
https://fullcalendar.io/docs/agendaEventMinHeight


How to kill a particular in memory session in IIS console?

Question: I need to kill a user session if it's causing trouble on the web server due a web application bug as a quick workaround. Is it possible to kill only a particular in memory user session from the IIS console somehow without recycling and killing all other sessions as well?
Answer: No.
Comment: Ok. Thanks. Thought so. Unfortunately the app itself has nothing build in to kill the session.
Answer: Yes. But you would need 3rd party software to do it. But there is no way in the OS to accomplish this.
Check this software out. I just found this myself.
https://www.isdecisions.com/products/userlock/access-management-how-to-restrict-and-monitor-IIS-sessions.htm


Find an orthogonal matrix $P$ such that $P^{T}AP$ is diagonal.

Question: I began by finding the eigenvalues and eigenvectors of $A$ where $A=\begin{pmatrix}
  4 & 0 & -2 \\
  0 & 2 & -2 \\
  -2 & -2 & 3
 \end{pmatrix}$. This gave $\lambda_1=0, \lambda_2=3$ and $\lambda_3=6$ and $\mathbf{v}_1$ $= \begin{pmatrix} 0 \\ 0 \\ 0 \end{pmatrix}, \mathbf{v}_1$ $= \begin{pmatrix} 2 \\ -2 \\ 1 \end{pmatrix}$ and $\mathbf{v}_3 = \begin{pmatrix} -2 \\ -1 \\ 2 \end{pmatrix}.$
I then divided each eigenvector by its length and put them all together to make $P=\frac{1}{3}\begin{pmatrix}
  0 & 2 & -2 \\
  0 & -2 & -1 \\
  0 & 1 & 2
 \end{pmatrix}$
Now $P^{T}AP $ is diagonal as required but the problem is that $P$ isn't orthogonal because $P^{T}P\neq I_3$. I assume this has happened because of there being a $0$ eigenvalue but what should I do about it?
Comment: By definition, $\vec 0$ isn't an  eigenvector.  Try to find a non-zero vector of the kernel of the matrix.
Comment: What about $x=1$, $y=z=2$?
Comment: How did you found $v_2$? Just solve $Ax=\vec0$.
Comment: How would I do that?
Comment: That's what I tried originally. It gives me the equations: $2x=z$, $y=z$ and $-2x-2y+3z=0$. But isn't the only solution here $x=y=z=0$?
Answer: As answered in the comments above: the problem is that we needed an eigenvector for $0$, which by definition could not be the $0$ vector.
On top of this, note that in order to have $P^TP = I$, all columns of $P$ must have length $1$.  Ensure this by normalizing the eigenvectors, that is, dividing all columns of $P$ by their length.


Importing location data into Drupal 7

Question: New to Drupal but am interested in it as an option to transition to from a hand coded site. This site is primarily a location searchable venue index, with venues having various categories.
In Drupal I have set up my content type 'Venue' and have added the location module to store the venue addresses and other contact details.
Now I am wanting to import my existing data which I have ready in a CSV.
To do this I understand I should use the feeds module which I have now installed (along with ctools and job_scheduler).
Now under Structure-> Feeds importers -> Add importer I can create and configure my CSV import - Great!
Unfortunately I can't see any option under Processor to associate my CSV address fields with the location module fields. What am I missing here?
Answer: A little late but there's this module: https://drupal.org/project/location_feeds
Location Feeds :D
Haven't actually tried it yet but It seems to do exactly what you want.
Answer: I can't help you with the feeds module, but i can tell you how we did this. We used the Migrate module to import a large amount of addresses as locations. With migrate we also had the chance to geocode each location on import (with the Google Geocoder). Migrate is a very powerful module which has a lot of possibilities when it comes to importing data to Drupal.
Comment: Would you mind sharing how you did it?

Importing location data into Drupal 7


How to express Hotelling T² test as a Likelihood ratio between two multivariate linear models?

Question: Is it possible, given that Hotelling's T² (or Hotelling-Lawley Trace for that matter) is just a generalization of Student's T, to reformulate the same testing procedure (to test if two vectors differ) as a relative Likelihood comparison between two multivariate linear models?
Analogous to expressing a t-test as a linear model (in Wilkinson Notation) value ~ 1 + group and then comparing it to the intercept-only model?
Answer: When Hotelling's $T^2$ test is called a likelihood-ratio test, that doesn't mean that $T^2$ is itself a likelihood ratio, but rather that the test based on $T^2$ is the same as the test based on the likelihood ratio, because $T^2$ is a monotone function of a likelihood ratio. A likelihood ratio test rejects the null hypothesis precisely if the likelihood ratio is too extreme (meaning too large or too small, depending on which quantity you decided to put in the numerator and which in the denominator). The likelihood ratio is too extreme precisely if $T^2$ is too big, so although $T^2$ is not itself the likelihood ratio, the test based on it is the same test as the one based on the likelihood ratio; thus it is a likelihood-ratio test.
You have $X\sim\operatorname N(\mu,\Sigma),$ where $\mu\in\mathbb R^p$ and $\Sigma\in\mathbb R^{p\times p}.$ The null hypothesis says $\mu=\mu_0.$ The likelihood function based on an i.i.d. sample of size $n$ is
\begin{align}
& L(\mu,\Sigma) \\[8pt]
\propto {} & \prod_{i=1}^n \left( (\det \Sigma)^{-p/2} \exp\left( -\frac12 (x_i-\mu)^\top\Sigma^{-1} (x_i-\mu) \right) \right) \\
& \text{where "$\propto$" means proportional as a function} \\ & \text{of $\mu$ and $\Sigma$} \\[8pt]
= {} & (\det\Sigma)^{-np/2} \exp \left( -\frac12 \sum_{i=1}^n (x_i-\mu)^\top\Sigma^{-1} (x_i-\mu) \right).
\end{align}
It is well known (and here I omit the proof) that the value of $(\mu,\Sigma)$ that maximizes this is
\begin{align}
\mu = {} & \text{the sample mean} = \overline x = \frac1n\sum_{i=1}^n x_i \\[8pt]
\Sigma = {} & \text{the sample covariance matrix} \\
& S = \frac 1n \sum_{i=1}^n (x_i-\overline x)(x_i-\overline x)^\top, \\
& \text{(which is a biased estimator of} \\
& \text{the population covariance matrix).}
\end{align}
That, however, is under the alternative hypothesis. Under the null hypothesis, one has $\mu = \mu_0.$
The likelihood ratio is therefore
\begin{align}
& \frac{(\det S)^{-np/2} \exp \left( -\frac12 \sum_{i=1}^n (x_i-\overline x)^\top S^{-1} (x_i-\overline x) \right)}{(\det S)^{-np/2} \exp \left( -\frac12 \sum_{i=1}^n (x_i-\mu_0)^\top S^{-1} (x_i-\mu_0) \right)} \\[8pt]
= {} & \exp\left( \frac12\left( \sum_{i=1}^n (x_i-\mu_0)^\top S^{-1} (x_i-\mu_0) - (x_i-\overline x)^\top S^{-1} (x_i-\overline x) \right) \right)
\end{align}
and one rejects the null hypothesis if this is too big. It is too big precisely if
$$
\sum_{i=1}^n (x_i-\mu_0)^\top S^{-1} (x_i-\mu_0) - (x_i-\overline x)^\top S^{-1} (x_i-\overline x) \tag 1
$$
is too big.
Now we use some algebra to massage a portion of the expression above.
\begin{align}
& \sum_{i=1}^n (x_i-\mu_0)^\top S^{-1} (x_i-\mu_0) \\[8pt]
= {} & \sum_{i=1}^n \big((x_i- \overline x) + (\overline x - \mu_0)\big)^\top S^{-1} \big((x_i- \overline x) + (\overline x - \mu_0)\big) \\[8pt]
= {} & \sum_{i=1}^n (x_i- \overline x)^\top S^{-1} (x_i- \overline x) \tag2 \\
& + \sum_{i=1}^n (x_i- \overline x)^\top S^{-1} (\overline x - \mu_0) \tag3 \\
& + \sum_{i=1}^n (\overline x - \mu_0)^\top S^{-1} (x_i- \overline x) \tag4 \\
& + \sum_{i=1}^n (\overline x - \mu_0)^\top S^{-1} (\overline x - \mu_0). \tag5
\end{align}
Observe that line $(3)$ above adds up to $0$ because as $i$ goes from $1$ up to $n,$ $S^{-1} (\overline x - \mu_0)$ does not change, and may therefore be pulled out of the sum, getting
$$
\left( \sum_{i=1}^n (x_i- \overline x) \right)^\top S^{-1} (\overline x - \mu_0)
$$
and the expression within the big parentheses is $0.$ Similarly, line $(4)$ is $0.$
So the expression on line $(1)$ adds up to
\begin{align}
& \sum_{i=1}^n (\overline x - \mu_0)^\top S^{-1} (\overline x - \mu_0) \\[8pt]
= {} & n (\overline x - \mu_0)^\top S^{-1} (\overline x - \mu_0),
\end{align}
and that is ($n$ times) Hotelling's $T^2.$
Thus the likelihood ratio is too big precisely when Hotteling's $T^2$ is too big.
(How big is too big? That depends on the level of the test and on the probability distribution that $T^2$ has when the null hypothesis is true.)


How would I use DATEDIFF(), NOW(), and BETWEEN in a db_delete() query?

Question: Is the something like the following possible?
db_delete('note_dates')
    ->condition("DATEDIFF('start', NOW()) BETWEEN 0 AND 30")
    ->execute();

Answer: You can use DeleteQuery::where(), e.g.
$args = array(':arg1' => $foo, ':arg2' => $bar);
db_delete('note_dates')
  ->where("DATEDIFF('start', NOW()) BETWEEN :arg1 AND :arg2", $args);
  ->execute();

That'll give you
DELETE FROM {note_dates}
WHERE  (DATEDIFF('start', NOW()) BETWEEN :arg1 AND :arg2)


How to add an extra domain name to Exchange?

Question: We would like to be able to send and receive mail using an extra domain name.  We want to be able to tack on extra email addresses (with the new domainname) to our existing AD users.
I've added the DNS entry, I just need to configure Exchange.
Can anyone give me some pointers?
Some additional information: I've added the new domain to our default recipient policy, and added the new email address to my user account - i can send mail to myself, but not from my gmail account.  I also cannot send from this new address.
Thanks,
Ashley
Answer: Just edit your recipient policies to include the additional addresses.  Here is a step-by-step guide.
Comment: +1 - Congrats on breaking 10K.
Comment: +1 - Recipient policies is what you need and the guide in Petri is an A+.


Show that $\det(P(t))=\det(P_0) e^{\int_0^t \operatorname{Tr} A(s)\, ds}$

Question: Let $A(t)$ be a continuous family of $n \times n$ matrices and let $P(t)$ be the matrix solution to the initial value problem $P'(t)=A(t)P$, where $P(0)=P_0$. Show that $$\det(P(t))=\det(P_0) e^{\int_0^t \operatorname{Tr} A(s)\, ds}.$$
If we consider $A(t)=
    \begin{pmatrix}
    a & b  \\
    c & d  \\
    \end{pmatrix}$, $P(t)=
    \begin{pmatrix}
    x_1 & y_1  \\
    x_2 & y_2  \\
    \end{pmatrix}$, and $W(t)=\det (P(t))$ then $W'=\operatorname {Tr}(A) W$.
My question is how do I solve the last system?
And I just consider  $2\times 2$ matrix, but the result follows easily for an $n\times n$ matrix; am I right?
Comment: @user486983 $ W'=\text{Tr}(A)W $ can be solved just by integration, because $\text{Tr}(A(t))$ will be just a real valued function of $t$.
Comment: well I have a result in my notes that says $P(t)=e^{At}P_0$, for A a matrix, $P_0\in \mathbb R^n.$
Comment: @user486983 Also $\text{det}(P(t))$ is a real valued function of $t$.
Answer: Given $P'(t)=A(t)P, ~ P(0)=P_{0}$. Let $W(t)=\text{det}(P(t))$ and suppose that $p_{1}(t),...,p_{n}(t)$ be column vectors of $P(t)$. Since determinant is multilinear function, derivative can be determined as $$ W'(t)=\sum_{k=1}^{n} \text{det}(p_{1}(t),...,p'_{k}(t),...,p_{n}(t)) $$
$$ =\sum_{k=1}^{n} \text{det}(p_{1}(t),...,A(t)p_{k}(t),...,p_{n}(t)) $$
$$ = \text{Tr}(A(t)) \text{det}(p_{1}(t),...,p_{n}(t)) = \text{Tr}(A(t))W(t) $$
$$ \text{So, }~ W'(t)= \text{Tr}(A(t))W(t)  $$
Integrating above differential equation, we will get
$$ W(t)=c \text{e}^{\int_{0}^{t} \text{Tr}A(s) \text{ds}}. $$
Using initial condition $P(0)=P_{0}$, we get $c=\text{det}(P_{0}).$
$$ \text{Therefore,} ~ \text{det}(P(t))=\text{det}(P_{0})\text{e}^{\int_{0}^{t} \text{Tr}A(s) \text{ds}} $$
Comment: Thank you for your answer


Ideas for solofying for cello

Question: I'm looking for some schemes to solofy a simple tune on cello. Some obvious things, like adding a fancy bassline fail in this case of course.
As an example let's take this simple tune.

One obvious idea is to add some double stops.
Are there other stereotypical recipes?
By solofying I mean things you can do to the score to create sheet music that has more ornaments and is more interesting to listen at when played by a single instrument.
Comment: Any particular reason why you want the melody to stay in the lowest bass register? Setting it as a tenor chant would give you many more opportunities of using other strings for accompaniment, and in my opinion sounds better anyway.
Comment: _Morgen, Kinder, wird's was geben_? Christmas is over...
Comment: Yes! It's the melody of Morgen, Kinder, wird's was geben just an example for a simple tune. (The song is Morgen, Kinder, wird's nichts geben by Erich Kästner btw :-))
Comment: @KilianFoth No particular reason. Transposing it in a higher register is a good idea. I really love those low notes, but yes you surely are right. Thank you.
Comment: I might start by doing an analysis of the chord progression (and/or key progression if any) and building the support notes around the intended chord structures.
Answer: If I had to play this piece solo, I might do something like this:
Comment: Wow! Great effort! Thank you very much. You used many pattern there, I'll be able to extract and list them on my own. Thank you!
Answer: I can't find a translation in german and find whether an explanation nor synonyms of solofie and solofying in english.
but if you mean to play a solo or variation of the given tune (and others) try by fill the  crotchets with eighth notes with an other chord note. find out and  write down the chord progression of the tune and compose a little variation using this chord notes, returning notes and passing notes (diatonic and chromatic)
Comment: In this case I can give you another hint: just play the first basic note of each chord and the fifth with upper diatonic returning note or lower chromatic returning note as in blues or boogie woogie (do so la so or do so fi so) and at instead of the last half note of the first line: so fa mi re do (all as 8th notes) and listen to the last section of the 6th symphony of Beethoven.

Ideas for solofying for cello


How to use same database for two website but different panel?

Question: Is this possible to use same database for two different domain? Example domain1.com and domain2.com but their views and designing are different for both site but content will be same .
If I change in one domain1.com it will reflect also in the domain2.com
Answer: You should start from https://www.drupal.org/docs/8/multisite
Drupal supports multisite structure out of the box. You don't need Domain Access module to reach it.
You may share some db tables among your websites, e. g. content but keep settings (Views, display settings unique). It depends of your purpose. Also you may have shared or unique modules and themes.
The idea is that you specify the list of the sites in sites.php and have several subfulders under /sites folder. At least it worked with Drupal 7. I'm sure there is no drastic charge with Drupal 8.
But be careful with cache. Mind which caches you want to keep shared or unique.
Comment: i have setup two sites , can we separate both sites view like site1.com  view show only in site1.com admin panel and vice versa?
Comment: You have to make Views settings (db tables storing such data) unique for every site. That means you will have all the Views separated.
Comment: can you suggest me any tutorial regarding the views setting for all setting only content will be the same?
Comment: Unfortunately, I don't have my laptop on tap with all the bookmarks at the moment. I did it quite a long time ago with Drupal 7. I don't recall any straight forward guide, just find some tutorial related to Multisite with Drupal 8, try it out, understand how it works and play around with the tables
Comment: I have setup the multi site with same database . How can I use different menu and footer for the different theme. I don't understand how can I use because using the same admin  panel in multi site .I want different logo different footer different menu
Answer: You can using the Domain Access module.

The Domain Access project is a suite of modules that provide tools for
  running a group of affiliated sites from one Drupal installation and a
  single shared database. The module allows you to share users,
  content, and configurations across a group of sites such as:
example.com one.example.com two.example.com my.example.com
  thisexample.com <-- can use any domain string example.com:3000 <--
  treats non-standard ports as unique By default, these sites share all
  tables in your Drupal installation.
Comment: it will work on  the localhost?
I have to install drupal for both domain ?
can I use the different theme for both domain with same users , content and configration?
Comment: @ManmeetKhurana 1) Never tried it myself on localhost, but in theory it should work. 2) No you just install Drupal once 3) Yes diff theme for each site and configuration. An example of this is [https://mahindrausa.com/](https://mahindrausa.com/) & [https://build.mahindrausa.com/](https://build.mahindrausa.com/) & [https://mahindracanada.ca/](https://mahindracanada.ca/)
Comment: I have done new installation on root directory for xyz.com .its working fine and now i have install the domain module and  created the subdomain xyz.com.au and its directory under the root folder and  fill both domain at domain setting xyz.com and xyz.com.au .but its not working for second domain .
Have i miss something?
Comment: Please suggest how can use different domain for Domain Access Module not the sub domain.
Comment: @ManmeetKhurana Sorry I can't answer this with few words. You will need to read & follow the module's [documentation](https://www.drupal.org/docs/7/modules/domain-access).
Answer: If I understand you want to change only the theme based on the domain.
I have not made such changes in Drupal 8 but Switch Page Theme module can help you.
Here is a similar question: How can I change the active theme programmatically?
Comment: That makes no sense. The same content but different admin panels is a contradiction. If you want to have the same content on both pages, the content in admin will be same too.
Comment: yes I want to change the theme one theme for  first domain and second theme for the second domain . Is their any method to setup with sub directory ?two setup of drupal with same database
Comment: If only the topic should be changed, it will be one drupal with two themes. There is no need to install two drupali.
Comment: I understand what you are saying but I want different admin panel for both domain.


Proper way to account for yourself in Google Analytics

Question: I'm relatively new to seriously working with Google Analytics (I can obviously review page views and referrals) but I want to get something back now.
One of the first things to do is remove myself from being tracked which I understand is using a filter, with my IP address.
My question is, since IP addresses change periodically, even on always on cable connections, how do I account for this change? Do I have to keep tabs on it? How about in a situation where there are a couple of IP addresses always working on the server?
Thanks
Rich
Answer: If you are using dynamically generated webpages (eg. PHP, Python, Rails, Perl, etc) then you can set yourself a cookie which the page looks for and then only includes the tracking script if it fails to find that cookie.  This is the solution that most CMS systems seem to use for Google Analytics code, and it works quite well since it's just part of the normal login process.
Alternatively, especially if it is static html files, create a second website for yourself to work on and then come up with some way of synchronising the files from this second website to the live server and add the tracking code whilst synchronising.
Answer: Be ignoraant.
Seriously.
Unless your website is a "blog of me looking out of the window" your own traffic simply is not relevant. Once you have 200-300 visitors per day - do you really need to count your own views? They wont really change anything relevant.
Answer: This might be the simplest and sturdiest way to conceal your own activity on a website from GA, i.e., so that it is not counted by client-side analytics: create a unique user-agent.
As evidenced by the fact that Google has published instructions for how to set up a filter to exclude data from a custom user agent string, this technique is at least tacitly endorsed by Google.
Here's one way to do it:

open a browser window in Firefox;
type "about:config" (without quotes)
in the address bar;
press 'return'
right-click the blank area to get a
contextual drop-down menu;
select "New" from that List, then
select 'String';
a dialog will open and prompt you to "Enter the
preference name";
type "general.useragent.override" in
the text box then click 'ok'
enter a user agent string of your
choice

That's it. Now all you have to do is set up a Filter in your GA account. Here are simple step-by-step instructions from the Google Analytics Team for setting up a Filter to exclude a particular user agent.


Hide or disable field after registration

Question: I have 1 field on user registration page that should not be changed after account registration. It needs to be hidden or disabled.
Which module can do this ?
Comment: related: https://www.drupal.org/node/374416
Answer: If you want to do it in custom module
my_module_form_user_profile_form_alter(&$form, &$form_state) {
  // Since it is on registration form, field might be reqruied.
  $form['your_field']['#required'] = FALSE;
  $form['your_field']['#access'] = FALSE;
}

Comment: @Smalution You don't have to - for registration form it would be `my_module_form_user_register_form_alter`, not `my_module_form_user_profile_form_alter`.
Comment: hook is hook_form_FORM_ID_alter FORM_ID for registration and edit is diefferent
Comment: How can it differentiate between user creation and edit?
Comment: Ok got it. I have checked when user register its form id "user-register-form" and when user edit its form id "user-profile-form" normally.
Comment: Yes, as expected :)
Comment: This answer seems to be almost right. To differentiate between user creation and edit you could use    global $user object. In case of creation $user->uid will be equal to 0, but In case of edit it will have any other value. I didn't try it myself but from my previous experience it should work. I don't think that enabling field permissions module for such small task is a best solution. Thanks.
Comment: @BogdanTur forms are different for user add and user edit, which has been already taken care by hook_form_FORM_ID_alter.
Answer: You can try Field Permissions Module

Features

Enable field permissions on any entity, not just nodes.
Role-based field permissions allowing different viewing patterned    based on what access the user has.
Author-level permissions allow viewing and editing of fields based on    who the entity owner is.
Permissions for each field are not enabled by default. Instead,    administrators can enable these permissions explicitly for the fields
  where this feature is needed.
Comment: How can it differentiate between user creation and edit when it's the same field? I'm not saying it can't, I genuinely would like to know how. And I guess OP would, too.
Comment: It will be role based field permission, need to give permission only for anonymous(not sure will this condition works for the case).
Answer: Try with this code:
function MODULENAME_form_alter(&$form_state, $form_id){
  $form[$field]['#access'] = FALSE;
  $form[$field]['#disabled'] = TRUE;
  }

Comment: Please add few words of description.
Comment: $form['field_name']['#disabled'] = TRUE;  also works.
Answer: function module_form_alter(&$form_state, $form_id) {
 if (isset($form['title'])) {
    $form['title']['#required'] = FALSE;
    $form['title']['#type'] = 'value';
  }
}

Answer: Make field visibility property for anonymous users only. So Value will be stored at time of registration. Then no one can access that field. Once you install field permission module, you will find this option to apply to only anonymous user only.
Answer: Try using hook_form_alter, see the example below:
function MODULENAME_form_alter(&$form_state, $form_id){
      global $user;
      //$form_id :: user detail edit form id
      if($user->uid != 0 && $form_id == "required_form_id"){
         //$field :: requied field name
          $form[$field]['#access'] = FALSE;

      }
   }

Answer: place this code in a custom module, field will be able on new content but will be disabled to edit it.
if ($form_id == 'YOUR_FORM_ID') {
//dsm($form);

// for user form use '#user' instead of '#node' and uid instead of nid
if (isset($form['#node']) && isset($form['#node']->nid)){

    // Prevent editing a field once the node has been created
    // hiding the field entirely on the edit form.
    $form['field_name']['#access'] = FALSE;

    // disable update field on the edit form (gray color).
    $form['field_name']['#disabled'] = TRUE;
}

}
Answer: I actually think, that #disabled is not required, when you already have #access to false.
Also #disabled is not a really good thing because it adds disabled=disabled to the form field which you can easily delete as a user.
What you want to achieve is:

Access false
the field value which the user gave for example at the registration form is still there.

You can achieve this in your module with the following code:
use \Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter() for form 'user_form' (user edit form).
 *  - disable the change of field field_MY_FIELD (Registrierungstyp)
 */
function YOUR_MODULE_form_user_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
// in the example you see also how to make the administrator role can still change the field
  $currentuser = \Drupal::currentUser();
  $roles = $currentuser->getRoles();
  $authenticated = $currentuser->isAuthenticated();
  if ($authenticated &&
    !in_array('administrator', $roles)
  ) {
    $form['field_MY_FIELD']['#access'] = FALSE;
    $form['field_MY_FIELD']['#default_value'] = TRUE;
  }
}


automatic folder creation in bash

Question: I have a folder with a nested structure of sub-folders in it. I want to create another folder and copy that structure to in. However, I only want to keep the first level of the structure. To be more clear, imagine 1 folder containing 100 folders each of which having some other nested levels of folders. I want to  create a separate folder, somewhere else, in which I create 100 folders with the exact same names. That's it. No need to copying the contents of each folder.
Is it possible to this in one line of code via piping, and mkdir or something else?
Comment: The task is clear. Now after you've described what you want, what do you expect us to do?
Comment: @AxelAmthor just added info the question. Totally forgot about asking the question!
Answer: Write the folderstructure to some file
find . -type d > /tmp/dirs.txt

cd into your new folder and create the directories using
xargs mkdir -p < /tmp/dirs.txt

Or if you have spaces in the foldernames (which is never a good idea):
find . -type d -print0 > /tmp/dirs.txt
xargs -0 mkdir -p < /tmp/dirs.txt

If you only want the first level of structure, add -maxdepth 1 to the find command.
Comment: Not working. 1) splits folder names with space and creates separate folders based on each split name! 2) copies the whole structure where I wanted to have a copy of the first level of the hierarchy.
Comment: you should never uses spaces in foldernames. However, I'll update he answer to include that.
Answer: You can use find like this to create directories found at 1st level:
find ./A -mindepth 1 -maxdepth 1 -type d -execdir mkdir "$PWD/B/{}" \;

Comment: Doesn't work. "Error: mkdir: cannot create directory 'A/BlackAndWhite': File exists".  What I tried: "find A -maxdepth 1 -type d -exec mkdir B/'{}' +"

automatic folder creation in bash


When do I use the "when" keyword (or expression) in emacs lisp

Question: I'm in the process of learning how to extend my local GNU emacs software by learning emacs lisp. In one of the source codes I encountered I saw a "when" there. I think this is a control structure but I'm not sure. I've tried googling "the when keyword/expression in emacs lisp" (and other similar permutations of the sort). I even checked the gnu.org website. I only found source codes that contained "when" but no description for how and and when to use "when". Can someone tell me how and in what appropriate situations should I use "when" in control structures, etc, in emacs lisp? Thanks in advance.
Answer: Type C-h f when RET and you'll see the documentation:

when is a Lisp macro in subr.el.
(when COND BODY...)
When COND yields non-nil, eval BODY forms sequentially and return value of last one, or nil if there are none.

You can see how it's implemented if you macro-expand it:
ELISP> (macroexpand '(when cond body1 body2 body3))
(if cond
    (progn body1 body2 body3))

You should use when instead of if in the case where you don't have an "else" clause. It looks nicer, and it provides a hint to the reader that there's no "else" clause. If you have an "else" clause but no "then" clause you can write unless.
Comment: And also note that there's an `unless`, which may be preferable to `(when (not ...) ...)`
Comment: See the last sentence of my answer!
Comment: Seems the link is broken, https://www.emacswiki.org/emacs/WhenToUseIf though works. This seems to indicate this answer is wrong. Use `when` when you want to indicate side effects.
Answer: Many people follow the convention of using when and unless to signal to human readers that the return value of the sexp is not important -- what is important are any side effects performed.


Who first coined the phrase "correlation does not imply causation"?

Question: Reading Galton and Wright has indicated to me that even from the early days of considering correlation, there was some awareness that correlation is not synonymous with causation. However, who was the first (citable source) to say the familiar phrase "Correlation does not imply causation"?
Comment: Maybe a cave man with a long history of "better hunting on cloudless days," but who eventually discovered the truth is that there's better hunting on warmer days---even if there are clouds. (Prey hides when it cold.)
Comment: @BruceET :D haha indeed, I think our ancestors have had such a notion since time immemorial. The phrase itself probably came much later ;)
Answer: tl;dr: A book reviewer with the initials F.A.D in a 1900 issue of Nature appears to be the first to publish the phrase "correlation does not imply causation."
Long form answer
Depending on whether you are looking for the exact words "correlation does not imply causation" (note also "correlation is not causation"), or just want the primary dive into the relationship between correlation and causation, a good answer is 18th Century Scottish philosopher David Hume in A Treatise on Human Nature, where he muses on the relation between correlation and causation. For example,

It is certain, that not only in philosophy, but even in
common life, we may attain the knowledge of a particular cause merely by one experiment, provided it be made with judgment, and after a careful removal of all foreign and superfluous circumstances. Now as after one experiment of this kind, the mind, upon the appearance either of the cause or the effect, can draw an inference concerning the existence of its correlative; and as a habit can never be acquired merely by one instance; it may be thought, that belief cannot in this case be esteemed the effect of custom.

While Hume was nowhere near formalizing a causal calculus (e.g., Pearl's do operator), we can see in the above few sentences (abstracted from a whole section on correlation and causation), that he asserts that causal beliefs result from correlation between putative cause and effect of it, but only within a judicious model accounting for "superfluous circumstances" (backdoor confounding, selection bias, and differential measurement error, anyone?). Causal evidence demands correlation per Hume (both in the everyday sense, but also within the sciences), but neither naked correlation nor the absence of naked correlation is enough to establish a cause and effect relationship: in today's language we would say you need appropriate study design, and a causal calculus to deductively account for the structure of causal beliefs. Hume also made the notable contribution that causation can only be inferred, that what our senses give us is correlation.
As you indicate in your question, Sewall Wright is another worthy of consideration in answer to your question. One could make a claim that Wright originated the causal path analysis which led to both Pearl's work in formal counterfactual  causal inference, but to other formal models of causal inference, such as Levins' loop analysis of complex causal systems in which every variable directly or indirectly causes every variable in the system at some future time. In his paper "Correlation and Causation," Wright noted:

One should not attempt to apply in general a causal interpretation to solutions by the direct methods.

Where "direct methods" are those measuring what I called "naked correlations" above set in the context of Wright's methodological contribution of path analysis (prefiguring the use of both directed acyclic graphs and signed directed graphs in causal inference). In other words: naked correlation is not causation.
If you are looking only for the exact phrase, Google ngram book search records the first appearance of that phrase in its corpus in a May 17th, 1900 review of racist eugenicist Karl Pearson's The Grammar of Science titled "BIOLOGY AS AN "EXACT" SCIENCE" in Nature by one F.A.D., who writes:

As the author [Pearson] himself elsewhere points out, correlation does not imply causation, though the converse is no doubt true enough.

Pearson himself does not use the phrase "correlation does not imply causation" but is grappling with the relation between the two in The Grammar of Science, for example:

All causation as we have defined it is correlation, but the converse is not necessarily true, i.e. where we find correlation we cannot always predict causation.

Coda: I fully agree with @BruceET's direct comment to your question. Without wanting to reify the WEIRD, I suspect that causal reasoning, and perceptions of correlation are pretty inherent to human cognition across societies and times (my cat informs me non-human cognition also).

Selected References
D., F. A. (1900). Biology as an "Exact" Science. Nature, 62(1594), 49–50. [Collected in a May-October fassicle]
Levins, R. (1974). The Qualitative Analysis of Partially Specified Systems. Annals of the New York Academy of Sciences, 231, 123–138.
Pearl, J. (2000). Causality: Models, Reasoning, and Inference. Cambridge University Press.
Pearl, J. (2018). The Book of Why. Basic Books.
Pearson, K. (1900). The Grammar of Science (Second edition). Adam and Charles Black.
Wright, S. (1921). Correlation and Causation. Journal of Agricultural Research, 20(7), 557–585.
Comment: That is what I intended by "general idea" and "in the air."
Comment: I would argue that Francis Galton invented correlation circa 1888, but it was Pearson who discovered spurious correlations in 1896 in his craniometry studies. I don't know if he used that exact phrasing. Of course, the general idea was in the air long before that, as your quote demonstrates.
Comment: @dimitriy I think you confuse a ***statistical measure* named 'correlation'** with **the *concept* of correlation**. The latter preceded the former.


SQL search no duplicates

Question: Ok I'm trying to learn the best way to perform a search.
I have 40 tables.  In the 40 tables All tables have 2 of the same column, ID and date; all the tables obviously have other columns that don't match.
Now not every table is used by the user.  A user could use 5 tables, they could use all 40.  Also the IDs could have multiple dates attached too them.  I would like to get ALL the dates from all 40 tables from an ID with no duplicates.  AKA if table 1 and table 10 have the same date I only want it 1 time.
So here I have some questions.
The first way I have read is this.
 $stmt = $this->con->prepare("SELECT date FROM table1
 left join table2 on table1.id = table2.id
 left joins for table2--->table40
 WHERE ID = ?
 GROUP BY date");

the second way I have seen is like this.
 $stmt = $this->con->prepare("SELECT Distinct date FROM table1
 left join table2 on table1.id = table2.id
 left joins for table2--->table40
 WHERE ID = ?");

and the third way I have read is this. (their words not mine)
"In my experience (which is limited btw), I have used the equi join query for this purpose. Let me show you an example.
Consider three tables named Table1, Table2, and Table3 with a common column named Code(turned to ID). The code snippet below joins these three tables with no duplicates:"
 select date from Table1, Table2, Table3..... where Table1.ID=Table2.ID=Table3.ID......;

Now my question is what is the proper way for me to do this search??
It should return a list of dates found for 1 ID (the one being searched) no duplicates.
Comment: update your question add  a proper data sample and the expected  result
Answer: Your first and third approach differ only on syntax (first approach has a proper syntax, while the third one uses an archaic syntax that shouldn't be used for any new development for the last 15+ years).
All three approaches suffer from the same problem: when Table1 does not have a target ID, presence or absence of that ID in other tables would not matter: you wouldn't get any dates from them unless Table1 has the target ID.
You can fix this by using UNION on individual selects, like this:
SELECT date
FROM (
    SELECT date FROM Table1 WHERE Id=?
UNION
    SELECT date FROM Table2 WHERE Id=?
UNIO
    SELECT date FROM Table3 WHERE Id=?
UNION
    ...
UNION
    SELECT date FROM Table40 WHERE Id=?
) AS x

This would yield all date values regardless of the table in which it is found.
Note: An unfortunate side effect of this approach is the need to bind Id parameter forty times, because JDBC does not support named parameters.
Comment: @MadhurBhaiya Right, that would do the same thing with less code. I am using `UNION ALL` + `GROUO BY` because I remember it being poorly optimized in one of the engines that I used 10+ years ago, but I am not sure if it is still relevant.
Comment: Instead of using `Union ALL` and then eventually doing `Group By` to merge them into one; I feel that better approach would be simply using `Union`. It would remove all duplicates
Comment: thank you, that clears things up for me.  I see the dilemma now that you pointed it out.  I didn't think about that prior.  It didn't occur to me that it would be an issue.   One question.  What is the AS for at the end?  I looked at examples https://www.w3schools.com/sql/sql_union.asp   as an understanding on how to do the union.  I was just curious if there is a reason to AS (which I understand as Alias) to the end of it?
Comment: @gtcode I added an alias to make the syntax compatible with other RDBMS engines which require an alias on a nested select. I don't think it's necessary on MySQL, but it's a good idea to keep it anyway in case you decide to migrate your project to SQL Server or another engine that requires an alias.
Comment: ok cool I will hit the w3schools and figure out how to add it.  thank you guys a bunch for helping to teach me.
Comment: @gtcode Aliasing on Derived Table is necessary on MySQL. "The [AS] tbl_name clause is mandatory because every table in a FROM clause must have a name." Refer: https://dev.mysql.com/doc/refman/8.0/en/derived-tables.html
Comment: @gtcode please dont use w3schools. Always prefer official docs on understanding how things work in actual.
Comment: cool i just book marked your link.  thanks for taking the time
Comment: there is something wrong with searching this way as it comes up empty.  I searched just 1 table and the PHP side gives a response on 1 table that is correct.  But when trying all these unions I get an empty reply on postman.  {
    "error": false,
    "message": "Data Aquired",
    "date": []
}   any ideas?
Comment: @gtcode That's not possible, there must be some other mistake somewhere else in your query.
Comment: finally got it to work.  I changed the column positions on the DB and it works now.  Not sure why it was that way but it finally works. thanks

SQL search no duplicates


A basic question on random graph

Question: Consider undirected graphs with $n$ vertices. now consider the set of all possible edges (excluding self-loops). now, select edges from the set with probability $p$ independent of the other edges. so, we have a random graph. call it $A_p$. Do, the same thing but now with probability $q(q\geq p)$ to get another random graph $A_q$.
Let $Q$ be the collection of graphs such that if $X \in Q$ and $X \subset Y$(means that the edge set of $Y$ contains edge set of $X$) then $Y \in Q$.
In a book, I see that $P(A_p \in Q) \leq P(A_q \in Q)$. I don't find any trivial argument for this. Any suggestion will be helpful.
Comment: The magic word is "coupling". I don't have time to write a complete answer today, but if you don't figure it out or get another answer in a couple days, ping me.
Comment: Could you give us the name of the book and the page number?
Comment: I think you should use conditional probability.
Answer: As mentioned by @Nate, the key notion here is called coupling. Simply put, this means that there exists two random objects $G_p$ and $G_q$ defined on a common probability space $(\Omega,\mathcal F,\Pr)$ such that:

$G_p$ is distributed as $A_p$
$G_q$ is distributed as $A_q$
$G_p\subseteq G_q$ with full probability

Assuming these random objects exist, one gets
$$
P(A_p\in Q)=\Pr(G_p\in Q),\qquad P(A_q\in Q)=\Pr(G_q\in Q),
$$
and, for every increasing property $Q$,
$$
[G_p\in Q]\subseteq[G_q\in Q],
$$
from which the result is direct.
A simple way to couple the random graphs $G_p$ for every $p$ in $[0,1]$ at once is to start from an i.i.d. collection $(U_e)_e$ of random variables unform on $[0,1]$, indexed by the edges $e$ of the complete graph. Then, for each $p$, the edge set of $G_p$ is defined as
$$
\{e\mid U_e\leqslant p\}.$$
The property that $G_p\subseteq G_q$ for each $p\leqslant q$ follows.
Comment: Thanks. I have never come through this kind of argument.
Comment: Then, here is a suggested reading: Noga Alon, *The probabilistic method*.

A basic question on random graph


Drupal Error log services

Question: Can I create views for error logs, or directly expose them to services? How can I maintain my own error logs and expose them in services?
Answer:
Can I create views for error logs?

Yep, you can create Views for pretty much any type of data. There are a couple of existing modules that already do this:

Views Watchdog
Better Watchdog UI

Or you could of course write your own.
To expose Views as services, you can use the Services Views module, or, again, you can write your own resources for the Services module if it doesn't do exactly what you want.

Drupal Error log services


Point me in the direction of developing new forum features?

Question: Probably the most confusing part about Drupal for a beginner (read: Me!) is figuring out which modules should be used to develop new functionality. I'm looking for the path I would need to take to develop the specific functionality I'm trying to create.
This is what I'm looking to accomplish:
-Attach a user created "idea" or "opinion" to a forum post or thread
-Allow users to vote on & modify these "ideas" and "opinions"
Any leads are appreciated.
Comment: what research have you done ?
Answer: In order to create a forum in drupal, you can start with the forum module. It is a core module, so it will already be installed. The following steps can make forum development simpler:

Enable the module-

Go ahead and navigate to Site Building>>Modules and check the box next to forums to enable the module.

Set up containers-

you need to navigate to administer >> forums to start setting up your new forum

Set up forums-

Each container "contains" several forums. In other words, your
containers are children of the root node and your forums are children of
your containers

Customize your forum for adding content or ideas-

The following modules can be used for content entry:

BUEditor or wysiwyg
Live
Quote
Smileys
Signatures for Forums
Comment Upload

In order to add the voting/rating features, use the following:

VotingAPI
Rate

Advanced Forum may also be used if you wish to enhance Drupal's core forum module features.


Make a form sticky with php session

Question: I am trying to create php multipage forms, and I use PHP sessions for this purpose.
However, when there is an error in user input and I want the form to ask user to fill in the form again with correct inputs, the forms field will not hold the data that the user has already put in so the user has to start things all over again.
How to make forms sticky with php session?
Thanks
My code is as bellow
<?php
// Session starts here.
          if (!isset($_SESSION)) session_start();
?>
<form action="registration.php" method="post">
  <h8>Please create your user name and password</h8>

           Username
           <input type="text" placeholder="Enter Username" name="username" required value="<?php if(isset($_POST['username'])) echo $_POST['username'];?>">

            Password
              <input type="Password" placeholder="Enter Password" name="password" required>

              Confirm Password
    <input type="Password" placeholder="Confirm Password" name="confirm" required>

     <?php
     if (!empty($_SESSION['error'])) {
                echo "<error>".$_SESSION['error']."</error>";
                unset($_SESSION['error']);
      }

  if (isset($_POST['username'])){
       $_SESSION['username'] = $_POST['username'];
       echo $_SESSION['username'];
       echo $_POST['username'];
        }
 ?>

    <input type="reset" value="Reset" />
 <input type="submit" value="Next" />

and the registration php contains
<?php
if (!isset($_SESSION)) session_start();
// Checking first page values for empty,If it finds any blank field then redirected to first page.
if (isset($_POST['username']))
{
      if (($_POST['password']) === ($_POST['confirm']))
                 {
                     foreach ($_POST as $key => $value)
                         {
                             $_SESSION['post'][$key] = $value;
                          }
                 }
       else
                 {
                    $_SESSION['error'] = "Password does not match with Confirm Password.";
                    if (isset($_POST['username'])){
                               $_SESSION['username'] = $_POST['username'];
                               echo $_SESSION['username'];
                              echo $_POST['username'];
                    }
                    header("location: createlogin.php"); //redirecting to first page
                 }
}

Comment: I didn't see a closing `` anywhere, not even in edit mode. So, we don't know if that isn't part of, or "the" problem.
Comment: Can you show the code you have already tried?
Answer: Something like this:
<input name="var" value="<?= isset($_SESSION['var']) ? $_SESSION['var'] : null  ?>" />

Comment: If you're interested, give my form library a try, saves a lot of hassle https://github.com/delboy1978uk/form :-)
Comment: Not my downvote here, yet I can't see why it was downvoted; it's a possible solution. Maybe because of the "blah", who knows. Edit: I edited just in case. Edit 2: seems they retracted the downvote.
Answer: Try the other way around. Linking the form-action to the current page, and if all fields are valid; redirect it to the next page (registration.php). This way you'd still have all the post-data, you can process everything that needs to be saved in the session- and you can redirect after all of the logic is done.
Answer: My two cent would be keep the same page to validate the content and for the form.
You can include other PHP files from a single page depending on if the form is valid.
This way, you keep the same $_POST between both pages and don't need to store the posted data in a session variable.
Otherwise, if you want to keep the same architecture, you need to use the $_SESSION variables instead of the $_POST ones in your input value, such as the answer by delboy.
Replace:
<?php if(isset($_POST['username'])) echo $_POST['username'];?>

With:
<?php if(isset($_SESSION['username'])) echo htmlspecialchars($_SESSION['username']); ?>

^ Note: htmlspecialchars is used to prevent a reflected XSS if the users enters " as username.
Comment: I tried to validate on the same page etc, at the end Anthony's solution works.
Answer: The problem is, your data posted to registration.php, so you can't get the posted value in your original file. You are trying to use $SESSION but that's not recommended, and not right. Your whole solution is wrong.
Forget about session and separated files, put everything to registration.php file together.
You can check if user posted or not with $_SERVER['REQUEST_METHOD'] variable.
if($_SERVER['REQUEST_METHOD'] == 'POST'){
  print 'Something just posted';
}

PS: Don't forget secure the password before you store it! :)
Comment: Thanks so much. It seems that some suggestions are to work without sessions. I will try that solution and report how it goes.

Make a form sticky with php session


Error-term in the expansion of a riemannian metric in normal coordinates

Question: Let $(M,g)$ be a Riemannian metric and $\exp_x^{-1}:B_r(x) \to B_r(0) \subset \mathbb{R}^n$ be a normal coordinate system around $x \in M$ with respect to some orthonormal basis $e_1,\ldots, e_n$. The coefficients $g_{ij}$ of the metric tensor in $tz$, $t \in \mathbb{R}$ and $z \in \mathbb{R}^n$ is then given by
$$
t^2 g_{ij}(t):= t^2g_{ij}(tz) =< Y_i(t), Y_j(t)>
$$
where the $Y_i(t)$ are the unique solution of the Jacobi field equations
$$
Y_\alpha(t)'' + R\left(\gamma'(t),Y_\alpha(t)\right)\gamma'(t) \quad (*)
$$
along the geodesic $\gamma(t):=\exp_x t z$ with initial condition $Y_i(0)=0$ and $Y'_i(0)=e_i$. For example in the "Lectures on Differential Geometry" by Schoen and Yau this is used to compute the first few terms in the expansion of the $g_{ij}$;
$$
\bar{g}_{ij}(x)= \left(\delta_{\alpha \beta} - \dfrac{1}{3}R_{i kl j}x^{l} x^{k}\right) + lower Order
$$
I am having trouble understanding what this "lower Order" means. How do I use relation $(*)$ to prove that the reminder actually is smaller than the other terms in the expansion for $|x|$ small?
Comment: They are estimated computing the different order covariant derivatives of the $Y_j$ at $0$, which can be computed in terms of the curvature tensor and its different covariant derivatives (use the Jacobi equation)
Comment: The lower order terms are $O(|x|^3)$, and they can be computed thanks to Taylor's formula.
Comment: Can they be estimated in terms of the curvature of the manifold?
Comment: I would have called these *higher order terms*!
Answer: The idea is first to show this lemma:

If $\gamma$ is a curve, $Y$ a smooth vector field along $\gamma$, and if $\forall k \geqslant 0$, $Y_k$ is the unique parallel vector field along $\gamma$ such that $Y^k(0) := Y^{(k)}(0) = \left(\nabla_\gamma^{(k)}Y\right)(0)$, where $\nabla_\gamma$ is the covariant derivative along $\gamma$, then:
$$
Y(t) \underset{t\to 0}{=} \sum_{j=0}^k \frac{t^j}{j!}Y^j(t) + o(t^k)
$$

This is just the Taylor formula applied in any parallel frame along $\gamma$. Then, one can compute, using this formula,
$$
g_{ij}(t) = \frac{1}{t^2} \langle Y_i(t) , Y_j(t)\rangle
$$
by developping the scalar product with Taylor formula (careful with indexes: there will be $Y_i^k$!) and compute the Taylor expansion of $g_{ij}$ at any orders in terms of the different covariant derivatives of $Y_i$ and $Y_j$ (there are many mixed terms). These last terms can be computed thanks to the Jacobi equation. For example, for $k = 2$:
$$
Y^2(0) = -R(\gamma'(0),Y(0))\gamma'(0) = 0,
$$
for $k = 3$:
$$
Y^3(0) = -R(\gamma'(0),Y'(0))\gamma'(0),
$$
for $k=4$:
$$
Y^4(0) = - \left(\nabla_{\gamma'(0)}R\right)(\gamma'(0),Y'(0))\gamma'(0) + \ldots ,
$$
etc. Note that we use several times the geodesics equation. One can show that the terms in the Taylor expansion of $g_{ij}$  are universal polynomials in the coefficients of $R$, $\nabla R$, $\nabla \nabla R$... and $Y'(0)$, $Y''(0)$, $Y'''(0)\ldots$
Comment: And regroup the terms with the same order in $t$. Note that $t = |x|$.
Comment: Just developp $Y_i$ and $Y_j$ at $t=0$ with the Taylor expansion I gave you, and compute the inner product of the two expansions, by bilinearity. There is absolutely nothing more to do.
Comment: Thank you for your answer. My problem is that I am not quite sure how I estimate the remainder in the Taylor expansion and how small I need to choose $t$ for the estimate to stay true.


R: Find position of last value meeting a certain criteria for every row of a dataframe

Question: I have a dataframe that looks something like this:
M0 M1  M2  M3  M4  M5  M6  M7  M8
1   1   0   0   0   NA  NA  NA  NA
2   2   2   2   2   2   2   0   0
2   2   2   2   2   0   NA  NA  NA
2   2   2   2   2   0   0   0   0

What I would like to know is the position (column) of the last value larger than 0 in each row.
The desired output would be a vector containing these indexed positions
here: (M1, M6, M4, M4)
Comment: could you give the output desired ? I am not sure to understand what you mean.
Comment: I added the outcome I would envision for the provided example
Comment: Related: [For each row return the column name of the largest value](https://stackoverflow.com/questions/17735859/for-each-row-return-the-column-name-of-the-largest-value/)
Answer: Here's what you could do using apply. Basically, the function inside the apply looks for data>0 rowwise, finds the last one using tail(x,1) and finds the corresponding column names.
df <- read.table(text="M0 M1  M2  M3  M4  M5  M6  M7  M8
1   1   0   0   0   NA  NA  NA  NA
                 2   2   2   2   2   2   2   0   0
                 2   2   2   2   2   0   NA  NA  NA
                 2   2   2   2   2   0   0   0   0",header=TRUE, stringsAsFactors=FALSE)

names(df)[apply(df, 1, function(x) tail(which(x > 0), 1))]

[1] "M1" "M6" "M4" "M4"

Comment: Thank you. This works, but returns a NA for row that only consist of zero's. Since Henrik's solution simply returns the last column then, it fits better for my purposes. But I didn't specify this in my questions, so no way for you to know. Thanks!
Answer: You may use max.col
names(df)[max.col(!is.na(df) & df > 0, ties.method = "last")]
# [1] "M1" "M6" "M4" "M4"

Answer: One solution is to reshape from wide to long format and to pick the rightmost, i.e., last column > 0 by row id:
library(data.table)
melt(setDT(DF)[, rn := .I], id.vars = "rn", na.rm = TRUE)[
  value > 0, last(variable), by = rn]

      rn     V1
1:     1     M1
2:     2     M6
3:     3     M4
4:     4     M4

If you only want the vector:
melt(setDT(DF)[, rn := .I], id.vars = "rn", na.rm = TRUE)[
  value > 0, last(variable), by = rn][, V1]

[1] M1 M6 M4 M4
Levels: M0 M1 M2 M3 M4 M5 M6 M7 M8


guitar bridge lifted-up

Question: My guitar's bridge seems to be lifted up. I tried to tighten the bracket screws in order to pull the springs tighter and lower the bridge again, it works but when I tune the strings up the bridge will lift again up. I also tried to set the outer two springs diagonally in order to increase the tension but it doesn't work. The tremolo arm seems too stiff.
How can I prevent the tremolo bridge from lifting?
Comment: New strings? Same gauge? Same tuning? Suddenly happened?
Comment: This happened to me when I switched to a Heavier Gauge. Mine had 3 Back Springs and I added another to make them 4 and my problem was solved.
Comment: It didn't happen suddenly. I never did any setting to the guitar. I've been playing in this condition for a long time.
Answer: Basically, a Strat trem is a primitive floating bridge.
It uses the balance between string tension at the front & spring tension at the back to maintain equilibrium.
Equilibrium is not usually flat to the body, otherwise the trem could only be pushed, not pulled.
Now, of course, the resting position of the bridge is up to you. If you want it flatter you can have it flatter. Personally, I screw mine flat to the deck & never touch it… but that's just me.
If you want it to have a little float, then you first set your tension how you like it, then adjust your string height to suit the neck action.
From the photo of the rear, I can see you've got the springs set for maximum tension, so if you want any more, you need to add springs or tighten the two screws that go into the body. Looks like you've another half inch to play with - but it's going to be pretty stiff tightened up as far is it will go. You may need to re-consider whether you want less play in it overall by tightening the 6 screws [out of sight in your pic] in front of the bridge pieces.
Whichever way you decide to go, always slacken tension off everything first & reset after adjustment. Don't try just brute-fore hauling against a tuned set of strings; same as truss-rod adjustment, take some of the fight out of it rather than break something. It's very much trial & error & you'll have to adjust string height & probably intonation a few times before you're happy.
Comment: Just a point, but I believe the original design "strat tremolo" from 1954 did only go one way,  and considering the design of the current strats where the action height range of the neck set is generally only in range when the bridge is set flat, I think that's the default position. I have an old spec and setup sheet from Fender in a file somewhere. If I can find it I'll post an answer with the info.  It was a few years later that Fender came out with the "floating tremolo" that allowed movement both directions.  Not that you can't set it up however you like...

guitar bridge lifted-up


Common Lisp: extract methods from generic function

Question: Is there a way to extract a list of methods from a generic function in Common Lisp?
For example:
(defmethod say ((self string)) ; method-0
  (format t "Got string: ~a~%" self))

(defmethod say ((self integer)) ; method-1
  (format t "Got integer: ~a~%" self))

(defmethod say ((self symbol)) ; method-2
  (format t "Got symbol: ~a~%" self))

(extract-methods-from-generic 'say) ; -> (method-0-obj method-1-obj method-2-obj)

To be more specific, I'm targeting ECL, so if this can be done via C API - that's ok.
I need this to do the next trick:
(defgeneric merged-generic ())

(loop for method
      in (extract-methods-from-generic 'some-generic-0)
      do (add-method merged-generic method))
(loop for method
      in (extract-methods-from-generic 'some-generic-1)
      do (add-method merged-generic method))

Answer: The generic function generic-function-methods is available in the CLOS to get all the methods of a generic function (see the CLOS protocol), but note that, for the second part of your question, you can attach a method to a generic function (with add-method) only if the method is detached from any other generic function (see the protocol):

An error is also signaled if the method is already associated with some other generic function.

You can use both of those functions through the package closer-mop, independently from any implementation:
CL-USER> (ql:quickload "closer-mop")
("closer-mop")
CL-USER> (in-package :closer-mop)
#<Package "CLOSER-MOP">
C2MOP> (defgeneric say (x))
#<COMMON-LISP:STANDARD-GENERIC-FUNCTION SAY #x30200176712F>
C2MOP> (defmethod say ((self string)) ; method-0
  (format t "Got string: ~a~%" self))

(defmethod say ((self integer)) ; method-1
  (format t "Got integer: ~a~%" self))

(defmethod say ((self symbol)) ; method-2
  (format t "Got symbol: ~a~%" self))
#<COMMON-LISP:STANDARD-METHOD SAY (SYMBOL)>
C2MOP> (generic-function-methods #'say)
(#<COMMON-LISP:STANDARD-METHOD SAY (SYMBOL)> #<COMMON-LISP:STANDARD-METHOD SAY (INTEGER)> #<COMMON-LISP:STANDARD-METHOD SAY (STRING)>)
C2MOP> (defgeneric merged-generic (x))
#<COMMON-LISP:STANDARD-GENERIC-FUNCTION MERGED-GENERIC #x30200181B74F>
C2MOP> (add-method #'merged-generic (first **))

#<COMMON-LISP:STANDARD-METHOD SAY (SYMBOL)> is already a method of #<COMMON-LISP:STANDARD-GENERIC-FUNCTION SAY #x30200165863F>.
   [Condition of type SIMPLE-ERROR]
; Evaluation aborted on #<SIMPLE-ERROR #x3020016719FD>.
CL-USER> (let ((first-method (first (generic-function-methods #'say))))
           (remove-method #'say first-method)
           (add-method #'merged-generic first-method))
#<COMMON-LISP:STANDARD-GENERIC-FUNCTION MERGED-GENERIC #x302000DC54DF>
CL-USER> (merged-generic "a string")
Got string: a string
NIL

Comment: Okay, but is it possible to 'clone' a method and attach its copy to another generic function?
Comment: @Renzo Thats clonig an object. He wants to make a merge between the two generic methods without destroying the originals, which is done in this answer. Perhaps one could proxy it somehow?
Comment: You could look at the answers to this question: http://stackoverflow.com/questions/11067899/is-there-a-generic-method-for-cloning-clos-objects


Merging contents of columns using apply or other vectorized approach

Question: I have a data.frame that is almost entirely blanks, but each row has one value. How can I use a vectorized or other r-vernacular approach to merge the contents of each row into a single vector?
sample data:
raw_data  <- structure(
    list(
        col1 = c("", "", "", "", ""),
        col2 = c("", "", "", "", ""),
        col3 = c("", "", "", "", ""),
        col4 = c("", "", "", "Millburn - Union", ""),
        col5 = c("", "", "Cranston (aka Garden City Center)", "",""),
        col6 = c("", "", "", "", ""),
        col7 = c("", "", "", "", ""),
        col8 = c("", "", "", "", "Colorado Blvd"),
        col9 = c("", "", "", "", ""),
        col10 = c("", "", "", "", ""),
        col11 = c("Palo Alto",  "Castro (aka Market St)", "", "", "")
    ),
    .Names = c("col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8", "col9", "col10", "col11"),
    row.names = c(5L, 4L, 3L, 2L, 1L),
    class = "data.frame"
)

This is what I tried but it fails, as it returns a 2-dimensional matrix instead of the desired vector:
raw_data$test <-  apply(raw_data, MAR=1, FUN=paste0)

Answer: You can do this very simply with a single index operation:
raw_data[raw_data!='']

Demo:
R> raw_data[raw_data!=''];
[1] "Millburn - Union"                  "Cranston (aka Garden City Center)" "Colorado Blvd"                     "Palo Alto"                         "Castro (aka Market St)"

If you care about the vector order being top-to-bottom (as opposed to left-to-right then top-to-bottom, which is what the above operation does), you can transpose the input data.frame:
R> t(raw_data)[t(raw_data)!=''];
[1] "Palo Alto"                         "Castro (aka Market St)"            "Cranston (aka Garden City Center)" "Millburn - Union"                  "Colorado Blvd"

Answer: Your intuition about apply is right.  You just need to pass the collapse argument to paste:
 apply( raw_data, 1, paste0, collapse = "" )
                                  5                                   4                                   3
                        "Palo Alto"            "Castro (aka Market St)" "Cranston (aka Garden City Center)"
                                  2                                   1
                 "Millburn - Union"                     "Colorado Blvd"

Answer: In this example, there is only one element per row that is not ''.   Here, is another way to use paste with do.call
do.call(paste, c(raw_data, sep=''))
#[1] "Palo Alto"                         "Castro (aka Market St)"
#[3] "Cranston (aka Garden City Center)" "Millburn - Union"
#[5] "Colorado Blvd"

Suppose, if there are multiple elements per row in 'raw_data' that are not '', in that case, it may be better to use sep=';' or,`.
raw_data[1,1] <- 'Millburn'
raw_data[1,3] <- 'Something'
gsub('^;+|;+$|(;);+', '\\1', do.call(paste, c(raw_data, sep=';')))
#[1] "Millburn;Something;Palo Alto"      "Castro (aka Market St)"
#[3] "Cranston (aka Garden City Center)" "Millburn - Union"
#[5] "Colorado Blvd"

apply gets the same result as above
unname(apply(raw_data, 1, FUN=function(x) paste(x[x!=''],collapse=';')))
#[1] "Millburn;Something;Palo Alto"      "Castro (aka Market St)"
#[3] "Cranston (aka Garden City Center)" "Millburn - Union"
#[5] "Colorado Blvd"


Follow up to MANCOVA and any possible alternative analyses

Question: In my research, I have two categorical IVs and a DV:

A factor with 4 levels (mindset, encompassing 4 mindsets)
A factor with 2 levels (condition, encompassing 2 conditions)
A DV which is a composite factor with 4 levels (4 subscales)

I followed up with a MANOVA test with a Roy-Bargman stepdown to find out how the significant IV was affecting the comp DV.
However, I also have a construct of interest which is a continuous variable. Theoretically, it should also have effects on the comp DV.
I did a MANCOVA including this continuous IV as a covariate, but get the exact same results essentially as a MANOVA. Any one have some better ideas about how I can go about this?
Answer: I personally find that MANOVA and MANCOVA are not very useful methods of running multivariate analyses, particularly with the number of assumptions that must be met and the very limited way that the analysis can be constructed. For a detailed look at why, check out this episode from Quantitude, aptly called "MANOVA Must Die". But that's not the bulk of your question. What is more striking is that, as Sointu alluded to, you seem to only have one DV. In that case, there is no reason at all to use this method, and a simple multiple linear regression would accomplish what you are looking for (using your two factors as predictors regressing on the DV you mentioned, and entering the other continuous predictor is also easily accomplished this way).
To the point you made about the estimates being the same between your MANOVA and MANCOVA, I can't really say for certain why that is the case without output from your analysis. But it could just be an error or it could be that the control variable doesn't partial out enough variance to matter. More info would be needed on that front.
Comment: +1 for the podcast only!
Comment: That podcast is a treasure trove of information. I'm thankful it exists given how few outlets there are for such topics.
Comment: A quick look at the content coverage seems to be appetizing indeed.
Answer: First, if you have 1 dependent variable, why are you using MANOVA? That's for multiple dependent variables. If you have 1 dependent variable with 4 levels, multinomial regression might be more suitable.
(Though from your other descriptions it sounds like you actually have 4 different continuous dependent variables that fall under the same higher-level construct, so MANOVA is probably the correct choice).

I did a MANCOVA including this continuous IV as a covariate, but get the exact same results essentially as a MANOVA.

If you have set your model correctly, and your new covariate has no effect on DV and also nothing happens to the relationship between IV and DV, then in your data, the covariate is not related to your DV and also is not a confounder in the relationship between IV and DV, regardless of what theory says. There's really nothing to do about that. (Actually, it may be valuable information that the theory was not supported.)
Although, did you hypothesize a main effect of the covariate or (or also) that the covariate might affect the relationship between your original IV and the dependent? If the latter, maybe include an interaction between IV and covariate into the model and see what happens.


Lattice Paths Question

Question: You know, how we can have lattice paths, where we can move either one block north, or one block east, and we have the find all the possible ways of reaching the point (x.y) from (0,0).
That is $\binom{x+y}{x}$ paths we can have.
But what if, instead of only being able to move one block at a time, we can move move (1, n) number of blocks at a time, where n is any positive integer (and in the north direction). How many ways are there of going to a point (x, y) with this?
Comment: To confirm, do you still allow moves of (0,1) and (1,0) in addition to (1,n)?
Comment: @Ross: no, (0, 1) and (1, 0) are not allowed. We can only jump in steps of (1, n)
Answer: Given that all steps are of the form $(1,n)$, you need to have exactly $x$ steps.  So you are looking at compositions of $y$ in $x$ parts.  If you imagine $y$ sticks in a row, you need to select $x-1$ places of the $y-1$ available to break the row, so there are $\binom{y-1}{x-1}$ of them

Lattice Paths Question


How to choose EC2 instance type for reverse proxy (4 million requests / month)

Question: First time i have to create a reverse proxy on AWS, and i do not know with kind of instance to choose.
I plan to create an EC2 to load balance my traffic between a main website (/) and a wordpress blog (/blog/) with nginx.
I have to handle 1.000.000 requests a week (1000000/7/24/3600 ~= 2 requests seconds) and nothing else than nginx will run on this EC2.
Any advice ?
Answer:
Any advice ?

Don't guess it, benchmark it and then adjust it. It's easy to switch between instance sizes in AWS so start with one that may be the right fit and observe how is it doing. Then increase or reduce the size to optimise your cost/performance.
By the way 2 requests per second is not much, almost any instance should do. The problem is that it's probably not a uniform load, instead it will likely be going up and down and in peak times it could be a lot more. You may eventually want to have a look at auto scaling, but it may be an overkill.
Your usecase can also be handled by an Application Load Balancer - you can create rules to direct the traffic to different backends based on the URL path. It can also handle SSL certificates for you, etc.
Hope that helps :)
Comment: Thanks you for your response @MLu. Friends are telling the same thing too, the ALB seems much more appropriate for this use case. Should i take care about something else if i use ALB ? Should i choose a size or it will automatically handle all the traffic ? How works the ALB pricing (a bill each month for all traffic handled for the month) ?
Comment: I found this tutorial, i'll really appreciate your input on it (that seems too easy for me, i'm afraid to have some issues if a point is not cover) https://medium.com/commutatus/how-to-configure-a-reverse-proxy-in-aws-b164de91176e#:~:text=Reverse%20proxy%20as%20the%20name,apps%20under%20the%20same%20hood.

Thank you very much for your time.
Comment: @abenevaut Quickly scrolled through the tutorial and it seems spot-on. The GUI has changed a little but the concepts are correct: ALB, Listener, TargetGroups, etc. You can even configure it to handle HTTP to HTTPS redirection, and obtain a free certificate through ACM (Amazon Cert Manager). It scales with your traffic so no worries about the capacity. I'd personally do that rather than fiddling with nginx.
Comment: Thank you so much again for your time. I'll do this!
Comment: That's work well! Thanks again @MLu


Finding the dimension of a polynomial subspace

Question: Polynomial Subspace
For this question (in the attached link above) I originally thought the answer was 7 because typically the equation for finding the dimension of a polynomial is Pn+1 --> in this case it would be 6+1. However, since this is incorrect I was wondering if the answer would be 4 because I could only figure out the elements within W being 1, t^2, t^4, and t^6. Would this be correct?
Answer: I would prefer a slightly different wording, but that's the basic gist of it, yeah. The answer is $4$ because of the four polynomials $1, t^2, t^4, t^6$.
More formally, those four polynomials are linearly independent, as the only way to make
$$
a\cdot 1 + b\cdot t^2 + c\cdot t^4 + d\cdot t^6 = 0
$$
is to have $a = b = c = d = 0$ (at least as long as we require that $a, b, c, d$ are real numbers, which we do). Also, any polynomial in $W$ is a linear combination of these four polynomials (easily seen by just writing down the polynomial and looking at it).
Together this means that these four polynomials form a basis for $W$, and this implies that $W$ has dimension $4$.
Comment: Thank you for the clarification!


regex pattern for integer with comma

Question: The pattern
$test =  preg_match('/^(?=.\d)\d(?:\.\d\d)?$/', $_float1);

matches
0.25
2.55
1253.36
45.55

How to modify this to accept a comma in between the integer part?
such as 1,253.36?
Comment: Why did you set the JavaScript tag ? This looks more like PHP to me.
Comment: Potential duplicates: [this one](http://stackoverflow.com/questions/7199085/regex-for-optional-comma-separated-number-with-decimal-point) and [this one](http://stackoverflow.com/questions/20154386/regex-a-decimal-number-with-comma), but there are numerous other similar questions.
Comment: @dystroy yes its php i will remove the tags!
Answer: You could use this pattern:
/^\d*(,?\d{3})*(\.\d+)?$/

Answer: You can use this regex:
^\d+(?:,\d{3})*(?:\.\d\d)?$

RegEx Demo
Answer: I would've used this one:
/^\d{1,3}(?:(,?)\d{3}(\1\d{3})*)?(?:\.\d{2})?$/

Explained:

^\d{1,3}: starts by 1 to 3 digits
(?:(,?)\d{3}(\1\d{3})*)?: [optional] repeat XXX or ,XXX patterns (only one of them, to exclude numbers like 11,111111)
(?:\.\d{2})?: [optional] exactly two decimal places
$: That's all folks

Matches:
1 - 12 - 123 - 1234 - 12345
1,234 - 12,345 - 123,456 - 1,234,567
1.23 - 12.34 - 123.45 - 1234.56 - 12345.67
1,234.56 - 12,345.67 - 123,456.78 - 1,234,567.89
Doesn't match:
.1 - .12 - .123
1.2 - 1.234 - 1.2345
12,34 - 123,45 - 1,2345 - 1,2,345 - 1234,567
12,34.56 - 123,45.67 - 1,2345.78

regex pattern for integer with comma


The ratio of a maximized likelihood and a marginal likelihood

Question: I stumbled upon the following quantity and I'm wondering if anyone knows of anywhere it has appeared in the stats literature previously. Here's the setting:
Suppose you will observe data $y\in \mathcal{Y}$ which is distributed according to the density $p(y\,\vert\,\theta)$ for some parameter $\theta$ having a prior density $p(\theta).$ The marginal likelihood of $y$ is $p(y) = \int p(y\,\vert\,\theta)\,p(\theta)\,\text{d}\theta.$ Let $\theta_\text{ml}(y)$ be the maximum likelihood estimator of $\theta$ based on $y.$
The quantity of interest is $$c=\sup_{y\in \mathcal{Y}} \frac{p(y\,\vert\,\theta_\text{ml}(y))}{p(y)}.$$
I know that $c > 1,$ but I don't know much more than that. It certainly appears impossible to compute except perhaps in the simplest settings. I can't say immediately whether or when it is finite. I'm sure that it's also hard to bound above, which is what I'd be most interested in doing.
Comment: What is $m(y)$ in the denominator? Did you mean $p(y)$?
Comment: Yes, sorry. Fixed it.
Answer: The quantity $p(y|\theta_\text{ml}(y))$ is the marginal likelihood for the most favourable prior, which is not a true prior since it depends on $y$. It simply achieves the upper bound. Taking the supremum over all $y$'s does not make sense from a Bayesian perspective, since it should be conditional on $y$.
Now if one considers the Normal-Normal case, with prior $\theta\sim\mathcal{N}(0,1)$ and observation $X\sim\mathcal{N}(\theta,1)$, we have
$$p(y|\theta_\text{ml}(y))=\frac{1}{\sqrt{2\pi}}\qquad \text{and}\qquad m(y)=\frac{1}{\sqrt{4\pi}}\exp\{-y^2/4\}$$
Hence
$$\sup_{y\in \mathcal{Y}} \frac{p(y\,\vert\,\theta_\text{ml}(y))}{m(y)}=\infty$$
which is not very surprising in that $p(y|\theta_\text{ml}(y))$ will correspond to an overfit of the model, while $m(y)$ includes a penalty à la Schwarz (BIC). This may also connects with Lindley's paradox.


Can I add more blocks in a View page?

Question: I have a page that I created by View, I tried to create a template by creating node--view_page_machine_name.tpl.php, but it didn't work, the page did not change to this new template style.
How can I add more blocks/regions into a view page? Thanks.
Answer: In your view, under advanced there is a link called "Theme Information". If you open that up, there will be a list of all the different parts of the view that can be themed and a list of all the theme suggestions for each listed in order of broad to narrow.
You can create a theme file and naming it appropriately from the list of files in the theme information section. Once you've created the file, click on the "Rescan template files" button and the file you've created should be bold in the list.
Save the view and clear the cache.
Answer: But you don't mean the big Add button in your view which gives you the possibility to add blocks, attachements and else to your view, do you?
Be careful when you add blocks that way, you may want to override the display type, which can be chosen top left the moment you edit/add/delete a field, a filter criteria or else. Otherwise the changes will be applied to all your display types in that view.
Anyhow, I prefer to create an empty page first (via Content > Add Content > Page) and then I plant views blocks as much as I need on that page. So when I create a view I choose Block instead of Page.
And then when I'm done with creating my view I go to Structures > Blocks to choose the region and the site (the site I created first) where that block (views block) then should be displayed.
That way it's much easier I think to edit views 'cause now I have these Contextual Links on my page and when I hover over them they provide a quick link to edit the block or edit the view immediately.
Comment: Thank you for your reply, but that was not what I meant, this page is a view page, I want to add more stuff on this page, not the blocks that created by the same view. I actually want to style it just like they way I styled a node type of page. But thank you for your reply, I understand what you mean and that is also how I handle views generally.
Answer: Consider using panels :) https://drupal.org/project/panels. And please change title to page instead of pager, which is a very different thing!

Can I add more blocks in a View page?


Animating bar in canvas

Question: So, I'm trying to create an animated chart, where one bar is animated from bottom to top, at the time. The problem is when I run it, is shown only one bar with no animation.
Any one can help?
The code:
let canvas = document.getElementById('chart');
let ctx = canvas.getContext('2d');

let values = config().data;
let width = config().width;
let spaceBetweenBars = config().spaceBetweenBars;
let startingX = 50;

canvas.height = 300;
canvas.width = 400;
ctx.fillStyle = config().color;

for (let i = 0; i < values.length; i++) {
    let height = values[i];
    let l = 0;
    while(l < height){
        setTimeout(()=>{
            ctx.fillRect(startingX, canvas.height - height, width, l)
        },1000)
        l++;
    }
    startingX += width + spaceBetweenBars;
}

Comment: setInterval() instead of setTimeout will execute a function only once.
Answer: Since you don't give me the result of the config() I've invented a config object.
I've tried to do it the way you wanted to do it. I would have organised the data differently.
In order to animate the bars I'm using requestAnimationFrame since it's much more efficient. If you prefer you may use setInterval() instead.
Please read the comments in my code.

let canvas = document.getElementById('chart');
let ctx = canvas.getContext('2d');
canvas.height = 150;
canvas.width = 400;

let config = {width:30,height:0,spaceBetweenBars:5,color:"green"};

let values = [35,48,98,34,55];
// copy the values array and fill it with 0.
// This is the value of bars height during the animation
let currentValues = values.slice().fill(0); // [0,0,0,0,0]

let startingX = 50;

function drawBar(height,i){
    let x = startingX;
    x += i*(config.width + config.spaceBetweenBars);
    ctx.fillStyle = config.color;
    ctx.beginPath();
    ctx.fillRect(x, canvas.height,  config.width,  -height);
}

// I'm using requestAnimationFrame since it's much more efficient.

 function drawChart(){
 window.requestAnimationFrame(drawChart);
 for(let i = 0; i < values.length;i++) {
   if(currentValues[i] < values[i]){
     currentValues[i] ++;
     drawBar(currentValues[i],i)
   }
 }

}

drawChart()

canvas{border:1px solid;}
<canvas id="chart"></canvas>

Animating bar in canvas


Há alguma diferença entre uma tupla e um objeto com os mesmos tipos de elementos numa lista?

Question: Preciso operar com muitos pontos e fiquei em dúvida se ao usar um objeto, no lugar de uma tuple, para representar cada ponto irá aumentar o consumo de memória.
metodo1() é um método genérico para fazer algum tipo de operação com os pontos.
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int
    def metodo1(self):
        self.x = int(self.x/2)
        self.y = int(self.y/3)

p1 = [Point(i+1, i-1) for i in range(10)]
p2 = [(i+1, i-1) for i in range(10)]

Para esse exemplo, qual seria a melhor usar (a tupla ou a classe) em termo de performance, caso fosse fazer os mesmos tipos de operações com a lista depois?
for i in range(10):
    p1[i].metodo1()
    p2[i] = (int(p2[i][0]/2), int(p2[i][1]/3))

print(p1)
print(p2)

Comment: Dentro do seu `for` qual versão você preferiu? A do `p1` ou a do `p2`?
Comment: Prefiro a do p1, deixa tudo mais bem definido
Comment: mas como vou ter que ficar fazendo operações constantemente com os valores, então qualquer ganho ja seria muito bom
Answer: Sim - por padrão, apesar de uma instância de uma classe só consumir de memória os dados de cada instância, e os dados compartilhados com a classe (como o metodo1, nesse caso), são compartilhados entre todas as instâncias, por padrão, uma classe em Python vai ter um espaço de nomes (namespace) que é representado internamente por um dicionário: ele aparece como o atributo __dict__ na instância - e só ele consome quase 200 bytes.
Mas a linguagem resolve isso com um mecanismo que permite desligar o namespace dinâmico, reservando apenas espaço para atributos pré-definidos.São os "slots": na criação de uma classe sem o uso de dataclass, deve-se declarar o atributo __slots__ na classe, como em __slots__ = ("x", "y") : isso evita a criação do dicionário e de uma estrutura de dados usado para refereências fracas (__weakref__) e uma instância da classe fica equiparável, em consumo de memória, a uma tupla com a mesma quantidade de atributos.
O decorator dataclass implementa, a partir da versão 3.10 do Python, o parâmetro slots=True que faz a mesma coisa:
from dataclasses import dataclass
...

@dataclass(slots=True)
class Point:
    x: int
    y: int
    def metodo1(self):
        self.x = int(self.x/2)
        self.y = int(self.y/3)

(para versões anteriores, é só declarar o atributo __slots__ = ("x", "y") no corpo da classe, mesmo para uma dataclass)
Comment: Não seria bom ligar essa pergunta a sua resposta: [Qual é a finalidade de __slots__?](https://pt.stackoverflow.com/q/176757/137387)
Comment: Obrigado, não sabia sobre essa função do `__slots__` para evitar o desperdício. A outra resposta completamenta bastante sobre a minha duvida. Então vou poder continuar usando a classe dessa forma


List of path arrows in GAP

Question: I am using the QPA package with GAP and have the following problem:

I want to, given a path $p$, obtain a list (preferably ordered) of the arrows which make up $p$.

For example, if I have arrows $a,b,c$ in a path algebra $kQ$ and I have the path $p=ab$, I want the list $[a,b]$ to be returned from some function where I only have to input the path (and maybe the path algebra).
I did some digging and only found such a function for the quiver but not the path algebra: 3.7-4 in https://folk.ntnu.no/oyvinso/QPA/qpa/doc/chap3_mj.html#X7C8294338676C80E is a "WalkOfPath" function which returns such a list, but this only works for paths seen as paths in the quiver instead of paths seen as elements of a path algebra. There also does not appear to be a way to take a path of a path algebra and convert it back to a path in the quiver.
Any feedback is appreciated, cheers.
Edit: I have made a function which produces an unordered list of the arrows in a path, however this does not display them in the order in which they appear in the path (the latter would be better, so I am leaving the question open to answering). Also, my function does not include arrow multiplicities, which is something I really want out of it. Here is my function:
patharrows := function(pathalg, path)
 local i, arrows, output, rels, ideal;
 if path=Zero(path) then
    return [];
 fi;
 arrows := NthPowerOfArrowIdeal(pathalg, 1);
 output := [];
 for i in [1..Length(arrows)] do
    rels := [arrows[i]];
    ideal := Ideal(pathalg, rels);
    if \in(path, ideal) then
        Add(output, arrows[i]);
    fi;
 od;
 return output;
end;

Answer: Alas! I scanned the QPA manual and missed the following gem:
 LeadingMonomial(elem)

where elem is an element of the path algebra (call it $kQ$ with $Q$ being the quiver and $k$ the ground field). This function returns the tip of elem with respect to the given ordering for the Groebner basis calculations as a path in the quiver $Q$ rather than an element of the path algebra $kQ$. In particular, the tip of any monomial (regardless of the admissible ordering) is the monomial itself, and so if you input a monomial element of $kQ$ as elem then LeadingMonomial(elem) is the same monomial element regarded as a path in the quiver $Q$.
Now that we can play with our monomial element of $kQ$ as a path in $Q$, we can use the function
 WalkOfPath(path)

by setting path := LeadingMonomial(elem) and this function returns an ordered list of the arrows appearing in path. If you then want to interpret the arrows in this ordered list as elements of the path algebra $kQ$ rather than arrows in $Q$ (which is what the above does), you can use
 ElementOfPathAlgebra(kQ, path)

which embeds path into $kQ$.
Comment: Its amazing what a look into the manual can find (Variation on Westheimer's discovery: https://en.wikiquote.org/wiki/Frank_Westheimer).
Comment: Along the same line, in my work experience the manual was often sardonically referred to (especially when recommending its reading to newcomers) as 'the book of revelation'.

List of path arrows in GAP


Copy file from one domain to another

Question: I have two different websites running on two different servers with URL say http://192.168.0.102:1004 and http://192.168.0.122:1005.
Now i am trying to copy a image file from http://192.168.0.102:1004 to http://192.168.0.122:1005 using following code
if (File.Exists("http://192.168.0.122:1005/Assets/Images/Stores/14/14_Logo.png"))
{
    File.Copy("http://192.168.0.122:1005/Assets/Images/Stores/14/14_Logo.png", "http://192.168.0.102:1004/Assets/Images/Stores/14/14_Logo.png", true);
}

But If condition always return me false. However if i copy this URL in browser, it render me desired image on page.
If file exists, i need to copy it from source domain to target domain.
How to achieve this ?
Comment: How do i copy the file from that domain to target domain ??
Comment: You can't use System.IO.File methods with urls..
Answer: You cannot use the File object for these kinds of checks.
Please see the answer on: can I check if a file exists at a URL?
TL;DR
You should check if the server returns a 200 (OK) using the HttpWebRequest object.
Comment: You should look at various protocols. You can't simply use HTTP like that. You need to set up a server (with authentication) and decide exactly how to send files (with POST or PUT). SFTP is probably a more sensible protocol.
Comment: Thanks for your reply but this does not answer my question fully. How do i copy image from source domain to target domain then?
Comment: @RajeevKumar Download the image and save to disk

Copy file from one domain to another