How to prove this variation-of-constants formula?

Question: If $A ,B\in \mathbb{R}^{n\times n},v\in\mathbb{R}^n$,then from the variation-of-constants formula
$$\exp((A+B)\tau)v=\exp(A\tau)v+\int_0^\tau \exp(As)B\exp((A+B)(\tau-s))vds$$.
In my opinion,this formula can be seen as the soluion of the following ode:
$$ \frac{d v}{dt}=(A+B)v,$$
Thus, we can get
$$ \frac{d}{dt}(\exp(-At)v)=\exp(-At)Bv,$$
Then,
$$ \exp((A+B)\tau)v=\exp(A\tau)v+\int_0^\tau \exp(A(\tau-s))Bvds$$
So, how to get the first identity?
Answer: The solution to $\dot{x} = Ax + Bu$, $x(0) = v$ is given by
$x(t) = e^{At} v + \int_0^t e^{As} B u(t-s) ds$.
The solution to $\dot{w} = Aw + Bw$, $w(0) = v$ is given by
$w(t) = e^{(A+B)t}v$ and also by
$w(t) = e^{At} v + \int_0^t e^{As} B w(t-s) ds$, substituting gives the desired result.


Prefer quoting vs. escaping for ZSH completion

Question: ZSH is a wonderful shell, and all of the excellent auto-complete scripts written for it make it a breeze to learn and use.
However, I dislike that the autocompletions will use foo\ bar instead of 'foo bar'.
Is there any way to change this behavior?
Comment: Why do you prefer zsh to modify something which you have already typed on the command line? This would not be what I would intuitively consider as "completion". And, why does the backslash hurt you?
Comment: ZLE can totally modify what's already typed on the command line, and quoting is more pleasing on the eye than escaping, so this is an understandable question.
Answer: More of a comment, but need better formatting, so here goes.
I believe this should be possible in ZLE, but I don't know if there's code already available for this purpose, and it's been a while since I last programmed lower-level ZLE so I don't have time to freshen up and code it up myself...
However, this is sort of possible in using stock functions already. I'm talking about quote-and-complete-word:
# This widget uses the completion system to double-quote the current word
# if it is not already quoted, then attempts to complete normally.  If the
# normal completion fails, the quotes are removed again.
#
# To use it:
#   autoload -Uz quote-and-complete-word
#   zle -N quote-and-complete-word
#   bindkey '\t' quote-and-complete-word

Since it unconditionally quotes the word, it's obviously a bad idea to bind tab to it, but you may bind something else, say alt tab:
autoload -Uz quote-and-complete-word
zle -N quote-and-complete-word
bindkey '^[^I' quote-and-complete-word

(Or ^[[Z for shift tab.)
When you need to complete to something quoted, you press alt tab. Note that after completion, the cursor will be inside the quotes and you need to move one character right to leave the quotes behind, so it's unfortunately not ideal even as a variant.
Comment: Is there a variant of `quote-and-complete-word` which does not quote things which do not require quoting?


What is the name of this notation in this example by Couperin?

Question: Consider following excerpt from the beginning of the 2nd leçon of Couperin's Leçon des ténèbres pour le mercredi saint:

As you see, it uses a rather strange notation where, for instance, a bar of 3/2 containing six quarter notes is written as six notes with a white notehead (such as half notes) that are beamed (such as eighth notes).
Why is this, or does it has a specific name? (Is it related to half-time?)
Comment: @Tim they are sharps.  There was a time when key signature symbols were held to apply only to the octave to which they were actually applied.  Eventually, during the baroque period, people realized that this was unnecessary and began to consider that they applied to every instance of the indicated pitch class.
Comment: @phoog: Just wanted to clarify one point -- it would be more accurate to state that at this time, it was common to use a sharp or flat at every position *on the staff* (or immediately adjacent to it, as in the F-sharp in bass here). But it's not quite accurate to say that key signatures at this time only applied to octaves where notated, as a note on a ledger line at this time would still generally be presumed to have the same sharp or flat as other octaves, even if there were no corresponding symbol at the start of the staff. (What you say was true in some much earlier practices however.)
Comment: @Athanasius that more precise statement certainly agrees with my experience (which in any event is more extensive with 16th- and early-17th-century manuscripts and prints than with those from the eighteenth century).  Perhaps it is more accurate to see the key signature as a "set piece" then as it is now; it's only that the shape of the thing has changed.
Comment: FWIW a quick Google search for sheet music images suggests there are a few "modernized" scores that may be useful for comparing with this original
Comment: @Tim: Seems like left-adjusted sharps to me, the diagonal notation is present in other prints of that period as well); only that f sharp is repeated for octave.
Comment: While we're at it, what do the three stars represent after the treble clef sign - they *could* be #, but that would cover *both* F#s?
Answer: I've found this  pdf with an analog notation 3/2 like yours with 6 beamed white notes. They say
that these notes have the double value (quarter notes, not eighth) and they must be  played almost legato:
The example on the far right is notated with white notes. It says "On la note aussi de cette
façon6
". In fact, Couperin notices three of the four movements in Les Goûts-réünis in 3/2 time with white notes. In addition, Hotteterre says that this time signature is for slow pieces with pathetic,
tender music is used, and that the quarter notes are inegal (pointé) to be played here like
otherwise the eighth notes in other time signatures. In fact, the white quarter notes look almost like
Eighth notes off. In our transmission we kept the 3/2 time and the beamed ones
white note values doubled, i.e. eighths become quarters, etc. - The sentence starts with
"Pointé-coulé" called. In this context, "coulé" means "supple". We interpret this to mean that the quarters should be stroked back and forth, but so smoothly that it
almost like legato 7
http://www.guentersberg.de/vorwort/de/g224.pdf
Comment: If you're not familiar with rhythm in the French Baroque, you might have missed the statement about the quarter notes being 'inegal'.  Generally eighth notes in a running passage aren't played equally; rather the ones on the beat are slightly shorter.  You might think of this as being like the jazz practice of 'swing', except that it's reversed as to which notes are longer.
Answer: One name for this is white notation, although that term is typically associated with mensural notation.  To distinguish this from that, one may call it French baroque white notation.
See for example http://www.sibelius.com/cgi-bin/helpcenter/chat/chat.pl?com=thread&start=692692&groupid=3&&guest=1:

No, this will be French Baroque "white notation". A white notehead with one beam = a modern quarter note, with two beams = an eighth note, etc.

Another example is http://www.sibelius.com/cgi-bin/helpcenter/chat/chat.pl?com=thread&start=510933&groupid=3&&guest=1:

Forgive me if this has been covered elsewhere, but if so, I cannot find the answer. I am trying to create French Baroque style white notation - passages in 3/2 meter with regular whole and half notes, but with quarter, eighth, and smaller notes using white noteheads rather than black.
Answer: I find it a bit easier to read & interpret this mixed-(up)-notation style from another imslp version.  Other than dealing with flagged half-notes, it's closer to modern notation.
Comparing "beat by beat" to your original post, the other answers appear to be correct.


Negative variance of difference of binomial random variables

Question: Let $A = \text{binom}(n, p), B = n - A, D = A - B$
Actually, B is a complimentary binomial random variable of A, so it might as well be written as $B = \text{binom}(n, 1-p)$.
I calculated $E(D) = 2np - n$, but using the formula $V(D) = E(D^2) - E(D)^2$, I am getting $V(D) = -4np^2$ which is negative. How is this possible?
I think the answer should be $4np(1-p)$ because $D = 2A - n \implies V(D) = 4 V(A) + V(n) = 4np(1-p) + 0 = 4np(1-p)$. But I can't get it by algebra.
Comment: @taninamdar: The variance is $4np(1-p)$, since $D$ is twice a binomial, shifted. You gave a correct proof at the end of the post.
Comment: What does `A=binom(n,p)` mean? Do you mean $A \sim Binomial(n,p)$?
Comment: @wolfies I am not aware of the exact notation, but A is a binomial random variables with parameters n and p.
Answer: Yes. The variance will be $4np(1-p)$. As it is mentioned in Andre Nicolas comment. Hence it is not negative. Always positive.
Variance is $\ge 0$.
Comment: Shouldn't the answer be $4np(1-p)$? Because $D = 2A-n \implies V(D) = 4V(A) + V(n) = 4np(1-p)$.
Comment: I realized I was making a small algebra mistake due to which I missed the $+4np$ term in addition to $-4np^2$. Thanks anyway, I will accept this answer.


Express $\frac{\sin 7\theta}{\sin \theta}$ in powers of $\sin \theta$ only

Question: By using DeMoivre's theorm express
$$\frac{\sin 7\theta}{\sin \theta}$$
in the powers of Sine only
answer given in the book is
$$7-56\sin ^2\theta+112\sin ^4 \theta-64\sin^6 \theta$$
can any one help to solve the question
Answer: Steps To Carry Out
1) First take a look at this link which is a guide for DeMoivre's formula.
2) Using step 1 show that
$$\sin (7x) = 64\sin \left( x \right)\cos {\left( x \right)^6} - 80\sin \left( x \right)\cos {\left( x \right)^4} + 24\sin \left( x \right)\cos {\left( x \right)^2} - \sin \left( x \right)$$
3) Replace $\cos^2(x)=1-\sin^2(x)$ and obtain
$$\sin (7x) = 7\sin \left( x \right) - 56\sin {\left( x \right)^3} + 112\sin {\left( x \right)^5} - 64\sin {\left( x \right)^7}$$
4) Divide by $\sin(x)$
$${{\sin (7x)} \over {\sin (x)}} = 7 - 56\sin {\left( x \right)^2} + 112\sin {\left( x \right)^4} - 64\sin {\left( x \right)^6}$$
Answer: Take a look at Chebyshev Polynomial of the Second Kind.
Since $U_6 (\cos \theta) = \frac{\sin 7 \theta}{\sin \theta}$, we can find $U_6(x)$ be the recurrence given in the wikipedia link, i.e. $$U_0(x)=1$$ $$U_1(x)=2x$$ $$U_{n+1}(x)=2xU_n(x)-U_{n-1}(x)$$
We can then use $\cos^2 \theta = 1-\sin^2 \theta$ to convert it into a polynomial of $\sin$.
If you want to use DeMoivre's Theorem, use $$(\cos \theta + i \sin \theta)^7 = (\cos 7 \theta + i \sin 7 \theta)$$
Expand L.H.S to find the desired value.
Comment: OP want's the solution with DeMoivre's theorem
Comment: I edited the solution. I found that right after I wrote my solution :(
Comment: (+1) for the chebyshev thing! I didn't know that! :)
Answer: $(\cos x+i\sin x)^7=\cos 7x+i\sin7x$.
We have
$$(r+t)^7=r^7+7r^6t+21r^5t^2+35r^4t^3+35r^3t^4+21r^2t^5+7rt^6+t^7$$
 hence, making $\sin x=t$ and $\cos x=r$ and having in account the powers of $i$, we get
 $$\sin 7x=7r^6t-35r^4t^3+21r^2t^5-t^7$$ so, because of $\cos^2x=1-\sin^2x$,
$$7t-21t^3+21t^5-7t^7-35t^3+70t^5-35t^7+21t^5-21t^7-t^7=-64t^7+112t^5-56t^3+7t$$
Now dividing by $t$, we finish.
Answer: $sin(7\theta)=sin(\theta+6\theta)=sin(\theta).cos(6\theta)+sin(6\theta)cos(\theta)$ then we have $cos(6\theta)=cos(3\theta+3\theta)=cos(3\theta).cos(\theta)-[sin(3\theta).sin(3\theta)]$ now we know $cos(3\theta)=4cos^3(\theta)-3cos(\theta),sin(\theta)=3sin(\theta)+4sin^3(\theta)$. Now you can just back substitute and get the job done. Hope its clear.


How to change the format that shows the autocompletion of reference entities?

Question: I am trying to change the format that it shows by default in the text fields that have an associated reference entity.
I found an article where a format modification is made, I think it may be a good starting point, but this module changes the format of all the fields of the whole site, what I am trying to do is that I can define the format by type of content, that is, for Articles, it would have one format and another type of content, depending on what is most convenient.
For example, in the module mentioned, it changes the behavior of the autocomplete globally, is there a way to do it by type of content?
<code><?php
namespace Drupal\alter_entity_autocomplete\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;

use Symfony\Component\Routing\RouteCollection;

class AutocompleteRouteSubscriber extends RouteSubscriberBase {
  public function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.entity_autocomplete')) {
      $route->setDefault('_controller', '\Drupal\alter_entity_autocomplete\Controller\EntityAutocompleteController::handleAutocomplete');
    }
  }
}
</code>
Is there any way to do it?
The github project of the module
Answer: You can filter for the entity type & bundle in the getMatches() method.
It is also possible to add specific handlers to your forms: https://www.qed42.com/blog/autocomplete-drupal-8


