Question about IV chord in minor key

Question: Key of A minor:
Am - Em/G - F - D - Dm - Am/C - B - E

How would you describe the D chord?
I'm not sure. Is it from a melodic minor?
Is there any specific reason why this progression works well?

Thank you!
Comment: So many questions on this site searching for the reasons why certain things work! For the progression here, I'd have thought that the B chord was far more of an outsider than the D - even considering the F# may have come from the A melodic minor, where's that D# come from..?
Comment: It's often V/VII, but that doesn't seem to apply here.
Answer: The simplest answer is that chords are borrowed from the parallel key quite often. This is in key A minor, and all the other chords are diatonic to it and its various scale notes. So, yes, it could easily be seen to come from A melodic minor. That will explain the E major chord as well. But it's just as easily seen to come from the parallel key - of A major - it being IV in that key.
None of this explains the B chord, also non-diatonic. But since it's V/V - the dominant chord of the dominant chord - it leads nicely to the E major, dominant of A (maj or min), then probably returns to Am.
Answer: D in the key of A minor is a fairly common sound, and there are a couple ways to view it.
For starters, let's get this out of the way first: D major is not in the key of A minor, as you've noticed. D major is, however, diatonic to A dorian. As you've noticed, it's also diatonic to A melodic minor. In the specific case you've outlined, it sounds like it's definitely a borrowed chord. If I had to pick one, I'd say it's borrowed from A Dorian, because generally I don't like to say "borrowed from melodic minor" unless most of the progression is also melodic minor, but it wouldn't be wrong to say that. A more general term for this kind of chord is modal mixture.
Now, just because that one chord is from dorian/melodic minor doesn't mean the rest of the progression has to be the same. Obviously, the tonic here is some sort of A minor, and the rest of the chords make sense in A minor as well.
If you're curious, the reason I say that the B makes sense is because it's a secondary dominant. E is the dominant of A minor, and the dominant of E is B, so B major, though non-diatonic, functions in the key of A minor with predominant function.
Comment: 'The rest of the chords make sense in A minor as well' - excepting that B..?
Comment: @Tim How 'bout now? :)
Comment: Why borrowed from A Dorian instead of simply A Major/Ionian?
Comment: That's just the way I've always heard it described: Borrowed from Dorian. Makes sense, since the A minor flavor is preserved, but obviously it's not wrong to say "borrowed from major" or from melodic minor.
Comment: I'm not sure that *sub dominant* is the same as *dominant of the dominant*.
Comment: @Tim What word would you use for a chord that leads to the dominant (like IV)? "Predominant"? *(I might have messed up the terminology...)*
Comment: Yes, *predominant* is the one.
Comment: Curses. Fixed...
Comment: "D major is not in the key of A minor, as you've noticed. D major is, however, diatonic to A dorian. As you've noticed, it's also diatonic to A melodic minor." This isn't how minor works. You may as well claim that E minor isn't in the key of A minor because it doesn't have the raised seventh. Fact is that, like the flat seventh, the raised sixth is a perfectly ordinary part of the key of the minor key, which the melodic minor scale (it's a scale, not a key) exemplifies -- we use it when we want to step smoothly to the raised seventh.
Comment: @PeterSmith You're missing my point, though: "diatonic" in this case means accessible without modifying the base set of notes in the key. A minor, *by definition*, includes an F natural, thus D major cannot truly be "in the key" of A minor. It sees plenty of common use, obviously, but it's still not diatonic.
Comment: You and I both understand that music described as "in A minor" in reality uses notes that are outside of the white keys of a piano, of course. But minor is part of the same modal family as major, and if you argue that D major is diatonic to the key of A minor, then you should also be arguing that D major is diatonic in the key of C major. @PeterSmith
Comment: If you want to make that claim about E7 in A minor, fine - harmonic minor has a valid claim to being "diatonic minor" nowadays. But the major IV chord simply isn't described as "in the key" for minor. You have to draw the line somewhere, or else literally every chord is diatonic to every key because there exists music somewhere that uses that chord in that prevailing tonality. @PeterSmith
Comment: Minor is not a mode of major. As I pointed out earlier, the raised seventh -- the thing that makes minor distinct from aeolian -- necessitates the raised sixth.
Comment: @PeterSmith *"Minor is not a mode of major [...] raised seventh necessitates the raised sixth"* I know why melodic minor was invented and how it works, but "diatonic to minor" refers to your basic, run-of-the-mill natural minor, a.k.a. Aeolian, a.k.a. minor. When I said *"D major is not in* [diatonic to] *the key of A minor"*, I was correct. D minor is **the** D triad in A minor, not D major. Just because a chord is often used in a key doesn't mean it has to be a part of that key.
Comment: @PeterSmith Take an F major triad as further proof of my point. If you argue that D major is the diatonic D triad in A minor, then the bVII chord so commonly used in minor has the note F natural, but the D major chord has F#. Thus, D can't be diatonic to A minor - they can't both have different versions of the same note. And you can't argue that A minor contains the notes of all types of minor diatonically. In practice, yes. But not for the purposes of "is this chord diatonic in this key".
Comment: Look up definitions of the term "diatonic". I have yet to find one supporting your claim that D major is diatonic to A minor; melodic and harmonic minor, by definition, are *chromatic alterations* of the existing minor scale, exactly the opposite of diatonic.
Comment: Minor is not a mode of major. Minor isn't even "a" scale, it's a key often characterized by three different scales. You keep basing your arguments off absurdities created by treating minor as a mode of major, all while claiming to understand that it's not a mode of major. You accept that both the minor and major dominant fall within the key, but for some reason the raised sixth that logically follows from this is too far for you. "Diatonic" is a word with no clear meaning and is a total red herring here.
Comment: Diatonic has a clear, exact, and precise meaning. You accept that Aeolian exists, which is a mode of major. How is Aeolian not minor?  It's easy to derive the Aeolian scale from the Ionian one. That's how minor started in music - the other two types of minor were literally *invented* by *chromatically altering* the minor scale. Major has some basis in nature, with the harmonic series. Minor is then relative to that major scale. Chromatic alterations of that minor scale are *by definition* not diatonic. If you can't play it on the white keys of the piano with transposition, it's not diatonic.
Comment: You could say "diatonic *to melodic minor*", which is clear. But though "minor" varies widely in music as to which notes are *used* in it, every common alteration is derived from the Aeolian mode, a.k.a. natural minor.
Comment: Another common test/definition for diatonic: diatonic music has no accidentals in its sheet music. Key signatures are based off of natural minor, so diatonic music has an easy and precise definition. **Usage does not define what minor is, the same way that secondary dominant chords don't re-define what the major key is.** "Diatonic" is a precise term with no room for argument because minor is a strictly-defined set of notes. It just happens to have very common modifications. @PeterSmith
Comment: Aeolian is not minor because it lacks the dominant seventh we associate with cadences in minor-key music. Like, aeolian is very definitely a distinct tonality from minor. Major has no basis in the harmonic series (many notes appear in the harmonic series long before the entire major scale shows up), but even if it did that would be literally entirely irrelevant.
Comment: "Usage does not define what minor is", the concept of minor literally exists to explain harmonic features common to a large subset of music. "Minor" is a concept derived entirely from usage.
Comment: There's a huge difference between the raised sixth and seventh of minor -- things which literally define minor as distinct from aeolian -- and things like neapolitan chords and secondary dominants, which fit within a tonality without being necessary to define that tonality
Comment: "Major has no basis in the harmonic series" is possibly a false claim, as I read and think on it; but the arbitrary operations required to get major out of the harmonic series definitely make "major has some basis in nature" entirely false -- but, regardless, as I said earlier *none of this matters*
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/115348/discussion-between-user45266-and-peter-smith).
Answer: A lot can depend on the rhythm and voice leading, but if we skip that for the moment, you could abstract your progression to...
Am... Dm and B... E
First it goes to the subdominant and then it goes to the dominant. Tonally that is very clear harmony. If you are somehow emphasizing D and E as targets, it should make the tonality even more emphatically clear.
Am Em/G Dm/F E and Am G7 F7 E7 are common progressions. From that perspective you might be able to abstract the progression to...
Am - Em/G - F... E
It's a mix of the two progressions at the point of F, whether the chord is root position or inverted, but the descending bass at the opening seems clear. Instead of simply going to E you elaborate with another descent D C B before getting to the dominant E.
Answer: Free swapping between IV (major) and iv (minor) is very common whether the basic tonality is major or minor.   Anyway, D major IS diatonic to A minor if you consider the melodic form of A minor scale.
But let's look at 'degree of outside-ness' more generally.
In tonal music that extends beyond the '4-chord trick', major and minor triads just fit.  Any of them.  They're not as strongly active as chords that contain a tritone or other dissonance.  They match the 3-note density of surrounding triads. They're 'in the ballpark'.
Triads that contain two diatonic notes - that are one-note modifications of a diatonic triad - fit even better.
And you can get away with 'outside' chords much more easily when the voice leading includes common notes, and when it includes scalic lines.  Play the chords Am, E7, G, D, Dm  and make the bass line A, G♯,G♮, F♯, F♮.   See what I mean?
Answer: Apologies for a messy answer, but even though the question is short, the answer needs a lot of stuff. :) I suspect you're not only interested in the D chord, but what happens in the progression.
Why the chord progression works: it utilizes different harmonic movements, tension and release, old and new, familiar and unfamiliar. Keep something, change something. Do something expected, do something unexpected. You need to know a few different elements and dimensions of harmony to see why something might feel like expected and why something might feel unexpected. These dimensions are how you keep track of what changes or stays the same, and how you create expectations, tension and release.
One very basic thing is the scale. It's more expected that the scale stays the same than that it changes. Another basic thing to look for is the I / IV / V axis. The harmony is either at rest (or "at home") at I i.s. tonic, or leaning on the IV i.e. subdominant side, or the V i.e. dominant side. In the key of C major / A minor these are: tonic:C/Am, subdominant:F/Dm, dominant:G/E (or Em). The movement from G (or G7) to C, or from E (or E7) to Am is a dominant-tonic motion. When you're at a dominant chord, e.g. E7, the least unusual thing to happen next is to get the tonic Am.
Then you have the overall sense of where tonic is i.e. where "home" is. Not being home is, in a way, tension. How far away are you from home? If home moves, basically everything changes, you have to find a new orientation for everything.
(Side-note: The only root note that's left from the set of six chords Am, C, Dm, F, E, G is B. What's that? Dm6/B can be thought of being e.g. a mixture of a Am's subdominant Dm and "secondary dominant" B, which is E's dominant.)
You could say that the D major chord in the chord progression "borrows" from the parallel major key (A major), or that it brings feeling from the Dorian mode for a brief moment. Moving between minor/major can be thought of being a bit unexpected. You're settled at e.g. A minor and expecting the scale etc. but then you get an F# note which you're used to hearing in other keys, so have to do a bit of re-thinking. Something is changed, something stays the same.
To make the change last longer than just the D chord, it could go like this: Am - Em/G - F - D - A/C# - B - E. Can you hear the difference?
Another thing you have there is voice leading, stepping a voice or two up or down. The bass goes down: A - G - F - D - C - B - E. The final step can be seen as a V-I jump, although not from Am's V but E's V. Stepping a voice up or down by one step is perhaps in the conventional or expected side of things. But the conventionality feels safe and lets you do unexpected changes in other dimensions, to balance the expected and unexpected.
(You could say something about the movement of other voices move as well, but the lowest note is an easy pick because there's only one lowest note. For the other voices it could be argued if the motion was up or down, and the chord symbols don't really dictate exactly how the notes should be spread in different octaves)
If we map the chords to the tonic/subdominant/dominant role world, it goes like this:

Am : tonic
Em/G : dominant (but not the strongest one E7)
F : subdominant
D : subdominant (but different)
Dm : subdominant (but different)
Am/C : tonic
B : "secondary" dominant (giving a brief feeling of E being the tonic)
E : dominant

In the above I consider Am and C both being "tonic", which is in a way unorthodox. ;) But in most cases you can replace any chord with the relative minor/major while keeping most aspects of its function.
The final E leaves a strong expectation for an Am, which nicely wraps the chord progression and makes you want more of the same.
Changing between tonic and subdominant sides isn't necessarily very unexpected, but it is a change, which gives the progression some character.
So... that's why it works. Try it yourself, take something as a starting point, and then step by step change something in one of the dimensions.
One last thing to add: chords or chord symbols are not a physical or biological thing in your head, and there's no single correct dimension for reasoning about what happens in harmony. Chords are ready-made product packages, macro building blocks developed for practical use in Western music culture. Harmony construction kit for dummies. Even if you can select between a kitchen block, bedroom block and a toilet block, it doesn't mean that you can't combine the functions of those blocks in countless variations. :)

Question about IV chord in minor key


What should I set my Content-Security-Policy to?

Question: I'm using Drupal 8, and I currently use
Header always set Content-Security-Policy "default-src 'self'; nosniff"

However, this causes bugs, such as Google Analytics not working and the textbox mysteriously disappearing from the Edit page. What should I do?
Comment: https://www.youtube.com/watch?v=L97wtYCqfwM . this guy explains clearly about CSP.
Answer: The policy needs to contain every domain where assets are loaded from, which will vary depending on which services your site uses such as a CDN or third party JavaScript widgets.
For Google Analytics, it must be able to connect to www.google-analytics.com, and stats.g.doubleclick.net if Display Features tracking is enabled.
The Google Analytics module also requires the unsafe-inline policy value, since it injects the analytics snippet directly on the page.
Googalytics is an alternative built specifically for Drupal 8 that works without unsafe-inline.
Core also currently requires 'unsafe-inline' for scripts in element attributes due to its use of CKEditor 4 (see https://www.drupal.org/project/drupal/issues/2789139)

In order to test a Content Security Policy without impacting the functionality of your site, first use the Content-Security-Policy-Report-Only header instead.  This will make the browser report violations of the policy in the browser console and to the report-uri address, without blocking the content on the page.  Once you have a policy that works without violations, change the header to Content-Security-Policy.
You can also provide both headers at the same time, allowing you to test changes without the risk of breaking functionality.
Report-uri.io provides a free logging service that you can use to collect violations of both your enforced and report-only rules, and audit for any changes you may need to make.
They also have a wizard utility to help setup your policy for the first time.

Setting up a policy in Drupal 8 is also easier with the Content Security Policy module.  It integrates with Drupal 8's libraries system to automatically add script and style sources, provides an admin UI that validates your settings, provides a local handler for report violations, and will apply some optimizations to shorten the policy if possible.


Invalid argument supplied for foreach() Line 140

Question: Error ON 140 , invalid argument supplied for foreach() , i dont know what i have to do

MyController code :

if ($data['ms']['mspr_no'] != '') {
    $mdpr = $this->input->post('mdpr');
    foreach ($mdpr as $key => $value1) {
        foreach ($mdpr[$key] as $idx => $value2) {
            if ($mdpr['mdpr_mspd_no'][$idx] != '') {
                $data['md'][$idx]['mdpr_no'] = $data['ms']['mspr_no'];

                if ($key == 'mdpr_net') {
                    $data['md'][$idx][$key] = ftodouble($value2);
                } else {
                    $data['md'][$idx][$key] = $value2;
                }
            }
        }
    }
}

My Form Promo view :

    <?php
    if ($action == 'view') {
        if (isset($promo)) {
            foreach ($promo as $value) { ?>

                    <input type="text" name="mdpr[mdpr_mspd_no][]" class="form-control srstyle-ta-center mdpr_mspd_no" value="<?php echo $value['mdpr_mspd_no']; ?>" readonly />
                    <input type="text" class="form-control msph_pl" value="<?php echo $value['msph_pl']; ?>" readonly/>
                    <input type="text" class="form-control msph_hjkk_net" value="<?php echo $value['msph_hjkk_net']; ?>" readonly/>
                    <input type="text" class="form-control msph_hjkj_net" value="<?php echo $value['msph_hjkj_net']; ?>" readonly/>
                    <input type="text" name="mdpr[mdpr_net][]" class="form-control mdpr_net srstyle-ta-right auto-numeric" value="<?php echo $value['mdpr_net']; ?>" readonly/>

<?php
            }
        }

    }
    ?>

Thanks
Comment: you can check by printing the `$mdpr` if its an array
Comment: Please edit your question to add in the code as text not image
Answer:
"Warning: Invalid argument supplied for
  foreach() "

Its because of either null or false or argument is not array
foreach($mdpr as $key => $value1){
             ^
            see var_dump($mdpr),
            $mdpr is either null or false or not array you get above error

So what you can do is
$mdpr = $this->input->post('mdpr');
if(is_array($mdpr))
{
    foreach($mdpr as $key => $value1)
    {
            // your remaining code goes here
    }
}else
{
         echo 'Bad data posted';
}

We can regenerate this error like this for example
$ php -r 'foreach(null as $e){}'
PHP Warning:  Invalid argument supplied for foreach() in Command line code on line 1

/*false OR FALSE*/
$ php -r 'foreach(false as $e){}'
PHP Warning:  Invalid argument supplied for foreach() in Command line code on line 1

/* Not array */
$ php -r 'foreach("somestring" as $e){}'
PHP Warning:  Invalid argument supplied for foreach() in Command line code on line 1

I see OP made an edit - Line No : 140
Comment: im vardump($mdpr) with firebug , and response is just NULL ,
Comment: @MuhammadAldiansyah `foreach` does not work with null, false or string so
Comment: is my view form is wrong so foreeach does not work ?
Comment: @MuhammadAldiansyah: please debug with firebug, see what is being posted when you submit, what I can say is since your variable mdpr is not array, you are getting above warnings
Comment: Severity: Warning
Message:  Invalid argument supplied for foreach()
Filename: controllers/promo.php
Line Number: 140
Comment: no dude, should i ?, im really really newbie sorry dude
Comment: @MuhammadAldiansyah without above statement how php will know whether variable is of type array or something else ?
Answer: Use a if(is_array()) to validate that is a array to be looping.


Matrix Idempotency Questions

Question:
Firstly I apologise for the use of an image but I am still unfamiliar with using the math text on here.
So I am currently studying linear algebra at second year level and have been working on this question.
I have proved a) by squaring the matrix and obtaining that it is equal to the original matrix.
I have also shown b) by saying that
$$(I-B)^2= I^2 - 2IB + B^2$$
Which then equates to $I - B$ due to the fact that $I^2=I$ and $B^2=B$ for Idempotency.
I have also shown that for c) the determinants may only equal 0 or 1 by saying:
$det(C^2)= det(C)$
$det(c)* (det(c) - 1)=0$
However I'm now stuck on how to approach questions d) and e).
Any help would be greatly appreciated.
Comment: hint for (d): What's the relation between the matrix of $S\circ S'$ and the matrices of $S$ and $S'$?.
Comment: hint for (e): Is $E$ idempotent? Recall the hint for (d).
Comment: Do you know that if $T:\Bbb R^n\to\Bbb R^n$ has matrix $A$ and $T':\Bbb R^n\to\Bbb R^n$ has matrix $B$, then $T\circ T'$ has matrix $A\cdot B$?
Comment: Would you be able to expand your comment a bit more. I'm sorry but I'm not really grasping what you're saying.
Comment: Yes e) is idempotent as when squared it returns the original matrix but I'm not sure what the relation is between the linear maps. Is it because they both represent idempotent matrices?
Comment: I didn't know that no. So am I looking to multiply the matrix D by In - D?
Comment: Try to show this property first.
Comment: So I have looked throughout my notes and found the principle that you are talking about (theorem 4.12) but it simply just states that this is fact and does not have proof behind it in the notes. So I assume I have to state this theorem first to use this condition.
Answer: I'll expand my comments as required.
For (d): If $D$ is the matrix of $S$ and $I_n-D$ of $S'$, then the matrix of $S\circ S'$ is $$D(I_n-D)=D-D^2=D-D=0$$
so $S\circ S'$ is the null aplication.
For (e): As the matrix of $T$, $E$, is idempotent, then $E^2=E$. Also the matrix of $T^{9001}$ is $$E^{9001}=E^2 \cdot E^{8999}=E\cdot E^{8999}=E^{9000}=\ldots=E$$
so $T^{9001}=T$.
Comment: Thank you for expanding. Between the response time I learned about the further steps for d) and e) but did not know that S o S' was called a null application, so that's great to know!  However I'm still unsure  what it means to actually deduce/find the linear map. For instance what notation or words should I be writing?
Comment: Well, the name "null" i think it is not standard.... but it means the application that maps every vector to zero.
Comment: Okay yeah I get you. So when I'm answering that question do I just state "the linear map composition takes every vector and transforms it into the zero vector" and is the associated matrix just the 0 matrix by any size nxn?

Matrix Idempotency Questions


Tristate checkbox in Office ribbon

Question: Is there a way to have a tri-state checkbox on MS office 2016 ribbons?
Comment: No, the Ribbon UI doesn't provide that...
Answer: Nope. The Fluent UI has a limited number of controls with a pre-defined functionality. You can find all the ribbon UI controls described in the following articles:

Customizing the 2007 Office Fluent Ribbon for Developers (Part 1 of 3)
Customizing the 2007 Office Fluent Ribbon for Developers (Part 2 of 3)
Customizing the 2007 Office Fluent Ribbon for Developers (Part 3 of 3)

The checkBox control provides the getPressed callback which returns boolean:
C#: bool GetPressed(IRibbonControl control)
VBA: Sub GetPressed(control As IRibbonControl, ByRef returnValue)
C++: HRESULT GetPressed([in] IRibbonControl *pControl, [out, retval] VARIANT_BOOL *pvarfPressed)
Visual Basic: Function GetPressed(control As IRibbonControl) As Boolean

There is no third state.

Tristate checkbox in Office ribbon


Random effect and above cahnce performance in R