Logical Formalization of: "Children don't eat pasta with spinach or mushrooms on it"

Question: I want to formalize the following sentence in predicate logic:

If a children has spinach or mushrooms on its pasta then it will not
  eat its pasta.

The headline contains a shorter version. I have four solutions where l like your opinion or recommendation on:
\begin{align}
\forall x \forall y \, &((IsChildren(x) \land IsPasta(y) \land {} \\
&\land (hasIngridient(y,Spinach) \lor hasIngridient(y,Mushroom)) \rightarrow \neg Eatspasta(x,y) )
\end{align}

Modification: Could I omit $IsChildren(x)\land IsPasta(y)$ though naming $x$ in child and $y$ in pasta? For example:
\begin{align}
\forall child \forall pasta \, &((hasIngridient(pasta,Spinach) \lor hasIngridient(pasta,Mushroom)) \\
&\rightarrow \neg EatsPasta(child,pasta) )
\end{align}

Q1.1 Are variables allowed with more then one letter?
Q1.2 I think the name of a variable (is child or $x$) does not matter for its interpretation. So after the first modification child could be anything from my discourse universe.

Modification: Could I omit $\forall y$ by changing the formalization as follows:
\begin{align}
\forall x \, &(isChilrden(x) \land (hasIngridientSpinachOnPasta(x) \lor hasIngridientMushroomOnPasta(x)) \\
&\rightarrow \neg EatsPasta(x) )
\end{align}
Modification: Could I omit $\forall y$ by changing the formalization as follows:
\begin{align}
\forall x \, &(isChilrden(x) \land (hasIngridientSpinach(Pasta) \lor hasIngridientMushroomOnPasta(Pasta)) \\
&\rightarrow \neg EatsPasta(x,Pasta) )
\end{align}
Modification: Could I say instead there exist no chilrden that eats pasta with Spinat und Mushrooms:
$$\neg \exists x \forall y x(isChilrden(x) \land (Pasta(y,Spinach) \lor Pasta(y,Mushroom)) \rightarrow EatsPasta(x,y) )$$

Main question: which one are incorrect and why?
Answer:
Q1.1 Are variables allowed with more then one letter?

It's unusual in maths; usually a one-letter symbol with descriptive index is preferred, such as $n_\mathrm{mushrooms}$. But IMO multi-character names are fine, as are multi-character functions ($\sin$, $\log$...). But LaTeX won't typeset these properly if you just write out the letters like that; notice the bad kerning in your post. You should instead wrap such names in a suitable \math??{.} styling. Options are:

$Spinach$ ($Spinach$) (bad!)
$\mathit{Spinach}$ ($\mathit{Spinach}$)
$\mathrm{Spinach}$ ($\mathrm{Spinach}$)
$\mathbf{Spinach}$ ($\mathbf{Spinach}$)
$\mathsf{Spinach}$ ($\mathsf{Spinach}$)
$\mathtt{Spinach}$ ($\mathtt{Spinach}$)

I would recommend \mathit for multi-character variables, \mathrm for constants and standard functions, and \mathsf or \mathtt for special situations (like when you're paraphrasing computer code).

Q1.2 I think the name of a variable (is child or x) does not matter for its interpretation

Correct. This is what's in CS called $\alpha$-conversion: any variable that's quantified over with $\forall$ or $\exists$ can be renamed.
Your modifications 2 and 3 don't quite express the original thing, because you don't quantify over the pasta anymore. Basically this means that the pasta is a "global constant", you only ever consider one. This is often done in maths/science for simplification, but logic-wise it does make a difference.
Modification 4 just turns around the quantors. This can always be done in classical logic:
$$
  (\forall x. \neg P(x)) \leftrightarrow \neg(\exists x. P(x))
$$
Comment: Thanks for your comprehensive reply. Regarding Modification 2 and 3: do you think in consideration of the original sentence that it is necessary to quantify over pasta?


What are the differences between Hilbert's axioms and Euclid's axioms?

Question: Euclid had his axioms.
Why would we need Hilbert's modern axiomatization of Euclidean geometry?
What are key differences between the two sets of axioms?
Comment: There are really simple things that can't be proved via Euclidean postulates - they are hidden assumptions of Euclid. If I recall, the idea that a line is ordered is one of them - that if $a,b,c$ are three points on a line, then exactly one of the three is "between" the other two.
Comment: Hilbert saw the need for a *completeness* axiom. Say you have two points, $P$ and $Q$, and you draw a circle centered at $P$, and a circle centered at $Q$, both with radius $PQ$. How do you know that the two circles intersect? That there aren't "holes" in the plane where the intersections ought to be? Euclid's axioms don't do this for you; Hilbert's do.
Comment: Did you try to look up Hilbert's axioms?
Comment: read this: http://mathdl.maa.org/mathDL/22/?pa=content&sa=viewDocument&nodeId=3729&pf=1
Answer: The axioms of Euclid are insufficient, by a fair distance, for proving the theorems in Elements. The first mistake is in the first proposition, which is essentially about drawing an equilateral triangle.
The procedure involves drawing certain circles. Then the equilateral triangle has vertices at certain places where the circles meet. But Euclid does not show that the circles indeed do meet.
One major omission was noticed by Pasch, in the nineteeth century. Suppose that $ABC$ is a triangle, and let $\ell$ be a line that goes through a point $P$ on an edge of $\triangle ABC$. Then there is a point $Q$ (possibly equal to $P$,) on another edge of the triangle, such that $\ell$ passes through $Q$. The assumption that this is true is used tacitly in Elements. It is neither derived nor derivable from Euclid's axioms.
Around $1900$, Hilbert did a thoroughgoing axiomatization, with all details filled in. The result is vastly more complicated than the partial axiomatization by Euclid. One feature of the Hilbert axiomatization is that it is second-order. A benefit is that one can then prove that, for example, the Euclidean plane can be coordinatized using the real numbers.
Later, in the $1930$'s, Tarski produced an axiomatization that is first-order. Inevitably, we lose the result that the models are isomorphic to the coordinate plane $\mathbb{R}^2$. But there are bonuses, such as the later result (again by Tarski) that there is a decision procedure for elementary geometry.


Ansible not using correct vars when specifying?

Question: I'm having some issues with my ansible playbook not adding in the right variables. Here is the task.
 #Change name: to be the name of whatever group you want to add
 - name: Add new group if necessary
   group:
    name: "{{ group_name }}"
    state: present

# Change name: to be the name of the user you wish to add.
 - name: Manage user accounts
   user: name={{ item }} state=present group={{ group_name }}
   with_items: "{{ users }} "

Here are the variable files
---
users:
 - test1
 - test2
 - test3

group_name:
 - developers

For some reason when I am running this it creates the group and names it this
'developers'
Then, the add user part of the play actually is looking for a totally different group name just [developers]
See failed output.
PLAY [users] ******************************************************************

GATHERING FACTS ***************************************************************
ok: [172.17.51.202]

TASK: [user-manage | Add new group if necessary] ******************************
changed: [172.17.51.202]

TASK: [user-manage | Manage user accounts] ************************************
failed: [172.17.51.202] => (item=test1) => {"failed": true, "item": "test1"}
msg: Group [developers] does not exist
failed: [172.17.51.202] => (item=test2) => {"failed": true, "item": "test2"}
msg: Group [developers] does not exist
failed: [172.17.51.202] => (item=test3) => {"failed": true, "item": "test3"}
msg: Group [developers] does not exist

FATAL: all hosts have already failed -- aborting

Here is the group it actually creates.
I cannot figure out why they are both looking for different variables and neither one is actually the correct one that I have specified.
Any ideas?
In response to Petro:
I changed it from a list to a singular variable
---
users:
 - test1
 - test2
 - test3

group_name: developers

I still get this error
failed: [172.17.51.202] => (item=test1) => {"failed": true, "item": "test1"}
msg: Group [developers] does not exist
failed: [172.17.51.202] => (item=test2) => {"failed": true, "item": "test2"}
msg: Group [developers] does not exist
failed: [172.17.51.202] => (item=test3) => {"failed": true, "item": "test3"}
msg: Group [developers] does not exist

FATAL: all hosts have already failed -- aborting

So that didn't work. Any other ideas?
EDIT 2:
Petro that actually did work. Sorry. I had messed up. Your's was the right answer.
Thanks a lot!
Answer: You made "group_name" a list instead of single value.  Change your vars file to:
group_name: developers

and it should work
Comment: I updated my original comment to include your advice. Still does not work. See above.


can i restore soft deleted entity in apache atlas?

Question: i want restore a soft deleted entity in apache atlas, cause i want to delete the classification tagged on that entity.
i'm using atlas for data governance in HDP cluster.
And i deleted an entity without deleting the classification tagged on that.
When i want to delete the classification tagged on that entity, it turns out i can't delete that classification.
Cause the tagged entity was soft deleted, so atlas thought the classification i want to delete still have references.
So i want to restore the soft deleted entity, i found there are no API support restore in Atlas 7.0, so i try to change the data in related Solr index and Hbase tables.
I changed the data in Solr index "vertex_index" from "DELETED" TO "ACTIVE', and the data in Hbase table "ATLAS_ENTITY_AUDIT_EVENTS" show the entity status is "ACTIVE".
But when i search it in Atlas UI, it still shows that the entity is 'DELETED'.
So, i'm wondering do i miss some thing, can anyone know where exactly atlas store its entity data, and if i can't restore that data, can i delete it in the database or some where else?
Answer: You can directly delete the classification associated with the deleted entity. Atlas provides REST API for the same.
"/v2/entity/guid/{guid}/classification/{classificationName}"


Is there a way to save drafts of posts?

Question: I frequently start a question or answer, but get interrupted by other things.
Does anyone know if there is a way to save a post as a draft (obviously, other than to start writing it somewhere else and save it there)?
If not, is that a feature that SE could enable, or we could request to be put in to some future build?
Comment: Chrome/Firefox/Safari have a neat extension called "Lazarus" that will save a draft for any web form. http://getlazarus.com/download
Answer: Yes.
Typically as you type content for a question or an answer, it will auto-save a draft periodically.
You may need to wait up 45 seconds if you want to capture everything you've typed since the last auto-save.
Comment: Apparently you can use **Ctrl+S** in Firefox to manually save your draft as well.

Is there a way to save drafts of posts?


Direct Product of a Group and itself

Question: Let A be a cyclic group with prime order p. Then the direct product $A\times A$ should have order $p^{2}$ according to wikipedia.
http://en.wikipedia.org/wiki/Direct_product_of_groups#Elementary_properties
However I found this theorem in the book that states for subgroups H,K, of G that
$ o(HK) = o(H)o(K)/((o(H \cap K) ) $
But $A$ is a subgroup of $A$ and $A \cap A = A$ so then  $ o(AA) = o(A)o(A)/o(A) = o(A) $
The last result makes sense to me, as $AA = A$.
Maybe I'm confused about something. The external direct product $A\times A$ is isomorphic to the internal direct product $AA$, but I'm getting different orders for them.
What am I doing wrong ?
Comment: The direct product $A \times A$ contains two copies of $A$, and their intersection is not another copy of $A$.
Answer: There are certain conditions that have to be satisfied for a group to be considered an internal direct product of two subgroups.
Let $G$ be a group and let let $H$, $K$ be subgroups. Then $G$ is the internal direct product of $H$ and $K$ if $G=HK$, $H\cap K =1$ and $hk=kh$ for all $k\in K$, $h\in H$. In this case your order formula gives the correct order. In your example $A\cap A$ has nontrivial intersection so it cannot be considered an internal direct product. The idea here is that every element can be expressed uniquely in the form $g=hk$ and $(h_1k_1)(h_2k_2)=(h_1h_2)(k_1k_2)$, which makes the isomorphism to the external direct product much clearer.
In general multiplying two groups may not even be a group, though if one is normal it will be, but it still may not be a direct product. Look up semidirect product
Comment: Okay thanks I understand it now.
Answer: There are a couple of notions in play here. The internal direct product, the external direct product, and the internal (not necessarily direct) product.
The thing you are interested in is the external direct product. It is defined as follows: Let $G$ and $H$ be groups. The external direct product of $G$ and $H$, written $G\times H$, is defined to be the group that has the cartesian product $G\times H$ as underlying set, and where the multiplication is given by $(g,h)(g',h') = (gg',hh')$. It is then clear that $|G\times H| = |G||H|$.
The internal product of subgroups is the following: Let $G$ be a group and $H$ and $K$ subgroups of $G$. Define $HK = \{hk | h\in H, k\in K\}$. This is now a subset of $G$ of order $\frac{|H||K|}{|H\cap K|}$ but it need not be a subgroup.
The internal direct product is the following: If $H$ is a group with normal subgroups $H$ and $K$ such that $|H\cap K| = 1$ and such that $HK = G$ then we say that $G$ is the internal direct product of $H$ and $K$.
The connection between the internal and external direct products is the following: If $G$ is a group which is the internal direct product of two normal subgroups $H$ and $K$, then $G$ is isomorphic to the external direct product $H\times K$ via the map $\varphi: H\times K\to G$ given by $\varphi(h,k) = hk$. Similarly, the external direct product $H\times K$ is the internal direct product of the two subgroups $\{(h,1) | h\in H\}$ and $\{(1,k) | k\in K\}$.
For the specific question, just because two groups are "the same", they can still form an external direct product as described above and then the two subgroups $\{(a,1) | a\in A\}$ and $\{(1,a) | a\in A\}$ are isomorphic but not the same, and in fact they intersect trivially.
Answer: If $H$ and $K$ are subgroups of $G$, then one of the requirements for $HK = \{xy : x\in H, y\in K\}$ to be an internal direct product is that $H \cap K = \{1\}$. So the only way $A \times A=A^2$ could be an internal direct product would be if $A =\{1\}$.
As an external direct product, $G = A \times A = \{(x,y) : x, y \in A\}$.
The subgroups H = $A \times \{1\}$ and $K = \{1\}\times A$ are both "copies" of the group $A$.
Note that $H \cap K = \{(1,1)\}$, and $o(H)=o(K)=o(A)=p$.
$o(G) = o(H \times K) = \dfrac{o(H) \ o(K)}{o(H \cap K)}= o(A)^2=p^2.$

Direct Product of a Group and itself


Alternative to Views

Question: Suppose we have numerous entities of types Alpha and Bravo. Alpha entities could easily be taxonomy terms and Bravo – content nodes. Bravo entities can reference multiple
Alpha entities each; whereas, Alpha entities (taxonomy terms) are completely agnostic of any other entities.
The exercise is to aggregate all Alpha entities that are referenced together (by the Bravo entities) with a given Alpha entity.
Example: Alpha entity type is a taxonomy vocabulary containing Artists. Bravo is a Project content type. Sometimes Artists collaborate on Projects; therefore, some Projects have multiple Artists. An example of the aggregation in question would be to list all Artists that a given Artist has collaborated with (has been referenced in the same Project with).
I am building the information architecture for my first Drupal project, in which metadata and it's inter connectivity is important. I have achieved this aggregation using Views, but Views seems impractical for my uses. In many cases I want to list just Taxonomy term names like this:

Nirvana has collaborated with: Biggie Smalls, Lil' Wayne, Lil' Jon.

(Of course, I wouldn't want my Taxonomy system to make jokes)
What aggregation solutions are there? Do you have tips? Have you done something like this?
Why I'm looking for an alternative to Views:
The reason I find Views impractical for this use: my impression is that it's geared more towards heavier listing, like catalogs and is hard to squeeze into "lighter" roles (like the one in my example). If I am fooling myself, do correct me.
Comment: My personal experience is that we can use views for almost all kinds of listing with a little bit of tweaking here and there.
Comment: The reason I find Views impractical for this use: my impression is that it's geared more towards heavier listing, like catalogs and is hard to squeeze into "lighter" roles (like the one in my example). If I am fooling myself, do correct me.
Comment: The alternative to views is to code your own queries. http://drupal.org/node/242311 If you can't write your own queries then views is your only choice and it is great for something simple and complex.
Answer: If you're looking for a good core alternative to select entities, using custom queries, make sure you familiarize yourself with Entity Field Query (EFQ)
e.g, fetch 10 published article nodes with field_my_field value 'foo':
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->propertyCondition('status', 1)
      ->fieldCondition('field_my_field', 'value', 'foo')
      ->range(0, 10)

$result = $query->execute();

if (isset($result['node'])) {
  // nids are here
  $nids = array_keys($result['node']);
  // nodes can be loaded as such
  $nodes = entity_load('node', $nids);
}

More EFQ info here
Comment: Thanks for the tip. Note I am very green at coding Drupal. How do you implement custom functions (like the one you're recommending me to code) into a Drupal site?
Comment: you do this usually in a new module (you'll create) and implement that as a page callback, see hook_menu() for reference.
Answer: Views performance is OK, if you use caching. At least in this example, data won't change alot over the years. And if you preprocess, queries will be much lighter.
Suggested steps:
A. Outer view settings

Using your example, add a Term Reference field to the Projects content type, which will reference the Artists taxonomy (allow for multiple terms).
Make a view on the Artist taxonomy terms, then add an inner view as field (call it collaborators). The connection to the inner view is defined using the views_field_view module.

B. Inner view settings (picture below):

Make the inner view field-based, and set the term ID as it's contextual filter (under advanced settings). It should only show projects which add the term ID to their term reference field.
Change the fields of the inner view so it will only have one field - the term name, and don't provide default wrapper elements - to make it lighter. Also use a plain text formatter for the field so that there won't be any extra output - it will be even lighter.
Field settings of the 'Artists' field on the inner view: Open the collapsed 'multiple field settings' link on the field settings dialog and uncheck the option "Display all values on the same raw". Now each value will be on a separate row.
Add a new filter criteria to filter all terms whose id is equal to the contxtual filter we got as argument.
Go to the 'Query settings' under 'Advanced' and set the 'Distinct' option.
Also activate block caching.
Comment: Thank you for your response. I will try this now. By the way, is "Views Caching" as in [Views content cache](http://drupal.org/project/views_content_cache) what you meant by preprocessing?
Comment: I'd like to express my gratitude again for your step by step tutorial. It has been interesting to use the views_field_view module; and you're right about the caching, the outer (parent) view takes 150ms to render. However, I will continue looking for other solutions, this approach (all approaches with Views that I've tried) is cumbersome, and the output is extremely inflexible.

Alternative to Views


É necessário ativar o Cross-Origin Requests para ASP.NET Web API?

Question: Eu fiz uma aplicação de teste, onde aponto para uma web api que está online,  o endereço desta api funciona e retornar os dados se for postada na URL browser, ela faz um GET.
Na aplicação de teste eu tenho:

    <Select id="method">
        <Option value="get"> GET </option>
        <Option value="post"> POST </option>
        <Option value="put"> PUT </option>
    </Select>

    <Input type="button" value="Experimente" onclick="sendRequest()" />
    (Resultado)

@section scripts {

}

Não está me retornando os dados, inspecionei os dados e não retornar erro, apenas "XHR finished loading: GET"
Comment: @LucasCosta, eu vou pesquisar sobre isso
Comment: Não sou perito em ASP.net @itasouza, mas sim, o servidor (quem serve) tem que permitir executar uma ação. A diferença de funcionar o GET pelo Browser e não por Ajax é que Ajax faz um XMLHttpRequest e essa informação vai no header da requisição. Portanto, a única forma elegante e correta é a aplicação ASP permitir Cross-Origin.
Answer: Olá,
Se a API estiver em outro domínio, que não o da aplicação ,  você terá de ativar o cross origin(CORS) na API.
Por exemplo:
Se tiver a aplicação estiver em:dominio.com,
E a api em dominio.com/api você não precisará de cross origin
Agora se a aplicação estiver em:meudominio.com,
E a api em outrodominio.com, é preciso habilitar o cross origin.
Não conheço .net, mas imagino que esse link sirva:
https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Mais específicamente essa parte:
using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

e essa:
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebService.Controllers
{
    [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}

No parâmetro origins você deverá colocar o endereço da aplicação que quer chamar a api. Para testes você pode colocar "*", mas não envie para produção
Abraço!


Error "Expected OAuth 2 access token" on container-bound script

Question: I want to filter a google sheet for one value only, as in this question/answer.
I have activated sheets-api and looked through documentation, how to add oauth2 verification. Concluded, that it should happen automatically, since the script is container-bound.
var ss = SpreadsheetApp.getActiveSpreadsheet();

SpreadsheetApp.setActiveSheet(ss.getSheetByName('Aufgaben')); // change active sheet

var filterCriteria = {"type":"TEXT_CONTAINS","values":[{"userEnteredValue": "0001" }]}; // set filter

var filterSettings = {};
filterSettings.range = {sheetId: ss.getSheetByName('Aufgaben').getSheetId(), startRowIndex: 1};
filterSettings.criteria = {};
var columnIndex = 4;

filterSettings['criteria'][columnIndex] = {'condition': filterCriteria}; // Modified

var request = {setBasicFilter: {filter: filterSettings}};
Browser.msgBox(JSON.stringify({'requests': [request]})); //only works, when this line is added!
Sheets.Spreadsheets.batchUpdate({'requests': [request]}, ss.getId()); `

The code works, but ONLY if I add Browser.msgBoxone line above Sheets.Spreadsheets.batchUpdate(). Otherwise I get this error: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
    at onEdit(test:127)
Since I've already spent hours trying to solve this.
Thank you.
Comment: You need "installable" edit trigger instead of a simple one.
Comment: I cannot understand about `The code works, but ONLY if I add Browser.msgBoxone line above Sheets.Spreadsheets.batchUpdate()`. When the script is run by script editor, it works. But if it's run by the simple trigger and custom function, such error occurs. Custom function cannot use `Browser.msgBox`. So if you run it with the simple trigger, how about modifying to the installable trigger? [Ref](https://developers.google.com/apps-script/guides/triggers/installable) At that time, please modify the function name in order to prevent the double running. If I misunderstood your situation, I apologize.
Comment: My code is triggered by `onEdit()`. I inserted `Browser.msgBox...`as a simple way to check the parameters and all of a sudden, the code did't produce the error, that was chance. I just don't understand, how this could prevent the error? If I comment out or delete `Browser.msgBox...`I get the oauth-error.
Even works with `Browser.msgBox('hello')`. Very strange.
Comment: Thank you for replying. At first, I have to apologize for my poor English skill. When your script is used, [TheMaster`s comment](https://stackoverflow.com/questions/57344419/error-expected-oauth-2-access-token-on-container-bound-script?noredirect=1#comment101185094_57344419) will resolve your issue.
Comment: @Tanaike I appreciate your help. I don't know why, but with sheets-api I did not get it to work. But [ADW 's answer](https://stackoverflow.com/a/57345370/11874332) worked for me – Google Apps Script Spreadsheet Service instead.
Comment: Thank you for replying. I'm glad your issue was resolved.
Answer: Perhaps the

// set filter

is causing problems?
This worked for me without oauth2 verification:
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  SpreadsheetApp.setActiveSheet(ss.getSheetByName('Aufgaben')); // change active sheet

  var filterCriteria = {"type":"TEXT_CONTAINS","values":[{"userEnteredValue": "4210"}]}; // Modified

  var filterSettings = {};
  filterSettings.range = {sheetId: ss.getSheetByName('Aufgaben').getSheetId(), startRowIndex: 1};
  filterSettings.criteria = {};
  var columnIndex = 4;

  filterSettings['criteria'][columnIndex] = {'condition': filterCriteria}; // Modified

  var request = {setBasicFilter: {filter: filterSettings}};
  Sheets.Spreadsheets.batchUpdate({'requests': [request]}, ss.getId());

Edit
I'm was not able to replicate the issue with the code you provided. Even with the message box, I got an error.
If you are triggering the filtering function when the sheet is edited, you may want to try a version of the Google Apps Script Spreadsheet Service:
function onEdit(e) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var criteria = SpreadsheetApp.newFilterCriteria().whenTextContains("0001").build();
  var lastRow = sheet.getLastRow();
  var lastCol = sheet.getLastColumn();
  var range = sheet.getRange(2, 1, lastRow - 1, lastCol);
  range.createFilter().setColumnFilterCriteria(4, criteria);
}

Refs
newFilterCriteria()
whenTextContains(text)
createFilter()
setColumnFilterCriteria(columnPosition, filterCriteria)
Comment: Thanks for your reply, @ADW. That was my mistake, intered `// set filter` in the middle of the line instead of replacing `// Modified`.
Comment: That worked! I wasn't able to find the functions you provided for using Google Apps Script Spreadsheet Service, neither here nor on google. Thank you.


Cumulative sum of pca explained variance greater than 1

Question: I am getting strange result.
data_scaled = StandardScaler().fit_transform(dat_final)
pca = PCA(.99)
pca.fit(data_scaled)
print(np.cumsum((pca.explained_variance_)))
plt.plot(np.cumsum((pca.explained_variance_)))
result I am getting is
[ 2.9391298   5.75291849  7.18909411  8.39200852  9.22317861  9.89984402
 10.46682293 11.0008235  11.40999925 11.73238142 11.97820388]
how can the explained variance can be more than 1.
Please correct if I am wrong here.
Comment: It is quite possible if the total variance in the data is larger than 1. Perhaps you were thinking of the *proportion* of explained variance instead?
Comment: I am voting to leave this open. It's not really about R - similar issues could occur with the output of any software for PCA.
Answer: This is correct. Remember that the total variance can be more than 1! I think you are getting this confused with the fraction of total variance. Try replacing explained_variance_ with explained_variance_ratio_ and it should work for you.
ie.
print(np.cumsum((pca.explained_variance_ratio_))


Which C hole to use in the modern chromatic harmonica?

Question: Let's talk about the standard modern chromatic, tuned to the key of C.
On that instrument,the same C note appears twice at two adjacent holes, both blow notes. The first C hole ends an octave, the second one begins a new octave.
That being the case, when navigating through a piece of music and C has to be played, the player always has to choose which C hole to use. (Unless you're playing the lowest or very highest/last hole -
 C.) What are the criteria for choosing which C to play?

I am not a very serious player on the chromatic, but I do fool around with it sometimes. My general rule is that if I get to the end of an octave and intend to continue playing into the next octave, I jump to the second C hole to start the new octave. But if I intend to stay in the same octave and move back down (or just stop playing) I play the first C hole.
Can anyone add to this? Is there something wrong with my method - for example, some inefficiency or error it can lead to?
Comment: @Tim My harmonica has two holes for each C, like Stinkfoot describes. The reason why this exists is because there are more draw notes (D, F, A, B) than blow notes (C, E, G). By having two holes per C, the positions of blow and draw notes are neatly aligned across the entire harmonica. However, I'm a pretty sloppy harmonica player, and when I play a C note I indiscriminately blow into both holes at the same time. This is probably not proper technique. :-)
Comment: My personal issue with blowing through both C holes is that it creates a slight of tremolo (even if barely audible), and probably makes the note a bit louder than all others. That's probably not something you should do unless you really intend to get that effect. :)
Comment: Just dug out some of my chromonicas - 4 octave Hohners, a couple of them - and they all have one blow hole for C. Can't understand why they'd need two True, it means the lowest hole is C blow, D draw, and the next octave hole is B draw, C blow, making the next one up D draw, E blow. They're at least 50 yrs old, still playing well, so maybe the design has changed, but these are/were simple enough to play.   Thought about finding an older model?!!
Comment: the plot thickens! Just found four chromonicas - all C, and all work the same as I said, except one, which plays C# *until* the button is pressed in!! Another couple only have single C holes as well. The C# is somewhat intriguing though... Chromoni**K**a III.  I remember talking about it, but still think mine do the job well enough. Each octave becomes the same blow/draw...
Comment: Blowing through *two* C holes will use twice the air, I'd have thought.
Comment: @LeeWhite - could be that the two Cs aren't exactly in tune, thus creating *beats*.
Comment: @Tim - see: https://en.wikipedia.org/wiki/Chromatic_harmonica  . There are variations. Most common layouts have the double C but check out https://en.wikipedia.org/wiki/Chromatic_harmonica#Alternative_tunings - Classical tuning - sounds like that's what you have. _an't understand why they'd need two_ - we talked around this a couple of months ago in my question about just that - why A->B is two draws, unlike the rest of the scale.
Comment: @LeeWhite - see  https://music.stackexchange.com/questions/62042/b-c-on-a-chromatic-harmonica  - I asked it not long ago. _This is probably not proper technique_ - probably not... LOL
Comment: @LeeWhite - On second thought, if it's easy for you and you play it cleanly (I've never tried - the thought never occurred to me...) , **why not** play both? Keep your options open! Maybe Post it as an answer...?
Comment: @Tim - I have a 4 octave 16 hole Hohner "Professional Chromonica" (great sound) that's about 20 years old. It has the double C. I also have a 12 hole 3 octave Hohner "Super Chromonica" that is fairly new - it also has the double C. But if I'm not mistaken, that model is actually a reissue of their original Chromonica model - from 1928. Are you sure yours are stock? This is interesting - "for those who find interest in such things" : _Chromonica Trivia!_
Comment: @Tim  _which plays C# until the button is pressed in_ - I'm not sure I understand the layout you're describing. Check out the link I posted up above on alternate tunings. Are you talking what they're calling  _bebop tuning_ there? (This needs to become a separate question about the variations of the chrom's tunings)
Comment: No, there's one chromonika III -spelled as such - that plays in C# with the button released, and drops to C when it's depressed (so do I !!), unlike any others I've seen which work in the 'normal' way - C , and C# button in. It's stamped C, not C#, and although it's German, I don't think notes B and H get into the equation!  Will check link asap.
Comment: @Tim - OK - I understand. I assume it works that way for all the notes?
 If so it's called **_Irish Tuning_** there - the slide flattens by a semi-tone instead of raising by semi-tone.
Comment: @stinkfoot I caution you against wikipedia for harmonica.  It's misinformation and omission in equal measure with actual information in my experience.
Comment: @Some_Guy - I caution myself against wikipedia for **anything.** I'm not betting anything on what I found there.
Answer: I'm not actually really a chromatic player, I'm much more a diatonic player.  Having said that, here's the answer: there is no hard and fast rule, it's simply whichever one is more convenient for a given passage.  Practically, for the 2 blow notes, it makes very little difference.  Obviously, if you're about to play an A or a G then it's easier to play the first C, and if you're about to play an E or an F then it's easier to use the last one, to not have to skip over a hole.
The much more pressing question is whether to use the C on the blow with the slide out, or the C on the draw with the slide in: using the latter can make certain passages much easier, not having to reverse breath direction coming from a quick A for example.

If it seems strange and illogical that most notes on the chromatic harmonica have no enharmonic equivalent, but that C has 3 enharmonics, and 2 of them are right next to each other, that's because it is strange and illogical, but see this question for why that came about B -> C on a chromatic harmonica :
Comment: _The much more pressing question is whether to use the C on the blow with the slide out, or the C on the draw with the slide in_ **Yes.** Same question also applies to E->F. Draw or slide.
Comment: _but see this question for why that came about_ - Oh! That's my question - I didn't realize you finally posted an answer. I must have missed the notice. I will check it out.
Comment: We do have E#/F on the modern chrom.
Answer: Opinions about this are divided, and I've heard very good players argue for either approach. There is no consensus, or agreed best practice.
I have attended a workshop with a known teacher who argued that you should always use the same hole for C (usually holes 5 and hole 9 - avoiding 4 and 8). The teacher argued that it's confusing to use two different holes, and you don't actually gain anything.
Sure, it's faster to go from a G up to C by using hole 4 or 8 because you only jump one hole instead of two (e.g. 3 to 4 instead of 3 to 5). But the same doesn't apply going from, say, D to A (e.g. 5 to 7). You have to be very good at that two hole jump anyway, there's no advantage to using a shortcut just for one specific note.
On the other hand, in his book "Play Irish Music on the C Chromatic Harmonica", Brendan Power suggests an approach whereby you would use the C on hole 4 when music is descending, and on hole 5 when music is ascending. Brendan Power argues this is better to be able to play at the speed required for some pieces in Irish Music.
I have had lessons with a different teacher, who argues you should work on a piece-by-piece approach, using what works best for that piece. In particular that teacher was keen on keeping things as "legatto" as possible. So going from an E to a C, you would do the C on hole 5, blow. But going from a B to a C, you would do the C on hole 4, draw, with the slide in !
I have actually done a small survey about this on a forum with a number of Chromatic Harmonica players. I got 12 respondants - all of whom have been playing Chromatic Harmonica for a number of years, and many of whom perform regularly. They all agreed, with no exception, that they work on a piece-by-piece basis, using whatever combination works best for a given piece.
You can see the thread in question there, though it is a french speaking website: https://www.harmonicalement.fr/viewtopic.php?t=10734


Question About Modal Chord Progressions

Question: What is a modal chord progression? I know that some scale degrees resolve to other scale degrees other than the root note or root chord. Do I always have to resolve my phrases on the notes of the tonic chord for each different mode? If not, then how do I identify each mode's different sound without always relying on the mode's root chord? How do I solo over different chords without soloing over the tonic while still maintaining each mode's different and unique sound?
Comment: Music terminology is not standardized and even if it was, there would be numerous different standards and the standards are not followed anyway. Can you link to or describe a context where this phrase is used in the meaning you're asking about?
Comment: I'm convinced that, if you're not soloing on the tonic or a chord progression that involves the tonic, you're not soloing in a mode. Solo over the dominant of a minor key all you like (e.g. the *Live at the Acropolis* version of Yanni's "Keys to Imagination"), that is *precisely* what you're soloing over instead of any mode of the (A, in this case) harmonic minor scale.
Answer:
Do I always have to resolve my phrases on the notes of the tonic chord
for each different mode?

No, if the listener's perception of home note is provided by some other means, such as backing instruments.

If not, then how do I identify each mode's different sound without
always relying on the mode's root chord?

If a listener perceives the music as having the home note, harmonic centerpoint note, tonic or whatever you want to call it, as being X, and the harmony around X as being rigidly structured as a set of intervals called Blahblah, then the music can be said to be in X Blahblah mode, for that listener.
HOW exactly the perception of harmonic center and intervals around it is created, is an art, a skill, and beyond the means of a single answer to teach. Pitches, rhythms, even timbres have a role in it, and the perception happens inside the listener, and it depends on each listener's subjective history, acquired tastes, even sense of rhythm. If the listener is unable to identify where the "one" is in your rhythmic pulse, they will have a different idea of which notes are harmonically strong.
Think about going to a dance in Africa and you just cannot make sense of the beat and so you can't dance to it and people laugh at you. You need good old German boom boom boom boom marching beat ie. techno which tells you when to stomp. The same goes with harmony. Maybe you aren't skilled enough in hearing where the "one" is, rhythmically or harmonically. You can try and learn through experience, but you won't be able to calculate it with rules and math.
Repeating the root note a lot all the time, like the boom boom boom boom bass drum and bass notes in marching and techno beats, can work as a rule of thumb, if nothing else helps.
Answer:
What is a modal chord progression? I know that some scale degrees
resolve to other scale degrees other than the root note or root chord.

"Resolving" implies a movement to the root chord, which - although being a concept that stems from tonal music - is fine in modal chord progressions. But resolving phrasings isn't the main interest in modal improvisation. One could argue that resolving implies a musical movement that restricts improvisation to a certain degree.
If you want to employ some/any kind of chord progression, you are instead recommended to move between the root chord and the chords consisting of the character note, i.e. the note that is considered unique for the current scale you're playing.
Chords that consists of neither root note or character note can be used as passing chords, and will not aid in emphasizing the current mode.
Chords with tritones are considered tonal (representing the dominant chord function that want's to resolve to the tonic) and are therefore not really aligned with the purpose of modal music.
There is also the use of non-tertian chords - chords that aren't built on thirds - to further move away from a tonal and/or function sound. These can still consist of the root note, or the character note.

Do I always have to resolve my phrases on the notes of the tonic chord
for each different mode? If not, then how do I identify each mode's
different sound without always relying on the mode's root chord? How
do I solo over different chords without soloing over the tonic while
still maintaining each mode's different and unique sound?

The idea is that you focus on improvising strong melodies over resolving them. Also, some ways to emphasize the current mode are:

Relating character note chords to the root chord (which you've already mentioned).
Relating the current mode to a new one by switching them at a preferred pace while playing. This lets the listener hear/feel the relative difference between modes.
Focus your melodies around the character note.
Comment: Hello, so do I always need to hit the character notes to emphasize a mode, or can I just create melodies that land on the root note of a given mode? What happens if I only hit the mode's root note and not hit any of the character notes?
Comment: @HenryPaul If you want to convey the specific sound of a mode, I'd say it's necessary to utilize the character note. Avoiding the character note will likely undermine conveying the characteristics of the mode.
Answer: If you're thinking in terms of 'resolving' - other than being aware of a 'home' chord - maybe it isn't useful to label it as a 'modal progression'.
What's your criterion for deciding whether a piece is in D minor or D Dorian?  Maybe something to do with the presence of a sharpened leading note, enabling the most basic functional resolution, V - I?   Without that, it's a mode rather than a key?
A topic for exploration rather than a definitive ruling, I think.

Question About Modal Chord Progressions


getting unique values from a list of dict

Question:
Possible Duplicate:
how to uniqify a list of dict in python

I have a list as follows
<code>[
{'x':'1','y':'1'},{'x':'2','y':'2'},{'x':'1','y':'1'}
]
</code>
I want to get a new list as follows (unique elements)
<code>[
{'x':'1','y':'1'},{'x':'2','y':'2'}
]
</code>
What's the best way?
Comment: Are the two identical dicts in the example different objects (i.e., two objects with distinct ids)?  If so, the problem is more complex, since methods of making a unique list such as casting to a set, etc. will not work.
Comment: Thanks  @DSM , your suggesion works fine
Answer: <code>import ast

l = [
{'x':'1','y':'1'},{'x':'2','y':'2'},{'x':'1','y':'1'}
]

[ast.literal_eval(el1) for el1 in set([str(el2) for el2 in l])]
</code>
Usually an easy solution for keeping unique elements is to add them to a set. However, since a dict is unhashable (can't be put in a set), I provided a workaround. First, the dicts are converted to strings, placed in a set (to keep the unique ones), and then converted back to dicts using ast.literal_eval.
Comment: Why not use a dict of repr(dict) -> dict?
Comment: Or, do what black_dragon did, cast to tuples then back..
Comment: Does `str(d)` always iterate over the key, value pairs in the same order?
Answer: <code>>>> lst = [{'x':'1','y':'1'},{'x':'2','y':'2'},{'x':'1','y':'1'}]
>>> map(dict, set(tuple(x.items()) for x in lst))
[{'y': '1', 'x': '1'}, {'y': '2', 'x': '2'}]
>>>
</code>
Comment: I'm actually not sure this works.  I don't know if it's guaranteed that two equal dicts have their `.items()` return in the same order.
Comment: This will not work in Python3.


Java platform: How to manage Configuration Settings for each Developer

Question: Inspired by this question:
How to manage Configuration Settings for each Developer
How can I manage application configuration settings that are must be set for each developer without checking them into source control on the Java platform?
For example, this is the kind of thing we are doing now:

Datasource configuration is stored in a Spring configuration xml file.
Currently, each developer edits the file and tries his best not to commit that file into source control. Several of us have patches (diff files) that are applied to the code before performing testing against our local database and remove the patch before checking code in. Other developers edit and revert the configuration files by hand.
Sadly, patches get out of date. People sometimes forget to revert their local configuration before commit.

My question, however, is not limited to database connection settings. I would like to find a solution where each developer can override application configuration settings without having to alter source controlled files.
If we must change the way in which we are storing configuration settings, then I think we should do it (perhaps JNDI?, external configuration files in a well known path?, I don't know)
What would you do/have you done?
Answer: Place the configuration file in an external directory. If it is not present, read a default config file. The external directory can be configurable, and can have a default value, say c:\workspace\config.
Optionally, during the build, you can copy the external properties into the build artifact.
Comment: I also thought of doing this. Maven uses a similar approach: it looks for a $MAVEN_HOME/settings.xml file. If there is none, it uses configuration defaults. The only problem is how to solve the cross-platform issue of paths in Windows and *nix. Perhaps the environment variable approach of using $MY_SYSTEM_HOME should be enough. thanks!
Answer: We make the build completely self contained, including things like local H2/Hipersonic/JavaDB databases and Ruby mail servers.  That means the local build has no developer specific config and everything just points to the pre-packaged components.  It also means that apart from basics (JVM, Ruby, Editors) there is zero time to configure a developer box.
The drawback is that your code checkout is somewhat bigger.
Comment: This sounds very nice. I'm afraid we are not at that level of automation with our build and configuration management yet, but is a great answer. thank you.
Answer: Check a template file (like sample.context.xml) into source control. Each developer copies that file to context.xml and does any modifications he likes. If the real configuration file lives in a source controlled dirctory, add it to svn:ignore to prevent accidental checkins.
==> No accidental commits, and persistent local configuration settings.
If the local configuration file is missing, the application doesn't start. This makes it obvious to new team members that settings can be configured. Obviously, the continuos integration server will need a local settings file, too.
As for where to put that configuration: It makes build and deployment easier if the instance-specific configuration is not part of the .war file. We use JNDI entries, which are easy to look up from spring configuration files using <j2ee:jndiLookup>.
Comment: It makes a lot of sense and this would be the easies (closer) solution  in my case, because am already using source controlled files. We only have to add them to the ignore list. thanks
Answer: Best place to have these configuration is a database. And add a few lines to your production code just to read these configurations. It means no harm as long the purpose is solved and everything is consistent and coherent. Put on a small framework which reads these configurations and overrides the default ones that appear in production.
Fortunately some of the frameworks like Rails do provide these and I am pretty sure its flexible in Java as well.
Comment: Yeah, I'm afraid that the database way is not what I like the most. It is the only approach I have tried and I found 2 downsides: 1) You tend to use table-like configuration structures that are not always the best kind of structure or xml-field blobs that are not easy to edit; 2) you have to solve the problem again for the database connection setting somehow outside the database.
Answer: One thing we have done here is have a property loader which first checks for system properties.
e.g. you have a property named datasource.url which gets loaded in to your Spring file.
We extended the ResourceLoader to first check the system properties to see if there was a property with that name, and if so it would load it up rather than using the value from the properties file. (Actually I think Spring's ResourceBundleMessageSource does this out of the box if you configure it, but we wanted some custom behaviour which I won't go into).
So, if we start our application with a few additional command line parameters:
-Ddatasource.url=[local-datasource-url]
Then it overrides the value from the properties file.
Obviously this is easier to do for a Swing application (which ours was) than a web app, but still a possibility.


How find this sum closed form $I=\sum_{k=1}^{n}\int_{0}^{+\infty}\cos{(2kx)}x^{m-1}e^{-ax}dx$

Question: Find this closed form?
$$I=\sum_{k=1}^{n}\int_{0}^{+\infty}\cos{(2kx)}x^{m-1}e^{-ax}dx,m\ge 1,a>0$$
use
$$\cos{(2kx)}e^{-ax}=e^{-ax}\cdot\dfrac{e^{2kix}+e^{-2kix}}{2}=\dfrac{1}{2}(e^{(2ki-a)x}+e^{-(a+2ki)x})$$
so
$$I=\dfrac{1}{2}\sum_{k=1}^{n}\int_{0}^{\infty}(e^{(2ki-a)x}+e^{-(a+2ki)x})x^{m-1}dx$$
note
$$\int_{0}^{\infty}e^{(2ki-a)x}x^{m-1}dx=\dfrac{\Gamma{(m)}}{(a-2ki)^m}$$
so
we must find this closed form
$$I=\dfrac{1}{2}\Gamma{(m)}\sum_{k=1}^{n}\left(\dfrac{1}{(a-2ki)^m}+\dfrac{1}{(a+2ki)^m}\right)$$
This problem is from:AMM problem:http://www.mat.uniroma2.it/~tauraso/AMM/amm.html
Answer: For $m=1$ $$\sum _{k=1}^n \left(\frac{1}{(a-2 i k)^1}+\frac{1}{(a+2 i k)^1}\right)=\frac{1}{2} i \left(\psi ^{(0)}\left(1+\frac{i a}{2}+n\right)-\psi ^{(0)}\left(1-\frac{i a}{2}+n\right)-\psi ^{(0)}\left(1+\frac{i a}{2}\right)+\psi ^{(0)}\left(1-\frac{i a}{2}\right)\right)$$
For $m=2$
$$\sum _{k=1}^n \left(\frac{1}{(a-2 i k)^2}+\frac{1}{(a+2 i k)^2}\right)$$
$$=\frac{1}{4} \left(\psi ^{(1)}\left(1+\frac{i a}{2}+n\right)+\psi ^{(1)}\left(1-\frac{i a}{2}+n\right)-\psi ^{(1)}\left(1+\frac{i a}{2}\right)-\psi ^{(1)}\left(1-\frac{i a}{2}\right)\right)$$
For $m=3$
$$\sum _{k=1}^n \left(\frac{1}{(a-2 i k)^3}+\frac{1}{(a+2 i k)^3}\right)$$
$$=-\frac{1}{16} i \left(\psi ^{(2)}\left(1+\frac{i a}{2}+n\right)-\psi ^{(2)}\left(1-\frac{i a}{2}+n\right)-\psi ^{(2)}\left(1+\frac{i a}{2}\right)+\psi ^{(2)}\left(1-\frac{i a}{2}\right)\right)$$
Do you figure out the pattern? You should get all these by differentiating with respect to $a$ in the case $m=1$ and carefully treating the signs.
Comment: @math110: This is due to the fact that $x^me^{ax}$ is noting else than the $m^{th}$ derivative of $e^{ax}$ with regard to *a*.


Release UIViewController give exception

Question: I have UIViewController that i add to the UIViewControler with this:
ReportViewController *reportVC = [[ReportViewController alloc]initWithNibName:@"ReportViewController" bundle:nil];
[self.view addSubview:reportVC.view];

And i try to add
[reportVC release];

after this lines and i get exepction when i try to remove this reportVC.view with
[self.view removeFromSuperview];

Did i make a error while release it like this?
Comment: How about posting the exception?
Comment: Use ARC in your project
Answer: In your code you are removing "self.view" from superview, which you shouldn't.
You have to remove "reportVC.view" from superview.
You can write like this:
[reportVC.view removeFromSuperView];

[reportVC release];

reportVC = nil;

Answer: If you will need your class instance later in your code then don't release it. You need to declare it in your .h file and call [reportVC release] in your - (void) dealloc method.
Answer:  [reportVC release]

It means u released the memory of viewcontroller object.Again u r trying to do operation with viewcontroller object which is already released.So remove that statement at there and write in dealloc method or use arc project where there is no need of releasing memory by u.It automatically release.
Answer: Self in that context would be the memory that you released when you called [reportVC release].  Then you are accessing a property "self.view" on an object that was released.

Release UIViewController give exception


Sorting on a custom date field is slower than sorting on relevance: Is there a solution?

Question: I'm using search api with database backend on a Drupal 9.3.3 site.
I've indexed 26,000 nodes of a custom content type and these include a custom date field: field_display_date
The index is set up to do rendered html. Since I need users to be able to sort on field_display_date (descending) as well as relevance, I've exposed two sorts: relevance and date (using this custom date field) and have added field_display_date to the index in "date" format.
The ultimate goal is to be able get highly relevant search results but be able to sort them to see the most recent highly relevant results. Maybe there's a completely different way to do this.
Problem: with the view all set up, key in a search term an execute. With the sort set to the default 'relevance,' returns are pretty quick. If I change the sort to 'date' (field_display_date: descending) and submit again, there is a very long wait time, often a gateway timeout.
On one that didn't time out, the view sql and performance redout said this...
Query
Index: main2
Keys: 'test'
Parsed keys: array (
    '#conjunction' => 'AND',
    0 => 'test',
  )
Searched fields: rendered_item, title
Sorting: field_display_date DESC
Options: array (
    'search_api_view' => 'object (Drupal\\views\\ViewExecutable)',
    'search_api_base_path' => 'search2',
  )
Title   Search2
Path    /search2
Query build time    1.43 ms
Query execute time  2.81 ms
View render time    43237.89 ms

Why is the render time so high and any ideas on how to correct this? Also, is switching to apache solr likely to work better or have the same result? (Since setting up solr looks pretty involved and is going to take me quite a while, would like to know if it's likely to be worth doing.)
By contrast, here's the same view and index and search keyword sorted by relevance...
Query
Index: main2
Keys: 'test'
Parsed keys: array (
    '#conjunction' => 'AND',
    0 => 'test',
  )
Searched fields: rendered_item, title
Sorting: search_api_relevance DESC
Options: array (
    'search_api_view' => 'object (Drupal\\views\\ViewExecutable)',
    'search_api_base_path' => 'search2',
  )
Title   Search2
Path    /search2
Query build time    1.23 ms
Query execute time  2.68 ms
View render time    2990.91 ms

This seems to suggest that the search itself and getting the result are both pretty quick but for some reason loading the page is really slow?
Interestingly, bypassing search api entirely and just plopping the body field into a regular view and searching on the keyword gets a faster result, which makes me think I'm doing something incorrectly at a fundamental level.
Plain views filter with no index, sorted by field_display_date descending, searching the body field for the same keyword...
Title   Content
Path    /admin/content/node2
Query build time    3.23 ms
Query execute time  1.2 ms
View render time    6291.28 ms

Comment: Is your date sort using the date data from your index? or just a regular date field? Make sure you're using the indexed date field data.
Comment: It's the indexed date field.
Some other details from analysis so far: the render time is often worse if I do the search with relevance sort in the exposed filter first, then change it to date and apply. So far, that set of steps appears to be worse than doing the search with date in the dropdown first, but I'm less certain of that.
Also: the number of total hits has a major impact. More = longer render.
May help to know: the view doesn't include any entity references to slow things.
Comment: Another clue: If I use 'rendered html' in the exposed filter instead of 'full text search,' results sorted by custom date field (indexed) are much quicker. The rendered html filter doesn't offer relevance sorting though. Maybe I need to default to 'relevance sort & full text' but have a button to route the query to 'date sort & rendered html.' Would like to understand why this is happening though.
Comment: Might be related to this issue: https://www.drupal.org/project/search_api/issues/3227268   Much of the discussion there is beyond my current level of expertise, so I'm unsure of the relevance.
Answer: This is a vague solution, because I wasn't able to determine why sort would behave this way.
I can report, though, that installing Solr and switching the index to the Solr backend resulted in there no longer being any noticeable difference with one sort vs. the other.
To clarify: same views and fields, and same index configuration. (In search api, you can switch an index's backend, then re-index). This resulted in very quick sorts using the same search result view pages.


Simple question about relative primes in entire rings.

Question: Let $A$ be an entire ring. Let $a,b\in A$. Does

The g.c.d. of $a,b$ is a multiplicative unit. $\Rightarrow$ $\langle a,b\rangle=A$

hold? If yes, how can I proof it?
Comment: You meant a [gcd domain](https://en.wikipedia.org/wiki/GCD_domain) ? In $k[x,y]$, $(1)$ is the smallest principal ideal containing $(x,y)$
Answer: False, e.g. $\,\gcd(x,y)=1\,$ in $\,\Bbb Q[x,y]\,$ but $\,(x,y)\neq (1)$ else eval $\,xf\! +\!yg=1\,$ at $\,x,y=0\,$ $\,\Rightarrow 0 = 1.\ $


How can i attach a value from Json Data to an Actionlink in mvc4

Question: The data got from Json  i used to append to a table as rows.First data of the column needs to come in Link format.So i used ActionLink .But i get the following error as "The name 'Transaction_No' does not exist in the current context".
function CreateGrid(result) {

    $.ajaxSetup({
        cache: false
    });

    for (i = 0; i < result.data.length; i++) {
        debugger;
        var chk_row = true;
        $('#tbl_RoleMenu tbody').empty().append('

');
         String Transaction_No = result.data[i].Loan.toString();

        $('#tr-' + i).append(' @Html.ActionLink(Transaction_No, "Create", "Portfolio", null, new { @class = "openDialog", data_dialog_id = "emailDialog" }) 	');
        $('#tr-' + i).append('' + result.data[i].Loan + '	');

    }

}

Comment: enclose `Transaction_No` inside the double quotes like "Transaction_No"
Comment: @dakait :If we put in double Quotes its just print the text not value.  I want to get this value(result.data[i].Loan.toString()) instead of displaying just transactionno,and need to attach action link to it.
Answer: You seem to be completely mixing server side code with client side javascript. Try fixing this mess:
function CreateGrid(result) {
    $.ajaxSetup({
        cache: false
    });

    for (i = 0; i < result.data.length; i++) {
        debugger;
        var chk_row = true;
        $('#tbl_RoleMenu tbody').empty().append('

');
        var transactionNumber = result.data[i].Loan;

        $('#tr-' + i).append('' + transactionNumber + '	');
        $('#tr-' + i).append('' + result.data[i].Loan + '	');
    }
}

As an alternative to this horrible mess I would recommend you create this markup on your server using a partial view. I guess that you are calling this function after performing an AJAX request to a controller action (that currently returns a JsonResult). Modify this controller action so that instead of returning a JsonResult returns a PartialView and then simply inject this new markup into your DOM.


How to find out the number of conjugacy classes of complements in a special group extension?

Question: Let $U$ be an abelian group. Let $V:=\underbrace{U\times ... \times U}_{n\ \text{factors}}$.
Let $H:=C_n$ act on $V$ by cyclic permutation. Let this action be denoted by $\phi$.
Let $F:=V \rtimes_\phi C_n$.
Hence, $1\rightarrow V\stackrel{i}{\rightarrow} F\stackrel{p}{\rightarrow} H\rightarrow 1$ is a group extension.
Question:

Is there an easy way to see how many $H$-conjugacy classes of complements $V$ in $F$ are there?

Does one only have to find all group homomorphisms from $H$ to $F$ such that the sequence splits without computing the first cohomology group or does one have to compute the first cohomology group?
Thank you very much for the help.
Comment: It's an induced module from the trivial subgroup, so $H^n(C_n,V) = 0$ for all $n \ge 1$ by Shapiro's Lemma. So there is only one class of complements.
Comment: Who is $V$? Who is $H$? How are they related to $F=U\wr C_n$? Are they related at all? You should not first  introduce $F$ as a generic extension, then define it explicitly.
Comment: Ok, thanks, you're right. I edited the question.
Comment: What are your thoughts on the problem? Where did you encounter it?
Comment: Hm...I'd try to compute $H^{1}(C_n,V)$...maybe(?)
Comment: Ah, that is an elegant way - thanks!
Answer: As I said in a comment, this follows from Shapiro's Lemma: if $H \le G$ are groups, and $U$ is an $H$-module (over ${\mathbb Z}$ as default), then $H^n(G,U^G) \cong H^n(H,N)$ for all $n \ge 1$. In your example, $H$ is trivial, so $H^n(G,U^G) = 0$ for all $n \ge 1$. This result extends naturally to the case when $U$ is an arbitrary non-abelian group.
It is not hard to give a direct proof of the result in your case, so here it is. There is no need to assume that $U$ is abelian.
Elements of $F = U \rtimes_\phi C_n$ have the form $vg^k$ with $v \in U^n$ and $0 \le k < n$ where, for $v = (u_1,u_2,\ldots,u_n)$, we have $gvg^{-1} = (u_2,u_3,\ldots,u_n,u_1)$.
Now a complement of $U^n$ in $F$ is generated by an element $vg$ with $(vg)^n = 1$. Since, $$(vg)^n = v (gvg^{-1}) (g^2vg^{-2}) \cdots (g^{n-1}vg^{-(n-1)}),$$
this is equivalent to $v=(u_1,\ldots,u_n)$ with $u_1u_2\cdots u_n=1$.
In that case, putting $c = (1,u_1,u_1u_2,\ldots,u_1u_2\cdots u_{n-1})$, we have $c^{-1}gc = c^{-1}(gcg^{-1})g = vg$, so the complements are conjugate.


Discrepancies between Mann-Whitney Test and Linear Mixed Model Results in R

Question: I've conducted a four-phase experiment with physiological measures on two groups (Controls vs. Patients). After applying a Mann-Whitney test to examine differences between groups for each dependent variable at each phase, I found some significant results.
However, when I attempted to build a linear mixed model (LMM) in R using the formula model <- lme(Dep_Variable ~ TIME * Group, random = ~ 1|ID , data= data), the LMM results are substantially different from the Mann-Whitney test. Specifically, significant differences observed with Mann-Whitney at certain time points are not replicated in the LMM, and vice versa.
Are there specific considerations in interpreting results obtained from a Linear Mixed Model (LMM) compared to non-parametric tests? What factors could contribute to differences between Mann-Whitney and LMM results?
Answer: Mann-Whitney tests "the null hypothesis that, for randomly selected values X and Y from two populations, the probability of X being greater than Y is equal to the probability of Y being greater than X". You probably use your LME model to test hypotheses about explained variance, or about parameters being zero. These are very different things, so the answers that different tests give to different questions will also differ.
Best to first formulate your research question, then choose an appropriate test.
Comment: You will need to be more specific than "any differences between the two groups". Two groups can have the same mean (which is what t-tests test), but if you draw a random sample from each group, it may still be more likely that the observation from group A is greater than that from group B (which is what Mann-Whitney tests). Or the other way around. If you just want to test whether the CDFs differ, then a two-sample Kolmogorov-Smirnov test may be appropriate. Yes, this is complicated, and there is a lot of imprecise and misleading information out there.
Comment: The thing is that, as a first step, I would like to see if there are any differences between the two groups for each phase of the experiment. Subsequently, I would look into those differences to see which group has higher values. That's the purpose of building a model with all the four phases, and where I found results to be contrasting
Answer: In addition to the differences between Mann-Whitney and mixed linear models, as noted by Stephan Kolassa, part of your problem might be:

After applying a Mann-Whitney test to examine differences between groups for each dependent variable at each phase, I found some significant results.

That sounds like you did multiple comparisons over multiple outcome variables at multiple experimental phases. That leads to a potential multiple-comparison problem: if you do enough comparisons, some will pass a given threshold of "significance" even if there aren't any true differences. If you didn't correct the Mann-Whitney tests for the multiple comparisons you might well have found nominally "significant" differences that aren't real.
Note that the Mann-Whitney test can be considered a special case of ordinal logistic regression, a method that allows you to avoid the multiple pairwise testing you thought that you needed to perform. See Chapter 13 of Frank Harrell's Regression Modeling Strategies.
Finally, if a parametric linear model is appropriate then these data might not require mixed modeling. It sounds as if a classic multivariate (multi-outcome) linear model might be OK, or other approaches like those described in Chapter 7 of Regression Modeling Strategies.
Comment: @Ed9012 what I meant to convey is that ordinal logistic regression, which allows for complex linear multiple regression models without assumptions about error distributions, can be used _instead of_ MW, which can only compare two groups at a time. See Chapter 13 of the Harrell reference and [this resource](https://www.fharrell.com/post/rpo/). If you have complete data, multivariate linear models might provide an alternative to mixed models. That said, there's nothing necessarily wrong with your mixed models; if the assumptions are met I'd trust those results.
Comment: after I correct for FDR or Bonferroni, none of the results are significant. However, the reason why I would use a linear mixed model is to look at the effect of time between the two groups over each dependent variable (so that i build many different models with the same predictors).
I don't understand your suggestion on how the MW test can be used to avoid  the multiple pairwise testing, could you please write more details?
Comment: I did not mention though that my dependent variables are continuos. I see how I can use multivariate linear models, building models like the following: `model<-lm(Dep_Variable~Group,data=TIME1)`. In this way I can still see if there are any differences between the group for each phase for multiple variables, though I need to split the original dataset several times. Does that sounds right?
Comment: I mean, that would still be a simple linear regression... I don't see how I can apply the techniques you mentioned. I did Mann-Whitney because the data are not normally distributed.
Comment: @Ed9012 you typically should _not_ do separate analyses for each time point/phase. That tends to have less power than a comprehensive model of all the data. The usual normality assumption in multiple linear regression is about the _error distribution_ estimated by _residuals_ between observations and model predictions, not the raw data. Even that assumption can sometimes be relaxed. See [this answer](https://stats.stackexchange.com/a/100222/28500). _Ordinal_ regression doesn't even need that assumption; it just works with the rank-order of observations as Mann-Whitney does.


Nice proof of a polynomial root $x \in [0, 1]$

Question:
Prove that if
  $$\sum_{k=0}^{n} \frac{a_k}{k+1} = 0$$
  then
  $$\sum_{k=0}^{n} a_k\cdot x^n = 0$$
  for some $x$ in $[0,1]$. (original image)

So:
$$\sum_{k=0}^{n} \frac{a_k}{k+1} = 0$$
We must prove:
$$\sum_{k=0}^{n} a_k\cdot x^n = 0$$
So $f(x) = a_0$. Now:
$$a_0 = -\sum_{k=1}^{n} \frac{a_k}{k+1}$$
Now, I just need to verify that $\sum_{k=1}^{n} \frac{a_k}{k+1} > 0$
Thanks!
Comment: **Hint:** The first sum equals $\int_0^1 p(x)\, dx$.
Comment: No integration allowed (this is the derivative section).
Answer: Hint: Define a polynomial $f(x)=\sum_{k=0}^n a_k\frac{x^{k+1}}{k+1}$ and then apply Rolle's theorem (Note that $f(0)=f(1)=0$ ).
Comment: How is $f(1) = 0$? I see: $f(1) = \sum a_k \frac{1}{k+1}$ how does that evaluate to $0$?
Comment: @Lebes see the given condition in the question
Answer: Hint:

$a_0 + \ldots + \dfrac{a_n}{n+1} = \displaystyle\int\limits_{0}^{1}(a_nx^n + \ldots + a_0) dx$
Intermediate value theorem


Initial Value Calculus Problem

Question: I have this math problem:$$\frac{dP}{dt}=0.01P(1-0.001P); P_0=50$$
This is a differential equation, but I have no idea how to solve it.
$$\frac{1}{0.01P(1-0.001P)}dP=dt$$
$$\frac{1}{0.01P-0.00001P^2}dP=dt$$
$$\int{\frac{1}{0.01P-0.00001P^2}dP}=\int{dt}$$
$$ln\left | 0.01P-0.00001P^2\right |=t?$$
Comment: I guess it is $P|_{t=0}=P_0$.
Comment: Look for the method of separation of variables. In the meantime you forgot about $P^2$
Comment: That's what I am supposed to use, but what does P_0=50 mean?
Comment: $P_0 = 50$ gives the initial value of $P$. (The value at time $t = 0$ )
Comment: You are on the right track but you've integrated wrong on the left-hand side.
Comment: @amcalde, did I? is it the ln?
Comment: $\int \frac{dx}{a x-b x^2} = \frac{\log (x)}{a}-\frac{\log (a-b x)}{a}$
Comment: Your last integral is not equal your final answer. $u = 0.01P - 0.00001P^2 \implies du = 0.01 - 0.00002P\,dP.$ Recall that $\int \dfrac {f'}{f} \,dP = \ln|f|$.
Comment: @KFC also note that $$\int dt = t+C$$
Answer: Go with partial fraction decomposition. $$\int \frac{1}{0.01P(1-0.001P)}dP =\int \frac{1}{0.01P}+\frac{1}{10(1-0.001P)}dP \\ = \int \left(\frac{1}{0.01}\right)\frac{1}{P}+\left(\frac{100}{100}\right)\frac{1}{10-0.01P}dP  \\ = \int\frac{100}{P}+\frac{100}{1000-P}dP \\ = 100\int \frac{1}{P}+\frac{1}{1000-P}dP $$ The rest should be pretty easy to integrate. You'll get an answer in terms of the natural logarithm.

Initial Value Calculus Problem


Como desativar "tela cheia" do html5 video em qualquer navegador?

Question: Como posso desativar tela cheia em qualquer navegador ?
Segue a imagem onde tem círculo vermelho:

Alguma solução ?
Answer: Os controles CSS são esses: Enjoy :)

video::-webkit-media-controls-fullscreen-button {
    display: none;
}
video::-webkit-media-controls-play-button {}
video::-webkit-media-controls-play-button {}
video::-webkit-media-controls-timeline {}
video::-webkit-media-controls-current-time-display{}
video::-webkit-media-controls-time-remaining-display {}
video::-webkit-media-controls-time-remaining-display {}
video::-webkit-media-controls-mute-button {}
video::-webkit-media-controls-toggle-closed-captions-button {}
video::-webkit-media-controls-volume-slider {}
<video width="400" height="260" controls="">
    <source src="http://cdn.papercut.com/video/home/home2.mp4" type="video/mp4" />
        <source src="http://clips.vorwaerts-gmbh.de/VfE.webm" type="video/webm" />
        <source src="http://clips.vorwaerts-gmbh.de/VfE.ogv" type="video/ogg" />
</video>
Answer: Para isso teria que usar javascript também junto com HTML5, exatamente como colocarei abaixo ira dar certo:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Teste Video</title>

    <button onclick="playPause()">Play/Pause</button>

    <video id="video1" width="420">
        <source src="p360-2.mp4" type="video/mp4">
    </video>

Comment: WPfan, agradeço a sua resposta. Eu não quero perder atributo de controles do html5 video. Eu apenas quero ocultar ou desativar a `tela cheia`.
Comment: Existem eventos onclick para fazer cada um dos atributos do vídeo, no seu lugar eu usaria dessa forma deixando de fora apenas a opção fullscreen.


How to open URL in an Activity (instead of a new browser)?

Question:
Can anyone please help me check my code to see why it cannot be
  launched in the app itself but directs me to a browser? ): Thanks!!

MAIN ACTIVITY.JAVA
package com.intelligami.androidwebviewapp;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ShareActionProvider;

public class MainActivity extends Activity {

private WebView mWebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mWebView = (WebView) findViewById(R.id.activity_main_webview);
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mWebView.loadUrl("http://intelligami.com/submitqn");
    mWebView.setWebViewClient(new com.intelligami.androidwebviewapp.MyAppWebViewClient(){
        @Override
        public void onPageFinished(WebView view, String url) {
            //hide loading image
            findViewById(R.id.progressBar1).setVisibility(View.GONE);
            //show webview
            findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
        }});

}
private class MyWebViewClient extends MyAppWebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
@Override
public void onBackPressed() {
    if(mWebView.canGoBack()) {
        mWebView.goBack();
    } else {
        super.onBackPressed();
    }
}

private ShareActionProvider mShareActionProvider;
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    /** Inflating the current activity's menu with res/menu/items.xml */
    getMenuInflater().inflate(R.menu.menu_main, menu);

    /** Getting the actionprovider associated with the menu item whose id is share */
    mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();

    /** Setting a share intent */
    mShareActionProvider.setShareIntent(getDefaultShareIntent());

    return super.onCreateOptionsMenu(menu);

}

/** Returns a share intent */
private Intent getDefaultShareIntent(){
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_SUBJECT, "Convert Website to Android Application");
    intent.putExtra(Intent.EXTRA_TEXT," Vist www.AndroidWebViewApp.com if you Want to Convert your Website or Blog to Android Application");
    return intent;
}

}

MY APP VIEW CLIENT. JAVA
package com.intelligami.androidwebviewapp;

import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MyAppWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if(Uri.parse(url).getHost().endsWith("intelligami.com/submitqn")) {
        return false;
    }

    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    view.getContext().startActivity(intent);
    return true;
}
}

Where is the error? :D
It keeps opening up in the browser.
Answer: In the following line:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

you're asking Android to open a URL using the intent constant ACTION_VIEW - so it defaults to the external browser.
Here a full example (taken from here) that shows how to open the url using a WebViewClient:
package com.paresh.webviewclientdemo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/*
 * Demo of creating an application to open any URL inside the application and clicking on any link from that URl
should not open Native browser but  that URL should open in the same screen.
 */
public class WebViewClientDemoActivity extends Activity {
    /** Called when the activity is first created. */

    WebView web;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        web = (WebView) findViewById(R.id.webview01);
        web.setWebViewClient(new myWebClient());
        web.getSettings().setJavaScriptEnabled(true);
        web.loadUrl("http://www.google.com");
    }

    public class myWebClient extends WebViewClient
    {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub

            view.loadUrl(url);
            return true;

        }
    }

    // To handle "Back" key press event for WebView to go back to previous screen.
   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event)
  {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
        web.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
   }
}

Comment: I"m really new to this. So in order to make my code working, what should i change the intent to??
Comment: @JavierNg see the method `shouldOverrideUrlLoading()` in the example I posted, note that it doesn't use any intent!
Comment: public class MyAppWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(Uri.parse(url).getHost().endsWith("intelligami.com/submitqn")) {
            return true;
        }

So just like that?
Comment: @JavierNg no, did you look in the example I posted ?
Comment: I did and I copied paste the entire thing but it didn't work


Erro com ActionListener

Question:   import java.awt.Color;
    import java.awt.Container;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;

    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;

    public class SwingFileDialog  extends JFrame {
        private JButton bDialog; //botão p/ acionar o diálogo
        private JLabel bDialogo;  //botão p/ resultados
        private JFileChooser dialogo;  //diálogo de arquivos

        public SwingFileDialog() {
            super("SwingFileDialog"); //ajusta titulo
            Container cp = getContentPane(); //painel de conteudo
            cp.setLayout(new GridLayout(2, 1)); //layout grade 4 x1
            JLabel lResultado;
            cp.add(lResultado = new JLabel("Sem seleção"));
            lResultado.setBorder(
                    BorderFactory.createMatteBorder(2, 2, 3, 2, Color.GREEN));
            bDialogo.addActionListener(new ActionListener() { //AQUI ESTA DANDO ERROR

                public void actionPerformed(ActionEvent e) {
                   dialogo = new JFileChooser();
                   int res = dialogo.showOpenDialog(SwingFileDialog.this);
                   if(res==JFileChooser.APPROVE_OPTION) {
                       File  arq = dialogo.getSelectedFile();
                       lResultado.setText(arq.getName());
                           }    }
                } );
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            pack();
            }
        public static void main(String[] args) {
            new SwingFileDialog().setVisible(true);

        }
}

Erro:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method addActionListener(new ActionListener(){}) is undefined for the type JLabel

at SwingFileDialog.<init>(SwingFileDialog.java:29)
at SwingFileDialog.main(SwingFileDialog.java:43)

Comment: Forneça mais informações sobre o erro.
Comment: Eu não sei porque esta dando erro nesse código
Answer: Sua variável bDialogo não é um botão, é um label ("rótulo"). Labels só servem para mostrar informação, não existe nenhuma ação associada a eles (como a ação de clicar). Você está chamando o método addActionListener de um JLabel - que não possui esse método - daí o erro de compilação.
O fato de você estar tendo um erro de execução - e não de compilação - provavelmente é devido ao IDE (Eclipse?) responsável por compilar essa classe: nessa resposta no SOen, por exemplo, indica-se que o Eclipse compila o código e introduz essa exceção apesar do erro de compilação (me parece algo bem idiota de se fazer, mas eles devem ter seus motivos...). Se você estiver usando o Eclipse, tente "limpar" ou fazer "refresh" no código antes de compilá-lo (não uso esse IDE há muito tempo, não me lembro como ele funciona).
E para corrigir o erro, naturalmente, é só trocar o tipo de bDialogo de JLabel para JButton.
Comment: Vlw, deu certo aqui...

Erro com ActionListener


How to standardize a data-set

Question: I have a data-set consisting of N p-dimensional observations (all quantitative variables). I want to apply a hierarchical clustering algorithm to those data. As explained on page 505 in Elements of Statistical Learning, when using weighted average to combine the distances of the individual variables, it is often desirable (I have found no clues to the contrary in my scenario), to set the weights for each variable such that all variables have equal influence on the distance of the observations (formulas can be found in the book). The problem is, that I use scipy.spatial.distance for calculating the distances, and this does no let me specify any weights. My question is, if I standardize my observations (multiply each dimension with 1/average of that dimension), does that solve the problem?
Comment: Ideally, the question should be self-contained. Could you please give the relevant formulas as well? By the way, I may not have understood your question properly but won't euclidean distance give the same weight to all the variables? That metric seems to be one of the distance measures offered by the library you are using.
Comment: instead of "(multiply each dimension with 1/average of that dimension)" don't you mean to multiply by the reciprocal of the *standard deviation* of the corresponding coordinates?  This is not a bad choice but it's sensitive to outliers.  Rescaling by a resistant measure of spread, such as the IRQ, would protect you from outliers and still accomplish what you intend.
Comment: @Srikant Vadali: I wanted to post the formulas, but I couldn't find a way to embed them here, and ASCII-formulas would have made things worse instead of better. Also, the book I referenced is freely available as an ebook, so everyone can look it up.
Comment: Check out http://meta.stats.stackexchange.com/q/386/930 for LaTeX typesetting
Answer: I'd just say: be careful with that. Standarization is needed only when some variable(s) dominates the dissimilarity score just because it is expressed in "smaller units"; let's say that you have a variable that is truly equal for all elements, but there is some, very small variability due to the measurement error. Now if you'd normalize this value, you'll make those errors an important factor for clustering.
Comment: Thanks for your answer. I just found a useful paper on that issue: http://dx.doi.org/10.1007/BF01897163. It compares the usefulness of different normalization approaches with each other and with no normalization.

How to standardize a data-set


Connect multiple AD's to one site

Question: Is it possible to connect 2 AD's to drupal intranet to have single sign on (with the LDAP module)?
thank you in advance
Answer: Yes you can. After installing the ldap module:

Set up the two servers via: admin/config/people/ldap/servers
Set up authentication via: admin/config/people/ldap/authentication. Make
sure to "Check all LDAP server configurations to use in authentication."
Do your other settings as per your requirements.

Connect multiple AD's to one site


SBS 2008 - Add user not seeing AD users (reconnecting or creating new mailbox)

Question: Using SBS 2008 - completely updated.
I was originally trying to create a spam mailbox for quarantine purposes, and when I bring up the "select an existing user" it does not display any of the domain users (other than QB database user accounts installed on their server).  I have tried changing the scope and still nothing.  Searching reveals nothing either.
Then later I noticed that we had (1) disconnected mailbox, and I tried to reconnect it to the AD user - and I got the same results.
Help would be much appreciated.
Answer: The "Select an existing user" option will only show user accounts that have no mailboxes associated with them.
So for a spam mailbox like you describe you would need to have already created a user account in Active Directory (eg one named "spammailbox"), or during the New Mailbox wizard create a new account at that time.