Question: I am new to the world of GLMM, and I have a simple design. Each subject sees the same questions (4-choice). I want to treat the questions as random factor and test if subjects succeed above chance (0.25) in these questions. subjects are marked as Ss, Questions as Qs and accuracy (0/1) as ACC. In the past I used lme4. How can I test is ACC is above 0.25.
many thanks
Answer: This is what I did:
m1=lmer(data=d,Acc~1+(1|Stim)+(1|Ss))
conf1=confint(m1)
and verified that 0.25 is not in the confidance interval.
any other suggestions?


Como fazer para modificar uma variavel dentro de uma definiçao sem globalizar a variavel?

Question: Preciso modificar uma variável dentro de uma definição sem globalizar a variável porque assim eu posso uzar a mesma definição com variáveis diferentes.
Eu já tentei o código seguinte:
>>> n = 0
>>> def f(mmm):
        mmm = 1
        return mmm

>>> f(n)
>>> 1
>>> print(n)
>>> 0

Mesmo depois de executar a definição, a variável n continua com o valor de antes, oque eu posso fazer?
Comment: Eu acho que é melhor você atribuir o retorno da função f a variável n. Ou seja n = f(n)
Answer: De fato, sem usar variável global, não é possível fazer o que você quer.
Até porque, se eu fizer isso:
def f(mmm):
    mmm = 1
    return mmm

f(10)

Repare que chamei a função passando um valor diretamente, em vez de usar uma variável (f(10)) - se fosse possível modificar a variável de fora, o que seria alterado nesse caso? O 10? Não faz sentido.
Claro que algumas linguagens permitem que o valor da variável seja alterado dentro da função, mas o Python não foi feito assim.
A documentação cita algumas formas de contornar isso. No seu caso, a mais simples parece ser simplesmente pegar o retorno da função e atribuí-lo na própria variável:
n = f(n)

Para complementar o assunto, sugiro que leia aqui, aqui e aqui.
Comment: @FelipeMercês Se a resposta resolveu o seu problema, vc pode aceitá-la, [**veja aqui**](https://pt.meta.stackoverflow.com/q/1078/112052) como e porque fazê-lo. Não é obrigatório, mas é uma boa prática do site, para indicar a futuros visitantes que aquilo resolveu o problema
Comment: muito obrigado!


Prove that the two functions are equal.

Question: Let $f: \mathbb{Z}_5 \rightarrow \mathbb{Z}_{10}$ and $g: \mathbb{Z}_5 \rightarrow \mathbb{Z}_{10}$ be defined by $f([x]_5)=[x]_{10}$ and $g([x]_5)=([x]_{10})^5$ Prove that $f=g$
I know that the domain and codomain are the same but I'm unsure how to go about showing that for every input both functions have the same output.
Comment: You can just calculate it. f.e. $f([3]_5) = [3]_{10}$ and $g([3]_5) = [3]*[3]*[3]*[3]*[3] = [7]*[3]*[3] = [1]*[3] = [3] $ (in subscript $10$).
Comment: What are the definition of the functions? Given $[x]_5$, does one take a representative $x$ there and then modulo 10 to get $[x]_{10}$? Is this a well-defined? If that is the case, you need to show that $x^5-x = x(x^4-1)=x(x-1)(x+1)(x^2+1)$ is divisible by 10 for every $x \in \mathbb{Z}.$ Or, as another suggestion goes, once you know is well defined, just calculate the five values of both functions and compare.
Answer: You could make a table... and show that $f = g$ for all $x$ in the domain.
But, let's do some algebra.
We want to show that:
$(x^5 - x) \equiv 0 \pmod {10}$
$(x^5 - x) =(x)(x+1)(x-1)(x^2+1)$
Clearly for $x \equiv 0,1,-1\pmod5, (x^5 - x)\equiv 0$
So we still need to check, $2,3$
$(4^2+1)\equiv 0\pmod 5\\
(9^2+1)\equiv 0\pmod 5$
And since one of $(x)(x-1)(x+1)$ must be even.  $(x^5-x) \equiv 0 \pmod 5 \ \implies (x^5-x)\equiv 0 \pmod {10}$
Using similar logic we can extend this....One of $(x)(x-1)(x+1)$ is divisible by $3$
$(x^5-x)\equiv 0 \pmod {10}\implies(x^5-x)\equiv 0 \pmod {30}$

Prove that the two functions are equal.


Static variable out of scope, Error: cannot find symbol

Question: the Error is:

cannot find symbol System.out.println("value of count" + count);

Symbol:

variable count

Location:

class synchronize

I declared count variable static so doesn't that mean every class can access it?
class a extends Thread

{

public static int count=0;

public void run()

 {

   for(int i=1;i<=100;i++){

   count++;
    }
  }
}

class b extends Thread {

public void run(){

  for(int i=1;i<=100;i++){

  count++;
  }
 }
}

class synchronize {

public static void main(String args[]) {

  a obj =new a();

  b obj1=new b();

  obj.start();

  obj1.start();

  System.out.println("value of count "+count) ;

 }
}

Comment: Try `a.count` instead of `count`
Comment: Use `a.count`, not `a.count()`. With the parentheses, it looks for a static method called `count` in your `a` class, which does not exist.
Comment: Please make count globally static.
Comment: `static` means that a variable does not belong to any particular instance of a given class, but to the class iteself.  It's usually referenced through its class name. Like `ClassName.variable`.
Comment: Am using a.count() now it's showing cannot find symbol count. Location class. :b. Please help
Comment: @user187744 I have addressed your new problem in my answer.
Answer: the count variable is declared as a member of the a class.
So if you change:
System.out.println("value of count "+count);

To:
System.out.println("value of count " + a.count);

So that you are accessing the count variable as a member of the a class, then your synchornize class should be able to 'see' the count variable.
Also, you may want to use the a.count inside of class b as well:
class b extends Thread {

    public void run(){

      for(int i=1;i<=100;i++){

          a.count++;
       }
    }
}

Comment: Actually, it's a `static` member of class `a`, so it's better to refer to it statically: `a.count`. (I'd also suggest that OP rename the classes to start with upper case letters, so as to conform to Java conventions.)
Answer: Static variables have a single value for all instances of a class.
You have to access static variables by class name
instead of this
System.out.println("value of count "+count) ;

use this
System.out.println("value of count "+a.count) ;

Answer: Since it is public and static, you are correct in that you will be able to access the count variable in your a class from anywhere in your code.
However, you cannot access it just by using the variable count.
Your other classes do not know about any count variable, but they know about your a class. So you can use a.count to access the count variable in your a class from any of your other classes.
Comment: Thank you very much all of you


Formal way of defining a weighted average

Question: I am looking for a nice and formal way to define moving averages :
$y = \sum_{i=0}^N w_ix_i=<\mathbf{w},\mathbf{x}>$
and  especially the fact that weights have to equal one, i.e.
 $\sum_{i=0}^N w_i=1$.
This property seems quite obvious to me,  as you somehow want the output to have the same "level" as the input values. However, I don't know how to describe it a more mathematical way ..
Can somebody help me out ? Thank you
Comment: Yes, I think that pretty much what I was looking for. :)
Comment: ... and the weights $w_i$ are a vector in the [unit simplex](http://en.wikipedia.org/wiki/Simplex).
Answer: If $y=\sum_{i=1}^{n}w_ix_i$ is a weighted average of the $x_i$ with $\sum_{i=1}^{n}w_i=1$ and each of the $w_i\geq0$, then $y$ is a convex combination of the $x_i$.


init root viewcontroller causes crash

Question: I used codes below to init a root view controller
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

[window addSubview:rootViewController.view];
UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController: rootViewController  ];
}

it worked well on ios 4 about 2 years,ios5 1 years, there is no any problem when start to run the app
but on ios6 it crashed and reported
* Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'adding a root view controller  as a child of view controller:'
Welcome any comment
Comment: Is your rootViewController already a child of an other viewController ? or is it rootViewController on a window ?
Answer: 'rootViewController' is already in your view hierarchy. Remove it from whatever other container its in (window.rootViewController ?) first (window.rootViewController = nil).
Comment: Apple says the preferred initializer should be preferred. However one can imagine that it just sets the root controller, so it will probably be ok to use the 'initWithFrame' method then set the property. But then ask yourself why do that? When you stray from the lines you increase the likelihood of future problems. My app got bit twice by iOS6 due to minor straying. YMMV.
Comment: Somewhat related question: is calling UINavigationController-init legal, or do I have to call -initWithRootViewController:?  If the latter, is it legal to pass nil?
Answer: In your code you are adding rootViewController's view to window then immediately trying to add rootViewController's view to the new UINavigationController. Instead try this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    ...

    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:rootViewController];
    [window addSubview:nav.view];

    ...
}

or even better:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    ...

    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:rootViewController];
    window.rootViewController = nav;

    ...
}

The ... are there to show that these are incomplete examples of -application:didFinishLaunchingWithOptions:. You need to make sure you have included creating your UIWindow and calling -makeKeyAndVisible on it.

init root viewcontroller causes crash


Is the normalizer of a Sylow $p$-subgroup is a $p$-group?

Question: Given a group $G$ and a Sylow $p$-subgroup $P$ of $G$, is the normalizer $N(P)$ of $P$ a $p$-group?
I think that it may not be a $p$-group, so if there is an element $g \in G$ such that $g \in N(P)$ and $g \notin P$, the order of $g$ is not a power of $p$ since $g \notin P$ and $P$ is the maximal p-subgroup of $G$.
Answer: Not true in general. If $G$ is not a $p$-group with a normal Sylow $p$-subgroup, then $N_G(P)=G$. Example $G=S_3$, $P=A_3$.
Comment: I am just giving an example where it is NOT the case. The normalizer does not have to be a $p$-group. As simple as that, $N_{S_3}(A_3)=S_3$.
Comment: I'm not sure I follow your answer. There's no mention of the subgroup being normal.
Answer: $N(P)$ is a $p$-group if and only if $N(P)=P$, because $P$ is a maximal $p$-subgroup. Any subgroup properly containing $P$ cannot be a $p$-group.
Answer: If $N(P)$ were a $p$-group, since $N(P) \supseteq P$, which is by definition a maximal $p$-group, this would imply that $P=N(P)$.
So the answer is no, it happens if and only if $P$ is self-normalizing (see the other question you asked about that!)


Lagrange Multipliers with two constraints

Question: The problem is to find the maximum value of $ \ f(x,y,z) \ = \ x+y+z \ $ subject to the two constraints $ \ g(x,y,z) \ = \ x^2+y^2+z^2 \ = \ 9 \ $ and $ \ h(x,y,z) \ = \ \frac{1}{4}x^2+\frac{1}{4}y^2+4z^2 \ = \ 9 \ $.
I got these equations:
$$1 \ = \ 2x \ λ \ + \ \frac{1}{2}  x \ μ \ \ , \ \ 1 \ = \ 2y \ λ + \frac{1}{2}y \ μ \ \ , \ \
1 \ = \ 2z \ λ + 8z \ μ \ \ . $$
And from here, I'm not sure what I can solve for or simplify.
Comment: You need to fix the typos, for starters. Several $x$ and $z$ have been confused. Here's the hint: Once you get your equations right, you should realize that you'll need to have $x=y$ in order to solve. You don't need anything more with $\lambda$ and $\mu$.
Answer: Applying the indicated "Lagrange equations", we can subtract the second from the first to produce
$$ ( \ 2 \lambda \ + \ \frac{1}{2} \ \mu \ ) \ ( \ x \ - \ y \ ) \ = \ 0  \ \ . $$
This makes it a bit more evident that one's intuition about the symmetry of the functions is helpful.  As Ted Shifrin already notes, one result from this is that $ \ x \ = \ y \ $ .  Inserting this into the constraint equations, we obtain
$$ 2 \ x^2 \ + \ z^2 \ = \ 9 \ \ , \ \ \frac{1}{2} \ x^2 \ + \ 4 \ z^2 \ = \ 9 \ \ \Rightarrow \ \ \frac{3}{2} \ x^2 \ = \ 3 \ z^2 $$
$$ x^2 \ = \ 2 \ z^2 \ \ \Rightarrow \ \ x \ = \ y \ = \ \pm \sqrt{2} \ z $$
$$ 5 \ z^2 \ = \ 9 \ \ \Rightarrow \ \ z \ = \ \pm \frac{3 \sqrt{5}}{5} \ \ , \ \ x \ = \ y \ = \ \pm \frac{3 \sqrt{10}}{5} \ \ . $$
Hence, the maximum value of the function $ \ f(x, \ y, \ z) \ = \ x + y + z \ $ is found in the first octant as $ \ \frac{3 \sqrt{5}}{5} \ + \ \frac{3 \sqrt{5}}{5} \ + \ \frac{3 \sqrt{10}}{5} \ = \ \frac{3 \sqrt{5}}{5} \ ( \ 2 \sqrt{2} \ + \ 1 \ ) \ $ .  Because the constraint surfaces are symmetric about the origin, and the function to be extremized is anti-symmetric about the origin, we would expect that the minimum value for the function is $ \ -\frac{3 \sqrt{5}}{5} \ ( \ 2 \sqrt{2} \ + \ 1 \ ) \ $ , found in the opposing octant at the point on the constraint surfaces intersected by a line through the origin from the point we just found.
The other "result" from the first equation is $ \ \lambda \ = \ -4 \ \mu \ $ .  Inserting this into the third Lagrange equation gives us $ \ 2 \ z \ \lambda \ = \ 8 \ ( \ -4 \ \lambda \ ) z \ = \ 1 $ $ \ \Rightarrow \ \lambda \ = \ -\frac{1}{30 \ z} \ \ , \ \ \mu \ = \ \frac{2}{15 \ z} \ $ .  This, however, doesn't appear to take us any further.
$$ \ \ $$

the constraint sphere and constraint oblate spheroid, with one intersection circle marked in yellow (the other is located symmetrically "below the equator"); the minimum of the function to be extremized lies on the far side of the surfaces depicted, on the "lower" circle [the "beveling" near the equator of the oblate spheroid is an artifact of the grapher]
If we look at the geometric situation, the two constraint surfaces are a sphere and a (highly) oblate spheroid, which intersect at two circles in planes parallel to the $ \ xy-$ plane and disposed symmetrically about it (producing the rather saturnian -- or perhaps flying-saucerish -- configuration in the diagram above).  We can locate those planes by solving for the intersections of the spheroids:
$$ z^2 \ = \ 9 \ - \ x^2 \ - \ y^2 \ = \ \frac{1}{4} \ (9 \ - \ \frac{1}{4} \ x^2 \ - \ \frac{1}{4} \ y^2) \ $$
$$ 144 \ - \ 16 \ x^2 \ - \ 16 \ y^2 \ = \ 36 \ - \ x^2 \ - \ y^2 \ \ \Rightarrow \ \ 15 \ (x^2 \ + \ y^2) \ = \ 108  $$
$$ \ \ \Rightarrow \ \ x^2 \ + \ y^2 \ = \ \frac{108}{15} \ = \ \frac{36}{5} \ \ \Rightarrow \ \ z^2 \ = \ 9 \ - \ \frac{36}{5} \ = \ \frac{9}{5} \ \ . $$
This yields the values we found above.  We can "reduce" the function to that of a single variable, $ \ f(x) \ = \ x \ \pm \ \left( \ \frac{36}{5} \ - \ x^2 \ \right)^{1/2} \ \pm \frac{3 \sqrt{5}}{5} \ $ to locate extrema thus:
$$ 1 \ \pm \ \frac{1}{2} \ \left( \ \frac{36}{5} \ - \ x^2 \ \right)^{-1/2}  \cdot \ ( -2x ) \ = \ 0 \ \ \Rightarrow \ \ \mp \frac{x}{\sqrt{\frac{36}{5} \ - \ x^2}} \ = \ 1 $$
$$ \frac{36}{5} \ - \ x^2 \ = \ x^2 \ \ \Rightarrow \ \ x^2 \ = \ \frac{18}{5} \ \ , $$
from which follow the results described above.


Normalized subvectors of Dirichlet, mutually independent?

Question: Let$$X=(X_1,\cdots,X_k)\sim Dir(\alpha_1,\cdots,\alpha_k)$$
According to
this reference, the independence of the two vectors,
$$\bigg(\frac{X_1}{X_1+\cdots+X_j},\cdots,\frac{X_j}{X_1+\cdots+X_j}\bigg)$$and$$\bigg(\frac{X_{j+1}}{X_{j+1}+\cdots+X_k},\cdots,\frac{X_k}{X_{j+1}+\cdots+X_k}\bigg),$$
follows from the neutrality and aggregation property of the Dirichlet distribution.
I'm wondering to what extent can this result be generalized?
More specifically, for three-subvector cases, let $\{\pi_1,\pi_2,\pi_3\}$ be a partition over $\{1,\cdots,k\}$. e.g., $k=3, \pi_1=\{1\},\pi_2=\{2\}$, and $\pi_3=\{3\}$. Can we say the following normalized subvectors are mutually independent$$\bigg(\frac{X_k}{\sum_{j\in\pi_1}X_j}\bigg)_{k\in\pi_1},\bigg(\frac{X_k}{\sum_{j\in\pi_2}X_j}\bigg)_{k\in\pi_2},\bigg(\frac{X_k}{\sum_{j\in\pi_3}X_j}\bigg)_{k\in\pi_3}$$
Answer: The property stems from the fact that a Dirichlet random variable $$X=(X_1,\cdots,X_k)\sim Dir_k(\alpha_1,\cdots,\alpha_k)$$
is distributed as$$X=(Y_1,\cdots,Y_k)/\sum_{i=1}^k Y_i$$ when
$$Y_1,\cdots,Y_k\sim \prod_{i=1}^k \mathcal{Ga}(\alpha_i).$$
The result follows from the independence of the $Y_i$'s since
$$\bigg(\frac{X_k}{\sum_{j\in\pi_1}X_j}\bigg)_{k\in\pi_1},\bigg(\frac{X_k}{\sum_{j\in\pi_2}X_j}\bigg)_{k\in\pi_2},\bigg(\frac{X_k}{\sum_{j\in\pi_3}X_j}\bigg)_{k\in\pi_3}$$is distributed as$$\bigg(\frac{Y_k}{\sum_{j\in\pi_1}Y_j}\bigg)_{k\in\pi_1},\bigg(\frac{Y_k}{\sum_{j\in\pi_2}Y_j}\bigg)_{k\in\pi_2},\bigg(\frac{Y_k}{\sum_{j\in\pi_3}Y_j}\bigg)_{k\in\pi_3}$$
Comment: Thanks for the answer. I got your point. So, basically, the mutual independence holds for any partition, right? But what about the singleton cases? when $\pi_i=\{i\}$, can we say $X_i$ is independent of $X_j$ for all $i\neq j$? I don't get how this is possible because $X_i$'s should sum up to 1...
Comment: Oh, right :) Thanks!


OSX not serving PHP

Question: Okay so I have a confession first off … I've been messing … and I've broken the way that my local machine is behaving.
With that out of the way, here is some basics.

I'm running OS X 10.6.7
I Removed the default Apache install and replaced it with the lastest version from Apache.
I can now serve HTML from /usr/local/apache2/htdocs/ through 'localhost' which is okay.
I can't serve any PHP (it just shows up as plain text).

I'm sure that to get a solution I'm going to have to post some config files here but I'm not sure what you'd need; what'll be?
Here is my httpd.conf
Comment: Have you installed PHP or just Apache?  If just Apache, you now need to install PHP.
Comment: Not the exact answer to your particular setup but you may want to try MAMP if you just "want to get something up and running" http://www.mamp.info/en/index.html
Comment: Hi. This question belongs on another of the sites in the Stack Exchange eco-system due to its contents. Please check the [FAQ](http://stackoverflow.com/faq) for more information about what are appropriate question on Stack Overflow, and also take a look at the similar FAQ on the site I am migrating your question to. Thanks.
Comment: PHP is installed with OS X isn't it? I've not done an additional install.
Answer: Did you enable PHP within the Apache configuration file?
Default location:
/private/etc/apache2/httpd.conf

Remove the # before the following line:
LoadModule php5_module        libexec/apache2/libphp5.so

Finally restart Apache.
Comment: There is no LoadModule lines in my httpd.conf - see [my httpd.conf](http://shaunbellis.co.uk/stackoverflow/httpd.conf)
Answer: Normally on OS X to enable PHP you have to edit /etc/apache2/httpd.conf and make sure the line that starts with this is uncommented (i.e. doesn't start with "#"):
LoadModule php5_module

This may help you.  Or not.  Not enough info to say.
Comment: There is no LoadModule lines in my httpd.conf - see [my httpd.conf](http://shaunbellis.co.uk/stackoverflow/httpd.conf)
Answer: If PHP has been installed, have you configured Apache correctly to hand .php file to the PHP CGI executable or Apache module?  To do that, you'll need an AddHandler or AddType directive somewhere in your Apache configuration.
See steps 7 and 8 on this page (http://www.php.net/manual/en/install.unix.apache2.php) for the specific directives you'll need.

OSX not serving PHP


Is it possible to type hint a Clojure array filled with a deftype object?

Question: I'm optimizing a small performance focused section of an application. I'm attempting to create a Java array of a type created via deftype
(deftype MyThing [foo bar baz])

However, I can't seem to find any documentation on how to type hint these arrays, and without a type hint, reflection occurs.
(def my-array (make-array MyThing 10))
(aget my-array 0)

Gives the warning:
Reflection warning, call to static method aget on clojure.lang.RT can't be resolved (argument types: core.MyThing, int).

Is there a way to correctly hint the type?
Answer: I'm surprised to not find any question on this topic on Stack Overflow, and still more surprised to see that the official documentation for adding type hints does not cover this - I was sure I'd be able to close this as a duplicate, or link to official documentation, but here I am typing it out by hand like a barbarian.
The "primitive" version of type hinting, for which other forms are mere shorthand1, is
^"Foo" xs

where Foo is the JVM's internal name for the class you want to hint. There are shorthands for primitive arrays (^ints xs), and for ordinary class types (^MyType x), but this doesn't cover arrays of non-primitive types. For that, you have to know the official class name for your type. You could look up the rules for this, but the simplest thing to do is to just ask the interpreter!
user=> (defrecord Foo [])
user.Foo
user=> (def foos (make-array Foo 10))
#'user/foos
user=> (class foos)
[Luser.Foo;
user=> (aget foos 0)
Reflection warning, null:1:1 - call to static method aget on clojure.lang.RT can't be resolved (argument types: unknown, int).
nil
user=> (aget ^"[Luser.Foo;" foos 0)
nil

1 Actually, even more primitive is ^{:tag "Foo"}, but this distinction doesn't matter for this question.


Paypal MPL sdk with credit card support

Question: I am using MPL for adaptive parallel payment. It allows user to make payment using PAYPAL ID. I need to make payment via credit card as well.
Is anyone aware how can I use credit card with MPL or any alternate way for adaptive parallel payment using PAYPAL ID and CREDIT CARD both.
Any help will be appreciable.
Answer: You have credit option with single payment mode only..Refer
https://github.com/paypal/PayPal-iOS-SDK (Single Mode of Payment)
In terms of parallel payment using MPL. The Paypal API itself did not gave any option for Credit card payment..!
I have worked with Both SDK's MPL and PayPal-IOS-SDK. I tried to find solution for getting Credit card payment with MPL but could not make it.
Comment: Yes. But I need to make adaptive parallel payment with credit card support as well. Though I am unable to do so using MPL but It is my requirement to allow user to make payment using Credit Card too.
Comment: I have posted issue/enhancement at github..repository.

https://github.com/paypal/sdk-packages/issues/49

Paypal MPL sdk with credit card support


Sum of this converging telescoping series?

Question: I'm trying to understand which is the sum of the following telescoping series (I showed this is converging, I'm not reporting here):
$$\sum\limits_{j=n}^{\infty} [\mathbb{P}(E_j) - \mathbb{P}(E_{j+1})]$$
My take is that every term except the first and last one are canceling themselves so the sum should be, if I'm correct, given by $\mathbb{P}(E_n) - \lim\limits_{j\to\infty}\mathbb{P}(E_j)$
Is this OK?
Comment: Look at the partial sums, then take the limit. I believe you will get an "yes" to your question.
Answer: Yes $$\sum_{j=n}^m(\mathbb P(E_j)-\mathbb P(E_{j+1}))$$
$$=\mathbb P(E_n)-\mathbb P(E_{m+1})$$
Applying $\lim_{m\to\infty}$ on both sides, we get,
 $$\sum_{j=n}^\infty(\mathbb P(E_j)-\mathbb P(E_{j+1}))$$
$$=\mathbb P(E_n)-\lim_{m\to\infty}\mathbb P(E_m)$$
Hope it is helpful
Comment: Yes thanks! Very helpful!


When do I need to update the Report Model

Question: There is a constant change (!) in our database, new columns are often added.
Is reporting services the tool to choose for reporting in this case?
Case1: Developers add a new column to a table used in a report. Will the old reports created with a report model based on the old table still work?
Case2: Developers add a new column, and end users want to be able to report on it. If we update the report model, will the old reports based on the old report model still work? Or do we have to create a new report model every time the end user wants to report on a newly created column?
Regards
Lars
Answer: Reporting services has required strategies for change management. So, adding new column to a table in the underlying data source does not affect the reports.
If you want to include a newly added table column into your report model you should update (not create from scratch) your report model. Updating the report model automatically insert your new column to the model and does not break your old reports. on the other hand, updating report model does not update/delete the existing item if you change them (like table/column name or column data type etc) in the underlying source. You should manually change them at the report model and at the affected reports.
So, in your case, you won't be having any problem with reporting services.
Here i'm adding a change management section of the Reporting Services/Report Model document and strongly suggest you to read it.
Change Management

Models and the reports based on them
have many internal and external
dependencies. Therefore, you need to
consider the impact of changes
introduced into the dependency chain.
Report models based on relational data
sources use GUID attributes to
identify each entity, attribute, and
role. As mentioned, the report
model-generation process sets the
GUIDs, which are re-created at each
generation. For that reason and to
preserve edits on the report model,
generating a new report model each
time a change occurs is not an option.
You must work with the existing model
and update it, either manually or by
using the update options described
below.
The Semantic Query Engine
manages missing attributes when they
are not critical to report processing.
This functionality is in place to keep
reports running when security
attributes preclude users from seeing
some attributes in the report that may
be allowed to other users. Thus, if a
user is not allowed to access a field
such as the employee home telephone
number, the Employee Listing report
will run for that user but will not
show the excluded information. This
functionality works to your advantage
when models are edited to delete a
non-critical attribute. The report
will still run after you have removed
an attribute, although the report
might show a blank field. However,
query or report processing can be
broken by other changes to the model.
Remember that you should not overwrite
a model generated from a relational
data source when any reports depend on
it.

Schema Changes

If the underlying schema changes and
report model entities or attributes
are affected, you might have to update
the report model accordingly. To do so
in BIDS, use the Autogenerate command
on the Reporting Model menu. You can
also select Autogenerate from the
model item's context menu. By using
the context menu, you can select which
item on the model you want to update
without having to update the entire
model.
The autogeneration process will
show informational, warning, and alert
messages. These messages will show all
items in the model that are
out-of-sync with the underlying DSV,
even though those items are not
specifically included in the item
selected for autogeneration. This
functionality helps detect potential
errors than may lead to unpredictable
errors when running reports based on
the model.
Automatic update affects
newly added items only. The
autogeneration process will add any
new entity, attribute, or role found
in the DSV, but will not delete or
change any entity, attribute, or role.
Therefore, you need to manually manage
updated or deleted items. The messages
shown at the end of the generation
process will highlight any entity,
attribute, or role that needs to be
updated in the resulting out-of-sync
model. You will have to update the
model manually or revert the DSV
changes to maintain model-to-schema
coherence.

Data Source Changes

You can develop and test your model in
a development environment and then
deploy the model in a production
environment easily by changing the
connection string in the data source
file that the DSV uses. The two data
source schemas must be identical.
Note that the DSV contains statistics
based on the actual database data. As
mentioned in the section "Statistics
in Report Model Generation," the value
of those statistics will drive some
algorithm decisions during the model
generation. Therefore, if the
development database data is
significantly different from the
production database data, the model
might not be optimized for the data
that will eventually be used.

Hope this help.


Android http POST response

Question: My knowledge is very limited in android I am newBi, can anyone tell me how can I get the response and post of JSON that I am getting....If you have suggestion just edit my code and insert a comment , so that I can identify my missing methods.
I can't analyse some posted related question , I already do my research but I can't perfect it. Correct me if my code is wrong or incomplete.
 public void httpConnection(HashMap<String, String> postDataParams) {

    HttpURLConnection httpcon;
    String url = "(url here...)";
    String result;
    try {

        httpcon = (HttpURLConnection) ((new URL(url).openConnection()));
        httpcon.setDoOutput(true);
        httpcon.setRequestProperty("Key", "Value");
        httpcon.setRequestProperty("action", "get_scoop");
        httpcon.setRequestMethod("POST");

        httpcon.connect();

        OutputStream os = httpcon.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(postDataParams));
        writer.close();
        os.close();

        BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(), "UTF-8"));

        String line = "";
        StringBuilder sb = new StringBuilder();

        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        br.close();
        result = sb.toString();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }

    return result.toString();
}

public class CallAPI extends AsyncTask<String, String, String> {

    public CallAPI() {
        //set context variables if required
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {

        String urlString = params[0]; // URL to call

        String resultToDisplay = "";

        InputStream in = null;
        try {

            URL url = new URL(urlString);

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(10000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);

            in = new BufferedInputStream(urlConnection.getInputStream());

        } catch (Exception e) {

            Log.e("TAG", e.getMessage());

            return e.getMessage();

        }

        try {
                resultToDisplay = IOUtils.toString(in, "UTF-8");
            //to [convert][1] byte stream to a string
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultToDisplay;
    }

    @Override
    protected void onPostExecute(String result) {
        //Update the UI
    }
}

Comment: firstly looking at your code i would suggest you to use `retrofit` or `httpOk` apis
Comment: @MyMasterPeice can you give me example for that?
Answer: Simple example for fetching data via retrofit :
Note : this api runs in background thread hence do not call this method from any other background thread like asynctask
private void fetchDoctorClinics() {
        if (EasyPadhaiUtils.checkInternetConnection(DoctorDashbaord.this)) {

            // State Callback
            retrofit2.Callback callback = new retrofit2.Callback<ClinicsModel>() {
                @Override
                public void onResponse(Call<ClinicsModel> call, Response<ClinicsModel> response) {

                }

                @Override
                public void onFailure(Call<ClinicsModel> call, Throwable t) {

                }
            };

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(Constants.DOMAIN_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            // prepare call in Retrofit 2.0
            ClinicsInterface clinicsInterface = retrofit.create(ClinicsInterface.class);
            Call<ClinicsModel> call = clinicsInterface.getClinics("10");
            call.enqueue(callback);
        } else {
            // Network not available , handle this
        }
    }

and below is how you create post request via interface :
public interface ClinicsInterface {
    @FormUrlEncoded
    @POST(Constants.CONTROLLER_API)
    Call<ClinicsModel> getClinics(@Field(Constants.APPOINTMENT_DOCTOR_ID) String doctorId);
}

Do update your gradle with below retrofit  lib :
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'

Comment: first you need to create interface where you mention if get or post and pass params as above mentioned `getClinics(@Field(Constants.APPOINTMENT_DOCTOR_ID) String doctorId);` which will return you model of json 'ClinicsModel'
Comment: secondly you will import retorifit libs as mentioned above and will call api as mentioned above where you get reponse either in failure or success
Comment: read this for more info : https://guides.codepath.com/android/Consuming-APIs-with-Retrofit

Android http POST response


Is there a difference between "git add ." and "git add *" with respect to outcome?

Question: Both seem to add everything in the current directory. The Git add documentation points to pathspec, which points to fnmatch(3).
The docs suggests that git add . will add everything in the current directory, while git add * will add everything that matches *, which happens to be everything in the current directory. This then should result in the same outcome right? Perhaps git add . is a bit more performant because we don't have to expand the glob first?
Comment: Does this answer your question? [git add \* (asterisk) vs git add . (period)](https://stackoverflow.com/questions/26042390/git-add-asterisk-vs-git-add-period)
Comment: It possibly helps to reiterate that when you run `git add *` (on a Unix-like system, Mac OS X included), _the shell_ expands the `*` and the `git` programs receives the string "add" as its first argument and the names of the files produced by the shell as the rest of the arguments. The dot, `.` is passed to `git add` literally, and handled by `git add` by itself. The fact `*` as implemented by commonly used shells does not match the so-called "dot files" is actually a "usability hack" from the olden days, and it [can be configured](https://superuser.com/a/373751/130459).
Answer:
This then should result in the same outcome right?

Not exactly
Since * does not match hidden files in the shell, git add * will not add the hidden files/dirs in the current directory (but hidden files in subdirs will match since you add the full dir).
git add . will add everything, including hidden files in current dir.
Simple POC to illustrate:
$ tree -a
.
├── blah
├── .hidden
└── some
    ├── dir
    │   ├── .hidden
    │   └── titi
    ├── .hidden
    └── tata

2 directories, 6 files

$ git init
Initialized empty Git repository in /mydir/.git/

$ git add *

$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
    new file:   blah
    new file:   some/.hidden
    new file:   some/dir/.hidden
    new file:   some/dir/titi
    new file:   some/tata

Untracked files:
  (use "git add <file>..." to include in what will be committed)
    .hidden

$ git add .

$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
    new file:   .hidden
    new file:   blah
    new file:   some/.hidden
    new file:   some/dir/.hidden
    new file:   some/dir/titi
    new file:   some/tata

Comment: Not sure why the downvotes, but note that some command-line interpreters (the old CMD one on Windows, notoriously) don't expand `*` themselves. In this case it's up to Git to do it.
Comment: I'll be glad to know in which way this does not answer the OP's question.
Comment: Don't know why the negative votes. Adding hidden files sounds like a big difference to me... just consider .gitignore, .gitattributes.... that's a _big_ difference in outcome.


JavaFX image path for style

Question: I'm currently trying to make a custom button using JavaFX. I have defined 2 styles that contain 2 different images for 2 button states(Pressed and Free). I'm using Intellij Idea and when defining the paths it shows no error's, but the button doesn't show up. Its just transparent, but I can click it. I have tried specified different paths, but haven't gotten any result. Here is the code where I define the styles and my file tree. Thanks!
<code>public class CustomButton extends Button {
    private final String FONT_PATH = "src/Resources/GUI/pixelFont.ttf";

    private final String BUTTON_PRESSED_STYLE = "-fx-background-color: transparent;" +
            " -fx-background-image: url('../../Resources/GUI/Buttondown.png');";
    private final String BUTTON_FREE_STYLE = "-fx-background-color: transparent;" +
            " -fx-background-image: url('../../Resources/GUI/Buttonup.png');";

    public CustomButton(String text) {
        setFont();
        setPrefWidth(180);
        setPrefHeight(53);
        setText(text);
        setStyle(BUTTON_PRESSED_STYLE);
        initButtonListeners();
    }
}
</code>
File tree
Comment: Aha, thank you! Didn't see that.
Comment: Have you checked if the files exist, for example, `Boolean exists = new File("../../Resources/GUI/Buttonup.png").exists();`, if it doesn't, then are you sure that it is not an inner class resource rather than a resource in an external folder?
Comment: The file indeed exists, I am able to successfully make and display an ImageView containing this image.
Comment: @kleopatra Could you please tell me where my naming is wrong? Because according to this https://www.geeksforgeeks.org/java-naming-conventions/amp/ my naming is correct.
Comment: the package name should be lowercase :)
Answer: Moving all of the files into the pre-generated by Intellij Idea resources folder and then using that folder solved the issue.

JavaFX image path for style


Is every ring a quotient of a zero-characteristic ring?

Question: When I want to construct some ring $R$ of positive characteristic, say $n \ge 2$, I start by saying "let's consider the ring $\Bbb{Z}/n \Bbb{Z}$ and its polynomial ring etc...".
I realize that very often (*) such construction can be made with $\Bbb{Z}$ as starting point, so that the new resulting ring $\widetilde{R}$ would have characteristic $0$, and $R$ would be simply $\widetilde{R} / \langle n \rangle$.
As a consequence, this question popped into my mind:

Does every ring of positive characteristic arise as a quotient of a ring of zero characteristic?

(*): Actually this is not always the case: for example I could start with the algebraic closure of $\Bbb{F}_p$ (where $p$ is a prime), or with a Boolean ring $(\mathcal{P}(X) , \Delta , \cap)$ (which has characteristic $2$); these do not look like quotients of some ring of characteristic $0$ at first sight, but I suspect they are.
Until now, I have found no counterexamples, nor reasons to believe this is true: can you help me?
Answer: Yes; simply take the ring $\mathbb Z\langle R \rangle$, i.e. the ring freely generated by the elements of $R$. Then the map $\mathbb Z \langle R \rangle \to R$ which takes a variable with name $r$ to the element $r \in R$ provides a surjection. Edit: if we are working with commutative rings, as your commutative-algebra tag seems to indicate, use the polynomial ring instead (which is just the commutative ring freely generated by elements of $R$).
Edit: for something even more trivial, use $\mathbb Z \times R$ for a ring with the projection $\mathbb Z \times R \to R$ as a quotient mapping.
Comment: I'd like to add that if we take $A / \Bbb F _ p$ we can find a isomorphisms $\Bbb F _p [x_i] / (f_i) \to A$ this we can lift to $\Bbb Z [x_i] / (f_i) $, if we take any representatives for the $f_i$. Then we have

$\Bbb Z [x_i] / (f_i) \otimes _{\Bbb Z} \Bbb F _p \cong \Bbb F _p [x_i] /(f_i) \cong A$ which in a way shows that $\_ \otimes _{\Bbb Z } \Bbb F _p $ is surjective.


Clear textfield in a form after submit

Question: I have the following form:
<form onsubmit="chat.sendMsg(); return false;">
    Message:
    <input type="text" id="msg" name="msg" autofocus="true" placeholder="Type Your Meassage Here" />
    <input type="submit" />
</form>

and the JavaScript that goes with it:
//For sending message
this.sendMsg=function(){
    msg=document.getElementById("msg").value;
    chatZone.innerHTML+='
'+name+': '+msg+'

';
    oldata='
'+name+': '+msg+'

';
    this.ajaxSent();
    return false;
};

All works, but when I submit the form, the text stays in the form. How to clear this textfield after I hit enter/click submit?
ps I dont use jquery
Answer: Use this: document.getElementById("msg").value = '';
this.sendMsg=function(){
      msg=document.getElementById("msg").value;
      chatZone.innerHTML+='
'+name+': '+msg+'

';
      oldata='
'+name+': '+msg+'

';
      this.ajaxSent();
      document.getElementById("msg").value = '';//here
      return false;
 };

Answer: You could just add this
document.getElementById("msg").value='';

before the following statement:
return false;

Comment: Thanks, I think you both answered at the same time, so I coin flipped who got the Accpted answer, you lost :( Thanks anyway!
Comment: @Maurice not a problem dude. I am glad that I helped.

Clear textfield in a form after submit


(Multiple) Correspondence Analysis for count data entered as binary variables

Question: I have a data set, 1014 cases and 55 variables which are binary and is in the form of
Brand1Attribute1, Brand1Attribute2, ... , Brand1Attribute11, Brand2Attribute1, ... Brand5Attribute11

with 0 = "No, I do not associate this attribute with this brand" and 1 = "Yes, I associate this attribute with this brand".
Basically, I have been trying to use multiple correspondence analysis in SPSS to plot a perceptual map of how the brands and attributes relate, but I have been getting nowhere. I am imagining a 2-dimension plot, with no meaningful axes, and the distance between points is proportional to the correlation between brands, or attributes, or between brand and attribute.
Am I going about this the right way, or should I be using a different method?
Answer: Correspondence Analysis is a method to visualize a contingency table, such as frequency cross-table. I presume that the table in your case would be 5 Brands X 11 Attributes and the entries are frequencies (counts) of 1s: attribute is characteristic of a brand. And you want the analysis to produce a biplot wherein points-brands are acommpanied by points-attributes characteristic of them.
Note that since your table is 2-way (Brands X Attributes), simple correspondence analysis is a method to choose. You don't have to entangle with multiple correspondence analysis which is a more general method for k-way tables. SPSS has both simple and multiple correspondence analyis procedures.
Your data is, so far, original respondent-level data, not the frequeny cross-table. Command CORRESPONDENCE (Simple correspondence analysis) can take in data in various of ways:

Two categorical nominal variables - Brand and Attribute - with only
"Yes" responses, a data case being a response. This is the way
suitable if you want to run CORRESPONDENCE from the dialog box.
Two categorical nominal variables - Brand and Attribute, aggregated, plus the frequency variable weighting the dataset.
Input right the 2-way rowsXcolumns contingency table. This option is available only throuh syntax, not dialog box.

Below I'm showing, as an example, the 1st way in detail.
  Imagine this is your data: 3 Brands X 4 Attributes binary variables, 20 respondents.
  B1A1   B1A2   B1A3   B1A4   B2A1   B2A2   B2A3   B2A4   B3A1   B3A2   B3A3   B3A4
     1      1      0      1      1      0      0      0      0      0      1      0
     1      1      1      0      0      1      1      1      0      0      0      0
     0      1      0      0      1      1      1      1      0      0      1      1
     1      1      0      1      1      1      0      1      0      1      1      1
     1      1      1      1      1      1      0      1      0      0      0      0
     1      0      0      1      1      0      0      1      0      0      1      0
     1      0      1      1      0      0      0      0      1      0      1      0
     0      0      0      1      1      1      0      1      1      1      0      1
     0      1      1      1      0      0      1      1      0      1      0      0
     0      0      1      0      0      1      0      0      0      1      0      1
     1      1      1      0      1      0      0      1      0      0      1      0
     0      0      0      1      1      1      0      1      0      1      0      1
     1      1      1      0      1      1      0      0      1      0      1      0
     1      0      0      0      1      1      0      1      1      0      0      1
     1      0      0      0      1      0      0      0      0      0      1      0
     0      0      0      1      0      0      0      1      0      1      0      1
     0      0      0      0      1      1      0      0      0      0      0      0
     1      0      0      0      1      1      1      1      1      0      0      0
     0      0      0      0      1      1      1      0      0      1      0      0
     0      1      1      0      1      1      0      1      0      1      1      1

*Restructure the data (Goto menu Data-Restructure).
*Gather data corresponding to each brand into a single column.
*The syntax will be this.
VARSTOCASES
  /ID= id /*Let's create respondent id, just in case
  /MAKE B1data FROM B1A1 B1A2 B1A3 B1A4 /*Data of brand B1 goes here
  /MAKE B2data FROM B2A1 B2A2 B2A3 B2A4 /*Data of brand B2 goes here
  /MAKE B3data FROM B3A1 B3A2 B3A3 B3A4 /*Data of brand B3 goes here
  /INDEX= Attribute(4) /*Create variable with codes 1...4 marking the attributes
  /KEEP=
  /NULL= DROP.

*Restructure the resultant dataset once again.
*This time gather data from 3 brands into single column.
VARSTOCASES
  /MAKE Data FROM B1data B2data B3data
  /INDEX= Brand(3) /*Create variable with codes 1...3 marking the brands
  /KEEP= id Attribute /*Preserve these variables as is in the output dataset
  /NULL= DROP.

*In the resultant dataset each case corresponds to a response, not respondent.
*The response itself (1 or 0) is in variable Data.
*Respondent number is saved in id, attribute code in Attribute, brand code in Brand.
*You may now add value labels to the latter two variables so that they will show on the
*future map (try to make labels consize therefore).

*Since we are interested in "Yes" data only, delete rows with zero data.
SELECT IF Data=1.
EXEC.
*We don't need variable Data anymore.

*Go to Correspondence Analysis dialog box.
*Enter Attribute and Brand Variables as defining the table and specify their range of codes.
*Leave defaults for everything else.
*Press Paste. The following syntax appears.
CORRESPONDENCE
   TABLE= Attribute(1 4) BY Brand(1 3)
  /DIMENSIONS= 2 /*We'll request 2d solution
  /MEASURE= CHISQ /*using Chi-sq distance, most appropriate for the analysis of frequencies
  /STANDARDIZE= RCMEAN /*this often produce interpretable maps, but you could try other methods too
  /NORMALIZATION= SYMMETRICAL /*This means the biplot is most balanced in terms of "inertia"
  /PRINT= TABLE RPOINTS CPOINTS
  /PLOT= NDIM(1,MAX) BIPLOT(20).

It is noteworthy that Correspondence Analysis algorithm does not model the affinity between row categories and column categories directly. It allocates row points according to their profile similarity and column points according to their profile similarity - separately, in the space common to both. Thus, the affinity between a row point and a column point just emerges as the result of that "overlay". This is theoretically valid (as any biplot is), but Multidimensional Unfolding (MDU) might be a better choice because it does fit the rows-columns similarities directly. SPSS has quite versatile MDU procedure, so you can use it if you want. It can internally do preliminary Correspondence analysis to obtain the initial configuration for itself; or you can input the coordinates left by your (customized) Correspondence analysis as such initial configuration. Relations among several mapping techniques are briefly mentioned here. Maths of two-way (simple) correspondence analysis and related biplot techniques are found here.
Comment: +1. Sorry for the late reply, but this was perfect for what I needed. Thanks ttnphns!


Uncaught Error: Bootstrap's JavaScript requires jQuery on angular 4

Question: I'm trying to use Electron to make a simple application using Angular 4 and Bootstrap. The project can be found here.
When a run electron through

electron src/main.js

in folder electron, I got the error

Uncaught Error: Bootstrap's JavaScript requires jQuery

I tried force jQuery on main.ts, also tried to create vendor.ts and put it on .angular-cli.json like some workarounds I found. But didn't work at all.
I don't know what I should do to Bootstrap detect jQuery.
Answer: I removed "bootstrap.min.js"  and my error was solved.


select certain words from list of string after comma

Question: What i want to do is take particular values from a list of strings and store them into variables for that particular index.
Com317,subject,1,20,M,year1
the example is what is contained in each index of the list of strings. I want to select the 1 and the 20 from this list and store them into 2 variables. Been trying to do this with a for each loop but I'm not sure how i can single out these 2 values
thanks
Answer: maybe something like that should works
This is pseudocode (I dont have VS installed on this computer, so check for bugs)
dim st as string
st = "Com317,subject,1,20,M,year1"

dim var1 as integer
dim var2 as integer

var1 = CInt(st.split(",")(2))
var2 = CInt(st.split(",")(3))

Answer: You can use the split function to accomplish this:
Dim s As String = "Com317,subject,1,20,M,year1"
Dim splitVals As String() = s.Split(",")

MessageBox.Show(splitVals(2)) ' 1
MessageBox.Show(splitVals(3)) ' 20

Comment: yea i just got it :) using the same function, thanks for confirmation that this is the way it should be done


Replace a specific dictionary entry

Question: For my assignment I'm required to use file management in order to access information about the price/stock of certain items.
I'm currently using a dict like this
stock = {"Bread" : 27,
"Car" : 1,
"Banana" : 3000}

How would I go about to change the number of bananas in stock for instance?
Comment: It would be hard to believe that your teacher(s) have not provided basic information about dictionaries, but just in case here is the [Python Tutorial section](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) on them.
Comment: Ok. So presumably you know how to read the data from the file and store it into the `dict`. And your _real_ question is that you want to know how to write the modified data back to the file. So give it a try! It's not that hard. If you get stuck, put a [mcve] into your question and we'll help you fix it.
Comment: Did you try searching for [this](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)? `stock['Banana'] = new_value`
Comment: What does file management have to do with this? Are you reading from a file into a dictionary?
Comment: @user161151 Correct, updating a dictionary is easy I'm just not sure how to do it to another file.
Comment: This is like the first thing you do with a dictionary after creating it. Read a tutorial.
Answer: stock["Banana"] = new_value should do it.
Comment: While this does answer the _title_ of my question, I can't access a dictionary in another file with this.
Comment: @Carlgroth, it doesn't just answer the title. it answers the body as well. I see the comment you made, but it doesn't clarify what your problem is percisely. I suggest you try and ask the question you want answered exactly, instead of hoping we guess your problem. State your mission statement, and pseudo-code for what you want to accomplish.
Answer: You can access value using key in dictionary , so you can go like this -
stock['Banana']=23  // any desired number

Replace a specific dictionary entry


Compute partial derivatives of a function

Question: I am working with this paper to identify the term structure of interest rate using the potential approach rather than one or tow factor models. Anyway I came to example 2 for $X_t$ which is stochastic define as $$dX_t=dW_t-B X_t \, dt$$ where $B$ is general $d \times d$ matrix and this $X_t$ has a multi-variant normal distribution. Then example 2 which is (exponential-quadratic example) give us the function
$$f(x)= \exp \left( \frac{1}{2} (x-c)^T Q (x-c) \right)$$ where $c$ belongs to $\mathbb{R}^d$ and $Q$ is a $d \times d$ positive definite symmetric matrix. I want to find the first and second partial derivative of $f$ with respect to $x$ ?
I tried many times but I could not could any one guide me to the solution or help me by recommending books might help me distinguish the solution
Comment: Please have a look at the [MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) so that you can format your questions properly. Otherwise they are really hard to read which makes it quite unlikely that you will get feedback.
Answer: I answered wrongly and noone noticed that it was absolutely wrong. This answer should be correct:
$$\frac{\partial f}{\partial x_i} = \frac{\partial}{\partial x_i}\left(\frac{1}{2} (x-c)^T Q (x-c) \right)\cdot\exp \left( \frac{1}{2} (x-c)^T Q (x-c) \right) = \frac{1}{2}\left(\frac{\partial}{\partial x_i}(x-c)^T Q (x-c) + (x-c)^T Q \frac{\partial}{\partial x_i}(x-c)\right)\cdot\exp \left( \frac{1}{2} (x-c)^T Q (x-c) \right) = \frac{1}{2}\left(e_i^T Q (x-c) + (x-c)^T Q e_i\right)\cdot\exp \left( \frac{1}{2} (x-c)^T Q (x-c) \right) = \frac{1}{2}\left(Q_{i\_} (x-c) + (x-c)^T Q_{\_i}\right)\cdot\exp \left( \frac{1}{2} (x-c)^T Q (x-c) \right)$$
$e_i$ stands for the i-th vector in Eucleidan basis.
$Q_{i\_}$ stands for i-th row of Q and $Q_{\_i}$ stands for i-th column of Q.
If $Q = Q^T$, it can be simplified to:
$$\frac{\partial f}{\partial x_i} = Q_{i\_} (x-c)\cdot\exp \left( \frac{1}{2} (x-c)^T Q (x-c) \right)$$
And now the second partial derivatives:
$$\frac{\partial^2 f}{\partial x_j x_i} = \frac{\partial}{\partial x_j}\left(Q_{i\_} (x-c)\right)\cdot Q_{j\_} (x-c)\cdot\exp \left( \frac{1}{2} (x-c)^T Q (x-c) \right) = \left(Q_{i\_} e_j\right)\cdot Q_{j\_} (x-c)\cdot\exp \left( \frac{1}{2} (x-c)^T Q (x-c) \right) = Q_{ij}\cdot Q_{j\_} (x-c)\cdot\exp \left( \frac{1}{2} (x-c)^T Q (x-c) \right)$$


Using orderBy correctly with hook_query_alter

Question: I have a hook_query_alter function that I'm using to edit my search.module results. It works ok so far. However, I'm having trouble adding an orderBy condition that I need. Here's the SQL I want added that I'm using successfully elsewhere in a custom module:
    ORDER BY ('fdfty.field_type_value' = 'Webinar'),
('fdfty.field_type_value' = 'Workshop'),
('fdfty.field_type_value'= 'Conference'),
fdfed.field_event_dates_value, n.title

That's accepted SQL for ordering by specific values. However, when I try to add something similar to my query_alter function orderBy clause, like so:
$query->orderBy('fdft.field_type_value' = 'Conference');

Well, Drupal doesn't like the '=' sign being in there. Is there another way to include such normal SQL criteria in hook_query_alter?
Thanks!
Here's the complete code I'm working with in template.php:
// function for search results page to return correct results that meet business logic
function zen_pathfinder_query_alter(QueryAlterableInterface $query) {
    if (get_class($query) == 'PagerDefault') {
        foreach ($query ->getTables() as $table) {
            if ($table['table'] == 'search_index') {
                $query->leftjoin('field_data_field_event_dates', 'fdfed', 'n.nid = fdfed.entity_id');
                $query->leftjoin('field_data_field_type', 'fdft', 'n.nid = fdft.entity_id');
                $query->where('fdfed.field_event_dates_value >= CURRENT_DATE OR fdfed.field_event_dates_value IS NULL');
                    //->groupBy('fdft.field_type_value');
                $query->addField('fdft', 'field_type_value');
                $sql = 'CASE WHEN fdft.field_type_value = :first THEN 0
                WHEN fdft.field_type_value = :second THEN 1
                WHEN fdft.field_type_value = :third THEN 2
                WHEN fdft.field_type_value = :fourth THEN 3
                WHEN fdft.field_type_value = :fifth THEN 4
                WHEN fdft.field_type_value = :sixth THEN 5
                WHEN fdft.field_type_value = :seventh THEN 6
                WHEN fdft.field_type_value = :eighth THEN 7
                WHEN fdft.field_type_value = :ninth THEN 8
                WHEN fdft.field_type_value = :tenth THEN 9
                END';
                $query->addExpression($sql, 'my_alias', array(
                ':first' => 'Webinar',
                ':second' => 'Workshop or Training',
                ':third' => 'Conference',
                ':fourth' => 'Article or Report',
                ':fifth' => 'Blog',
                ':sixth' => 'Podcast or Webcast',
                ':seventh' => 'Newsletter or Magazine',
                ':eighth' => 'Tool',
                ':ninth' => 'Book or Workbook',
                ':tenth' => 'Certificate or Degree Program' ,
                ));
                $query->orderBy('my_alias');
                $query->orderBy('fdfed.field_event_dates_value');
                $query->orderBy('title');
            }
        }
    }
}

I keep getting a "Column not found: 1054 Unknown column 'my_alias' in 'order clause" error when I go to the search page. So I ran dpm((string) $query); and the results are as follows:
      SELECT SUM(i.score * t.count) AS calculated_score
        FROM
        {search_index} i
        INNER JOIN {node} n ON n.nid = i.sid
        INNER JOIN {search_total} t ON i.word = t.word
        WHERE  (n.status = :db_condition_placeholder_0) AND( (i.word =
:db_condition_placeholder_1) )AND (i.type = :db_condition_placeholder_2) AND (n.type NOT
IN  (:db_condition_placeholder_3, :db_condition_placeholder_4,
:db_condition_placeholder_5))
        GROUP BY i.type, i.sid
        HAVING  (COUNT(*) >= :matches)
        ORDER BY calculated_score DESC
        LIMIT 1 OFFSET 0

        SELECT fdft.field_type_value AS field_type_value, CASE WHEN fdft.field_type_value =
    :first THEN 0
                        WHEN fdft.field_type_value = :second THEN 1
                        WHEN fdft.field_type_value = :third THEN 2
                        WHEN fdft.field_type_value = :fourth THEN 3
                        WHEN fdft.field_type_value = :fifth THEN 4
                        WHEN fdft.field_type_value = :sixth THEN 5
                        WHEN fdft.field_type_value = :seventh THEN 6
                        WHEN fdft.field_type_value = :eighth THEN 7
                        WHEN fdft.field_type_value = :ninth THEN 8
                        WHEN fdft.field_type_value = :tenth THEN 9
                        END AS my_alias
        FROM
        {search_index} i
        INNER JOIN {node} n ON n.nid = i.sid
        INNER JOIN {search_total} t ON i.word = t.word
        LEFT OUTER JOIN {field_data_field_event_dates} fdfed ON n.nid = fdfed.entity_id
        LEFT OUTER JOIN {field_data_field_type} fdft ON n.nid = fdft.entity_id
        WHERE  (n.status = :db_condition_placeholder_0) AND( (i.word =
    :db_condition_placeholder_1) )AND (i.type = :db_condition_placeholder_2) AND (n.type NOT
    IN  (:db_condition_placeholder_3, :db_condition_placeholder_4,
    :db_condition_placeholder_5)) AND (fdfed.field_event_dates_value >= CURRENT_DATE OR
    fdfed.field_event_dates_value IS NULL)
        GROUP BY i.type, i.sid
        HAVING  (COUNT(*) >= :matches)
        ORDER BY my_alias ASC, fdfed.field_event_dates_value ASC, title ASC

Answer: You can use SelectQueryInterface::addExpression to add a CASE statement to the select and then order by that:
$sql = '
  CASE WHEN fdfty.field_type_value = :first THEN 0
       WHEN fdfty.field_type_value = :second THEN 1
       WHEN fdfty.field_type_value = :third THEN 2
  END';
$alias = $query->addExpression($sql, 'my_alias', array(
  ':first' => 'Webinar',
  ':second' => 'Workshop',
  ':third' => 'Conference',
);
$query->orderBy($alias, ASC);

Comment: @montaigne when you say 'my_type' what's supposed to go there? I've tried the field_type, which is the field name in the content type; I've tried field_data_field_type which is the table the type is stored in and I've tried both field_type_value itself and just 'my_type' as you typed it. I just get errors that no such column 'my_type' for example, exists.
Comment: Try the updated snippet. I had a quoting error in the SQL string and am now using placeholders. Renamed `'my_type'` to `'my_alias'` to clarify that this parameter is used to pass an alias for this expression that you can use later for the `orderBy` method. See the [API](https://api.drupal.org/api/drupal/includes%21database%21select.inc/function/SelectQueryInterface%3A%3AaddExpression/7) and [documentation](https://www.drupal.org/node/1848358) for more information.
Comment: @montaigne thank you that makes sense. However I'm still getting the error 1054 Unknown column 'my_alias' in 'order clause, which makes no sense to me. I don't know why it thinks 'my_alias' is supposed to be a column in the table...I'm updating my question with the complete code at the bottom so you can see what I'm working with.
Comment: Try adding the field's value column to the SELECT statement (`$query->addField('fdft', 'field_type_value')`) prior to adding the CASE expression. Also, note that you can only pass one field at a time to `SelectQueryInterface::orderBy`. To order by multiple fields call the method multiple times.
Comment: @montaigne I updated those things (see code above again) and am still getting column not found error. I've ensured that's the name of the column and field in mysql, checked my search index to make sure it's part of it, flushed my caches. It just keeps giving me the same error. The only way it doesn't give me the error is if I add a return line after the end of addExpression(); like so: { return 'my_alias'; } but then it doesn't give me the results ordered. Do you think I need a return line or am I barking up the wrong tree there?
Comment: As noted in the API, the alias requested by `SelectQuery::addExpression` may not be the actual alias used (it's checked for uniqueness), so it's more robust to use the return value of the method. I've updated my code with this in mind. If that still doesn't work, I believe this is an error thrown by the SQL server (MySQL, correct?). Can you dump the SQL string at the end of your alter function using `$query->__toString()` and post it?
Comment: @montaigne Ok, I ran dpm((string) $query); I hope that's what you meant. I tried $query->__toString() but it never output anything. I've updated my question above with the results.
Answer: Have a look at the API.
orderBy in Drupal doesn't accept operators.  Instead it should be:
$query->orderBy('fdft.field_type_value', ASC);

I suggest either sorting by the key or weight of the field value (if there is one).


What else can I do to my tennis racket to keep the ball in the court?

Question: I like to swing fast and hard....very hard. I get my stress out. But even with a head light tennis racket, on which I've weighted the handle, and top spin, my hits go too far.
I once borrowed a racket, and no matter how hard I hit it the ball stayed in court. Unfortunately I have lost contact with the person who had that racket.
What else can I do to my racket? I was thinking higher tension on the strings. Would that help?
Comment: Generally you need to balance power with control. having very high power and very high control is almost impossible, and that is just the configuration of your racquet. But good technique will trump what is being held in your hand (provided it is still a racquet)
Comment: Higher tension will, if anything, allow higher speeds. Don't do this!
Answer: One thing that all tennis players need to know is that the natural instinct of swinging the racquet like a baseball bat is not the best play to make. If you look at most professional players, they don't do full out swings. Instead, they focus more on the top spin by having an angle at the racquet as shown below.
I would say that it is more important to focus on having a topspin and lowering down your swing power. You can read this discussion for more help: https://www.quora.com/How-do-I-fix-the-problem-of-hitting-my-tennis-ball-too-far
Answer: String tension is extremely important in how much control you have over
the ball you are hitting.  For beginning players a lower string tension
results in the strings helping to power the ball -- but in some ways there
is less control.  With a higher string tension (around 60 lbs) you are
not using the stings to give you power.
   Additionally it might be that a heavier racquet might cause you to
slow down your hitting stroke.


Unable to pass JSON object in body to WebAPI

Question: I have an MVC 4 project containing a simple WebAPI2 controller. I'm trying to pass it data encoded as JSON within the POST body.
Public Class ClientController
    Inherits ApiController

    <AllowAnonymous>
    <HttpPost>
    <Route("api/Client/")>
    Public Function Post(<FromBody> entry As LogEntry) As HttpResponseMessage

        Try
            Dim lld As New LoginLogsEntities
            lld.sp_insertofflineloginaudit(entry.Hostname, entry.ClientName, entry.SessionID, entry.EventAction, entry.EventDateTime)
            Return New HttpResponseMessage(HttpStatusCode.Accepted)
        Catch ex As Exception
            Return New HttpResponseMessage(HttpStatusCode.BadRequest)
        End Try

    End Function

End Class

And the LogEntry class:
Public Class LogEntry
    Private _EventDateTime As DateTime
    Private _OSVersion As String
    Private _Hostname As String
    Private _SessonID As String
    Private _EventAction As String
    Private _Username As String
    Private _ClientName As String

    <JsonProperty("EventDateTime")>
    Public Property EventDateTime() As DateTime
        Get
            Return _EventDateTime
        End Get
        Set(ByVal value As DateTime)
            _EventDateTime = value
        End Set
    End Property

    <JsonProperty("OSVersion")>
    Public Property OSVersion() As String
        Get
            Return _OSVersion
        End Get
        Set(ByVal value As String)
            _OSVersion = value
        End Set
    End Property

    <JsonProperty("Hostname")>
    Public Property Hostname() As String
        Get
            Return _Hostname
        End Get
        Set(ByVal value As String)
            _Hostname = value
        End Set
    End Property

    <JsonProperty("SessionID")>
    Public Property SessionID() As String
        Get
            Return _SessonID
        End Get
        Set(ByVal value As String)
            _SessonID = value
        End Set
    End Property

    <JsonProperty("EventAction")>
    Public Property EventAction() As String
        Get
            Return _EventAction
        End Get
        Set(ByVal value As String)
            _EventAction = value
        End Set
    End Property

    <JsonProperty("Username")>
    Public Property Username() As String
        Get
            Return _Username
        End Get
        Set(ByVal value As String)
            _Username = value
        End Set
    End Property

    <JsonProperty("ClientName")>
    Public Property ClientName() As String
        Get
            Return _ClientName
        End Get
        Set(ByVal value As String)
            _ClientName = value
        End Set
    End Property
End Class

On the client side, I've tried a couple of things. the raw JSON included in the body is:
{
    "EventDateTime":"2022-08-19T04:02:51.3512145Z",
    "OSVersion":"10.0.19044",
    "Hostname":"comp",
    "SessionID":"E1B60C64B1",
    "Event":"Lock",
    "Username":"bob"
}

I've tried sending the request from PowerShell and using Boomerang (an Edge clone of Postman) but in all cases, while the post entry point is hit, the parameter is null. PowerShell code as below:
invoke-webrequest -Uri http://localhost:54321/api/Client -Method Post -Body $event -ContentType "application/json"

Answer: Problem solved; the JSON being passed was not valid. The Username parameter (before I edited it for this question), contained a domain name and username. The backslash was not correctly escaped.


Types of declaration methods Angular 6

Question: I am having some confusion about below 2 types of declarations.
filterabcData: abcHeader[] = [];

and
searchedabcDetails = new abcHeader();

Anyone help me for this.
Comment: The first one is Array of type AsnHeader and the second one is an object of type AsnHeader
Answer:
First one declaration says that filterabcData is an array having
items of abcHeader type.
Second declaration is pointing that you are creating an object of abcHeader class  and storing it inside searchedabcDetails.
Comment: @user2609024 please accept my answer if you are able to understand.

Types of declaration methods Angular 6


Question about batter's position in batter's box prior to pitch

Question: Since I've read two different interpretations of this, I'm going to ask a question about the batter's box and the batter's orientation in it prior to the pitch, even if I'm pretty sure I know the answer.
Under OBR, it says that a batter's legal position in the box while addressing the pitcher is when both feet are within the lines of the box (the lines themselves being part of the box). So, simply, prior to hitting the pitch, this means the batter cannot even have a toe outside the white chalk lines, correct? I read on some shady site that you just need your foot touching the lines, meaning you can have your toes at least partially outside the lines. However, all other evidence seems to be the contrary. So, must the batter have both feet entirely within the lines, no toes/heels, etc outside the lines? I realize he's able to have a toe outside the line when actually hitting the ball, by the way.
Comment: The rules on this are never really enforced.  I've seen batters standing wherever they want.  I've never seen an umpire say anything.
Answer: Both feet have to be in the batter's box if you swing and make contact with the ball and you have a foot outside of the box on the plate and or over the plate you can be ruled out if and only if the Umpire see this happen as far as your question both feet have to be in the Box for the picture to throw the ball to home plate