Term for movements in a song?

Question: In Skyrim's Score, Combat 6 there are several "movements":
0:17~
0:33~
0:48~
1:04~
1:36~
2:07~2:24
Here is the song:

I do not inherently believe that the term movements applies to parts of a song though I could be wrong, if not what is the term for the various sequences I've listed above?
Answer: I believe the term you are looking for here is a passage:

A passage is a musical idea that may or may not be complete or independent. For example, fill, riff, and all sections.

Those definitely aren't different movements in that piece. A movement is a:

self-contained part of a musical composition or musical form.

Those sections (or passages) you are referring to aren't self contained, they are also not independent. In a piece movements typically have a pause in between, before starting in a different key and/or tempo.
Comment: Good suggestion, passage. In this particular case I would consider the alternative "theme", as the piece is probably a kind of rhapsody compressing the game's soundtrack, normally several hours lengthy, into just a few minutes. Each section succinctly presents a theme that is fully extended and developed in the proper full soundtrack.
Comment: @joseem That's a good point! I hadn't considered it being a rhapsody.

Term for movements in a song?


SSL cert for used by a trusted 3rd party on my subdomain

Question: I own example.com, and I'd like to get an SSL cert. Normally I would simply buy a wildcard cert, so that I can add subdomains for future purposes.
However, I need to let a trusted 3rd party operate a subdomain of my site: 3rdparty.example.com. Our site will link to theirs for some specific functionality. We will keep the site look and feel the same so that users don't get confused. For the same reason we'd like to keep the 3rd party site under our domain.
What kinds of SSL certs do I need to buy for this scenario? They want me to buy the cert for the 3rdparty subdomain and send it to them.
edit:
The 3rd party is not competent, and I've never had to dive very deep into SSL. Based on the feedback and additional reading, I will outline the CSR fields (so they don't misspell anything) and ask them to create the CSR and send it to me. I will then apply for the 3rdparty.example.com cert, which according to godaddy also applies to www.3rdparty.example.com. There is no need for me to ever touch the private key used to sign the CSR, I can revoke the certificate using godaddy's web console if needed.
Can I still get a wildcard ssl cert for myself for *.example.com, or will this cause a conflict somehow? I haven't seen this exact scenario addressed anywhere.
Answer: Just get a standard certificate for whatever the domain name is that will be used to access resources on that side.  There really should need to be anything special.
I am a bit curious about the bit of having you purchase the certificate.  Did they send you a certificate signing request?  If not, then you should have them generate the private key and CSR for the correct name, so you can purchase the certificate.  The private key should be private which means they should be generating it, not you creating one and transferring it to them.
Comment: I agree with your argument about the private key, but if it's his domain anyway and he's effectively responsible for it (and confirming to the CA that a cert should be issued with this name), it would make sense for him to have the private key too. (It might simplify the revocation procedure in case of conflict, perhaps.)
Comment: @Bruno, if he generates it, then there is multiple copies, weakening security.  **He will also have to arrange for some kind of secure transport.**  Does the 3rd party have some kind of https web portable to upload the pkcs12 file?  Surely you wouldn't suggest that he email it?  I suppose in some cases the value of having a copy is worth the added risk of having multiple copies of the key, and transporting it over the Internet.  Anyway, the 3rd party should be able to tell him what they prefer, if they aren't incompetent.


Opening IE Browser from C#

Question: I can open a new IE browser via this code:
<code>var IE = new SHDocVw.InternetExplorer();
        object URL = "http://google.com";

        IE.ToolBar = 0;
        IE.StatusBar = false;
        IE.MenuBar = true;
        IE.AddressBar = true;
        IE.Width = 622;
        IE.Height = 582;
        IE.Visible = true;
        IE.Navigate2(ref URL);
</code>
That part and the sizing work fine but I am unable to set the location the window.
I need to open about 5 new individual IE browsers and all must be in different locations across the screen.
What is the syntax for the location?
Answer: Try Using the Left property.
[https://msdn.microsoft.com/en-us/library/aa752056(v=vs.85).aspx][1]
<code>   IE.Left = 0;
</code>

Opening IE Browser from C#


Alternative diff algorithm for special file extension for Git

Question: I want to use an alternative diff algorithm for special file extension, e.g. ".java" and the standart diff algorithm for other files.
I can make it via .gitattributes file:
*.java diff=javadiffprogramm

and .gitconfig file:
[diff "javadiffprogramm"]
    command = pathToDiffProgram.

My question is what is the format of input parameters of "javadiffprogramm" and where it should output the result of diff? The result of diff has the format like "@@ -1,7 +1,6 @@...".
Some questions on this topic:

Using custom diff tool with git show
Is it possible to set diff/merge-tool for a specific file extension in git-extensions?
Setup 'git diff' for special file types
Answer: This is documented in the git man page as GIT_EXTERNAL_DIFF.

GIT_EXTERNAL_DIFF
When the environment variable GIT_EXTERNAL_DIFF is set, the program named by it is called, instead of the diff invocation described above. For a path that is added, removed, or modified, GIT_EXTERNAL_DIFF is called with 7 parameters:
path old-file old-hex old-mode new-file new-hex new-mode

The docs go on to explain what those parameters are.
Output should be to STDOUT.
Comment: Thanks a lot! I have found about 7 input parameters, but nothing about Output. Maybe I wasn't attentive.
Comment: @NAlmaz I couldn't find information about output either. It's an educated guess based on how Unix tools generally work. If Git wants the output written elsewhere it can redirect it itself.


Copy entire row from another sheet to sheet 1 if unique code typed in matches

Question: https://www.dropbox.com/s/f83y17dedajbsz8/example.xls
That's a quick sample workbook of what I want this to work in.
Right now, sheet 1 (main) needs to have data from all the other worksheets copied to it manually. At the moment, what I am doing is I have a list of the unique codes I need, and I go to the sheet and ctrl+F for that code, then manually copy+paste that row into sheet 1 (main). It can be a bit time consuming.
What I want to do instead is to simply TYPE ANY unique code into any cell of column D on sheet 1, and then if that code matches the code on any of the other sheets, then the entire row will copy over to sheet 1.
Is this easily do-able?
Comment: Depending on how hard it is to find your unique code in the other sheets it should be fairly simple to accomplish your goal.
Answer: The following VBA should do the trick, you need to copy it into the workbook code section for Sheet1 (Main).
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Sheet As Worksheet
Dim Index As Integer
Dim Count As Integer
Dim Match As Range

    If Target.Rows.Count > 1 Or Target.Columns.Count > 1 Then
        ' You've done something that has edited lots of cells. Cant handle this.
        Exit Sub
    End If

    Set Sheet = ThisWorkbook.Worksheets("Main")

    If Not Intersect(Sheet.Range("D:D"), Target) Is Nothing Then
        ' The edited cell falls in the range D:D
        Count = ThisWorkbook.Worksheets.Count

        For Index = 1 To Count
            If Not ThisWorkbook.Worksheets(Index).Name = Sheet.Name Then
                Set Match = ThisWorkbook.Worksheets(Index).Range("D:D").Find(What:=Target.Value, LookIn:=xlValues)
                If Not Match Is Nothing Then
                    'copy the line across
                    ThisWorkbook.Worksheets(Index).Range("A" & Match.Row & ":E" & Match.Row).Copy Sheet.Range("A" & Target.Row)
                    Exit For
                End If
            End If
        Next Index

    End If

    If Match Is Nothing Then
    ' optional, if the target string is  not found clear the line.
        Sheet.Range("A" & Target.Row & ":E" & Target.Row).ClearContents
    End If

End Sub

Comment: That worked absolutely perfectly, and thanks so much for commenting the code. That made it so much easier to adapt to other worksheets too. Thanks so much!!


Views to display nodes based on ACL permission

Question: I'm trying to use Flexiaccess with ACL to build a view based on node that the user has access granted by Flexiaccess.
I found this on Drupal.org, it's the same use case, but is not working for me maybe because is for Drupal 6. (http://drupal.org/node/549412):

Here's how to do it:

Under Arguments, create a new argument: "Node: Nid"
Under "Action to take if argument is not present", select "Provide
  default argument"
Set the "Default argument type" to "PHP Code", and enter the
  following:
global $user; return db_result(db_query("SELECT
  GROUP_CONCAT(CAST(an.nid AS CHAR) SEPARATOR ',') FROM {acl_user} au
  INNER JOIN {acl_node} an ON au.acl_id = an.acl_id WHERE an.grant_view
  = 1 AND au.uid = %d", $user->uid));
Then check "Allow multiple terms per argument", and click "Update".

I follow those steps but my view shows nothing.
Any help is really appreciated.
Answer: According to: https://www.drupal.org/node/1255426, Drupal 7 does not have db_result function. You have to replace it with db_query().
Code which worked in my special case:
<?php
global $user;
$query = db_query("SELECT GROUP_CONCAT(CAST(an.nid AS CHAR) SEPARATOR ',') FROM {acl_user} au INNER JOIN {acl_node} an ON au.acl_id = an.acl_id WHERE an.grant_view = 1 AND au.uid = :uid", array(':uid' => $user->uid));
$result = $query->fetchObject();
return reset($result);
?>

Answer: Use Contextual Filters instead of arguments in Drupal 7 and check "Provide default value" and in PHP code insert like this.
global $user;
$query = db_query("SELECT GROUP_CONCAT(CAST(an.nid AS CHAR) SEPARATOR ',') FROM {acl_user} au INNER JOIN {acl_node} an ON au.acl_id = an.acl_id WHERE an.grant_view = 1 AND au.uid = :uid", array(':uid' => $user->uid));

$result = $query->fetchObject();
 return reset($result);

You can also get users allowed to view against each node like this by adding field for "views PHP" with this code
$query = db_query("SELECT GROUP_CONCAT(CAST(au.uid AS CHAR) SEPARATOR ',') FROM acl_user as au INNER JOIN acl_node as an ON au.acl_id = an.acl_id WHERE an.grant_view = 1 AND an.nid =$row->nid ");
$result = $query->fetchObject();
$res = reset($result);

$myArray = explode(',', $res);
//print_r($myArray);
foreach($myArray as $key=>$value){
                     $user_id = $value;
                     $query_user = db_query("SELECT name FROM users WHERE uid = $user_id");
                    $result_u = $query_user->fetchObject();
                    print "" .$result_u->name. "  ";

          }


4 green balls and 7 blue balls

Question: How many combinations for those 11 balls
A. All combinations
B. which no green balls adjoining
A. There are 11 positions
What i know, after we put 1 balls in one positions the next time we have one less ball for the next positions
But i can't understand how to apply combinations formula for this
B. _G_G_G_G_
There 5 positions for 7 blue balls to be put
And 3 middle positions must filled with blue balls, so there are 4 blue balls left for 5 positions.
But, how is it exactly? Please help me
Answer: For (A), we have $11$ available positions from which we simultaneously select a subset of $4$ of those positions to be used by the green balls.
We have $11$ positions and we choose $4$ of them.  $11$ choose $4$.  The answer will be $\binom{11}{4}$ (read aloud as $11$ choose $4$).  Remember that there are precisely $\binom{n}{r}$ ways to choose a subset of $r$ objects from a set of $n$ objects.
For (B), rather than placing the green balls first and fitting the blue inbetween... you would be better off by placing the blue balls first and making space to each side and placing the green balls in those spaces, using at most one green ball per space.
So, we have our $7$ blue balls arranged with spaces like so:
$$\underline{~~~}B\underline{~~~}B\underline{~~~}B\underline{~~~}B\underline{~~~}B\underline{~~~}B\underline{~~~}B\underline{~~~}$$
There are $8$ spaces available from which we want to choose $4$ of them to be used by the green balls.

 As an aside, you could have continued in the fashion that you started, having placed the green balls first and inserting a blue ball into each important gap., leaving you with four blue balls left to place into the five available gaps but allowing more than one ball per gap.  We could continue with stars-and-bars to get $\binom{4+5-1}{5-1}$ ways to continue, which of course equals the answer we would have gotten in the other way of $\binom{8}{4}$.  Stars-and-bars requires a bit more prerequisite knowledge however, so I would expect that you should have understood the first approach, but not necessarily the stars-and-bars approach.

4 green balls and 7 blue balls


For f continuous on $[0,1]$, show that there exist points $\alpha_k$ such that $\sum \limits_{k=1}^n \frac{1}{f'(\alpha_k)} = n $

Question:
Suppose that $f$ is continous on $[0,1]$ , differentiable on $(0,1)$ , and $f(0)=0$ and  $f(1)=1$.For every integer $n$ show  that there must exist $n$ distinct points $\alpha_1,\alpha_2\cdots,\alpha_n$ in that interval so that
   $\sum \limits_{k=1}^n \frac{1}{f'(\alpha_k)} = n $

Is it theorem or i can show it with basic differentiation knowledge .Please give me hint .
Comment: Hint: A twist of [MVT](http://en.wikipedia.org/wiki/Mean_value_theorem) - given any two numbers $a,b$ such that $0 \le a < b \le 1$ and $f(b) \ne f(a)$, there exists a $c \in (a,b)$ such that $\frac{f(b)-f(a)}{f'(c)} = b - a$.
Comment: Hint: Use the mean value theorem repeatedly. First to get the existence of a point $\xi$ such that $f'(\xi)=1$. Then pair points $a$ and $b$ (again using the mean value theorem and the intermediate value property of derivatives) such that $1/f'(a)+1/f'(b)=2$
Answer: $f$ is continuous with $f(0) = 0$ and $f(1) = 1$. It follows from the
intermediate value theorem that there are numbers
$$
   0 = b_0 < b_1 < \dots < b_{n-1} < b_n = 1
$$
such that
$$
  f(b_j) = \frac jn \text{ for } j= 0, \ldots, n \quad .
$$
Now use the fact that $f$ is differentiable and apply the
mean value theorem
to each interval $[b_{j-1}, b_j]$, $j = 1, \ldots n$.
It follows that there are numbers $\alpha_j \in (b_{j-1}, b_j)$ such that
$$
   f'(\alpha_j) = \frac{f(b_j) - f(b_{j-1})}{b_j - b_{j-1}} = \frac 1{n(b_j - b_{j-1})} \quad .
$$
Then
$$
\sum_{j=1}^n \frac 1{f'(\alpha_j)} = n \sum_{j=1}^n (b_j - b_{j-1}) = n(b_n - b_0) = n
\quad .
$$
The $\alpha_j$ are necessarily distinct because they are in distinct
intervals $(b_{j-1}, b_j)$.


Does there exists two way embedding between two non-homeomorphic spaces?

Question: I am searching for a two way embedding between two non-homeomorphic spaces. In other words, I want two non-homeomorphic spaces such that $X$ is embedded in $Y$ and $Y$ is embedded in $X$.

Recall given two spaces $(X, \mathfrak{T})$ and $(Y, \mathfrak{J}), A
   \subseteq Y$, if there is a homeomorphism $f: X \to A$ then we call
$X$ embedded in $Y$

My initial attempt is to create a space with copies in each set like:
Let $X = (0,1) \cup \{2\}$, and $Y = (0,1)$
The two spaces are obviously not homeomorphic. Then take the identitify function $id(Y) = A \subset X$, then $Y$ is embedded in $X$. But this way $X$ is not embedded in $Y$, since we cannot map $\{2\}$ into $Y$ through a bijective function.
What modification can I make to the spaces to get the two way embedding without them being homeomorphic.
Comment: You certainly can map $(0,1) \cup \{2\}$ homeomorphically  into $(0,1)$, e.g. by $t \to t/3$.
Comment: You cannot do this with finite sets, because injection from $X$ to $Y$ and vice-versa will imply that $\#X=\#Y$.
Comment: @RobertIsrael Oh I didn't think of this...how can you see that it is a homeomorphism
Comment: Let $C$ be [middle-thirds Cantor set](https://en.wikipedia.org/wiki/Cantor_set), and let $X=C\setminus\{1\}$. $C$ is compact, and $X$ isn't, so the two spaces are not homeomorphic. The identity function embeds $X$ in $C$, and the function $f(x)=\frac{x}3$ embeds $C$ in $X$.
Comment: @ShamisenExpert: it is a restriction of a homeomorphism from $\Bbb R$ to itself.
Answer: You can consider $[0,1]$ and $\mathbb{R}$.
Comment: $\mathbb{R}$ is homeomorphic to $(-1,1)$, compose this with the canonical inclusion.


Removing the subtractive cancellation of $(a+x)^n - a^n$ as x approaches zero

Question: $$(a+x)^n - a^n = \\
e^{n\ln(a+x)}-e^{n\ln(a)} = \\
?$$
This looks simple but I'm stumped.
I've tried to solve this another way too:
$$ f(a) = a^n \\ \frac{\delta f}{\delta a} = \lim_{x\rightarrow 0}\frac{(a+x)^n-a^n}{x}  \\ \\
(a+x)^n - a^n = \frac{(a+x)^n-a^n}{x}x = \frac{\delta f}{\delta n}x=a^n\ln(a)x:x\rightarrow0\\$$
How do I finish the first one, and is the second one correct?
Answer: Hint: Apply the binomial theorem:
$$(a+x)^n=a^n+nxa^{n-1}+\cdots+nax^{n-1}+x^n.$$
Your second method is incorrect because if you take $f(x)=x^n$, then $f'(x)=nx^{n-1}$. You are taking $f(x)=a^x$.
Comment: @Segmentationfault : If you have a complete enough math library, then you can implement this as `pow(a,n)*expm1(n*log1p(x/a))` where `expm1(x)` implements $e^x-1$ and `log1p(x)` implements $\ln(1+x)$ exactly (in the bounds of the floating point format) for small $x$.
Comment: In the second one I took $f(n) = a^n$ with x being the h that is used in the formula, does this make sense?
Comment: That would work if your exponent $n$ were going to zero (since then that would be the definition of the derivative of $a^n$), but you have $x$ going to zero instead.
Comment: I see... what if I use $f(a) = a^n$ instead?
Comment: Then that is correct. You would then have $\lim_{x\to0}\big((a+x)^n-a^n\big)/x=\left(na^{n-1}\right)\lim_{x\to0}x=0$.
Comment: Nice. Could you give another hint for the first method?
Comment: Your first method isn't likely to work, since it's no easier to relate the difference $(a+x)^n-a^n$ to the difference $e^{n\ln(x+a)}-e^{n\ln(a)}$ in an elementary way. Differences of exponentials are hard to work with. The best tool here is binomial expansion since this exactly allows you to cancel all terms independent of $x$.
Comment: @LutzLehmann Nice example use of those functions!
Answer: $$S_n=(a+x)^n-a^n=\sum_{k=1}^n  \binom{n}{k}  a^{n-k} x^k=a^n\sum_{k=1}^n  \binom{n}{k}\left(\frac{x}{a}\right)^k$$ Truncate where ever you want.
If $x \ll a$, the first approximation would be
$$S_n=n  a^{n-1} x$$ but you can have better with
$$S_n=\frac{2 n x a^n}{2 a-(n-1)x}$$


How to use a Shared-Variable

Question: I want to know your opinion on how I coded my QThread.
this part of my code is for handle a PWM for LED display.
The purpose of my QThread is to work as smoothly as possible while changing a value in the QThread else i can watch on LED display a very fast break during the value change, example when i use QMutex.
this is the reason why I chose to use the SIGNAL / SLOT way
When I need to change the brightness that depends on the time or value of a resistance, I use the emit SIGNAL_FUNCTION (qint32 new_value)
Is there a risk of crashing my application using my method?
is there another way more correct to handle this kind of procedure?
I enclose my code below.
#include "luminosite.h"

LUMINOSITE::LUMINOSITE(QObject *parent, qint32 P_PIN_LUMINOSITE) :
    QThread(parent)
{
    PIN_LUMINOSITE = P_PIN_LUMINOSITE;
    VALEUR = 1;
}

void LUMINOSITE::run()
{
    qint32 TICK = 0;

    while(true)
    {
        if (TICK == 0)
        {
            digitalWrite(PIN_LUMINOSITE, LOW);
        }
        else if (TICK == VALEUR)
        {
            digitalWrite(PIN_LUMINOSITE, HIGH);
        }
        TICK++;
        if (TICK == 33)
        {
            TICK = 0;
        }
        delayMicroseconds(1);
    }
}

void LUMINOSITE::CHANGEMENT_VALEUR(qint32 P_VALEUR) // SLOT
{
    VALEUR = P_VALEUR;
}

Answer: If your question is only "SIGNAL/SLOT are they thread safe ?", read that : http://doc.qt.io/qt-5/threads-qobject.html#signals-and-slots-across-threads
It only depend on the connection type you choose.
You need to choose between Qt::QueuedConnection and Qt::BlockingQueuedConnection

How to use a Shared-Variable


How to uniformly darken colors?

Question: I display two kind of texts: one in a bright color (say, for things to do today) and another one in a darker shade (say, for things to do tomorrow). The solution I use is to assign to the relevant div containers a class day and night, each of carrying the appropriate color.
This works fine for a binary case of two hand picked colors.
I now want to also add colorful badges (say, categories) for each of these informational texts and would like to badges to reflect the "bright"/"dark" dichotomy: when something bears the class today, its badge should be in a brighter color (and darker for the class tomorrow).
I can of course create two classes per badge: cooking-today, cooking-tomorrow, important-today, important-tomorrow, etc. - each of them having a handcrafted color. This is hardly scalable and I would prefer that the "darkening" is done automatically, by the mere addition of a class (which would modify all the colors towards a darker version).
I do not know how to approach this since I believe that a color must be hardcoded (in the sense that a CSS color: definition must be specific and cannot be computed on the fly based on the existence of another class). My knowledge of HTML5/CSS/JS being minimal I would be glad to be wrong.
Comment: mix-blend-mode or background-blend-mode, via a class could help, but without any code, it is just a guess
Comment: http://stackoverflow.com/questions/1625681/dynamically-change-color-to-lighter-or-darker-by-percentage-css-javascript
Comment: Look into using a language that compiles into CSS, such as [SASS](http://sass-lang.com/).
Comment: @GCyrillus: thank you, I did not know about these proprieties - I will give them a try.
Comment: here was the idea http://codepen.io/anon/pen/ZQaOGX
Comment: @BG101: There is a great solution in the answers to the question you linked to, using `opacity`. I just gave it a try and it looks promising: https://jsfiddle.net/tk1xghp4/
Answer: OK, this is a little off-putting if you've not used Sass before but take a look at my example on Codepen. Sass is a great tool to "programmatically" adjust colors in this way using a base color and output the classes required. Lists and loops are fairly advanced concepts though.
Codepen example output as straight-up HTML/CSS

.event--cooking {
  color: yellow;
  background-color: #333;
  border: 1px solid #e6e600;
}
.event--cooking.important {
  color: #b3b300;
}
.event--cooking.tomorrow {
  color: olive;
}

.event--sewing {
  color: grey;
  background-color: #333;
  border: 1px solid #737373;
}
.event--sewing.important {
  color: #5a5a5a;
}
.event--sewing.tomorrow {
  color: #404040;
}
<button type="button" class="event--cooking today">Today</button>
<button type="button" class="event--cooking today important">Important Today</button>
<button type="button" class="event--cooking tomorrow important">Important Tomorrow</button>

How to uniformly darken colors?


How to import an addressfield with Feeds?

Question: Using Drupal 7.10 with Feeds 7.x-2.0-alpha4.  I'm trying to create a feeds importer to import node data stored in a csv file.  On the screen where you setup the mappings, my addressfield (that is part of my content type) doesn't appear in the drop down list of targets (whereas other fields of my content type do).
How can I get this to work?
I see some issues for this but being a Drupal newbie I can't really understand how to get this to work:
Mapping Address Fields using Feeds and Feeds JSONPath Parser
Mapper for Feeds importers
Do I need to switch to using the Dev release of feeds?
Answer: Following the links you posted, it looks like it's all wrapped up. Yes, try the current dev releases for Feeds.
Comment: Ah thanks that was it.  Switching to dev version of feeds (dated 2012-Jan-07) makes it work.
Comment: its always better if you use recommended version of the module


If $Y$ is a regular, then $\delta(X,Y)$ with compact-open topology is regular

Question: Suppose $Y$ is regular.
Let $f^*$ be point in $δ(X,Y)$ and $\{f:f(K)∈G\}$ open set such that
$f^*∈\{f:f(K)⊆G\}$.
Since $f^* (K)⊆G$, and ($Y$ regular) then $∀y∈f^* (K), ∃v_y$ open set such that $y∈v_y⊆(v_y ) ̅⊆G$.
Since $f^*$ is continuous, then $f^* (K)$ is compact, and the open covering $\{v_y:y∈f^* (K)\}$ must have a finite subcover. The union of this subcover $V$ will have the property
$f^* (K)⊆V⊆V ̅⊆G$
Hence $f^*∈\{f:f(K)⊆V\}$.

If $g∉\{f:f(K)∈\bar{V} \}$, then $∃x∈K∋g(x)∉\bar{V}$.Thus,
$π_x^{-1}(X| \bar{V})=\{f:f(x)∈X | \bar{V} \}$
is an open set in the "point-open" topology and
hence also in the "compact-open" topology which contains $g$ is
disjoint of the form $\{f:f(K)⊆V\}$.
Hence $Cl(\{f:f(K)⊆V\}) ⊆\{f:f(K)∈\bar{V} \}⊆\{f:f(K)∈G\}$.

Let $f^*$ be contained in a general open set $\mathcal{G}^*$ which then contains
a basis open set
$\{f:f(K_1 )⊆G_1 \}∩…∩\{f:f(K_n )⊆G_n \}⊆\mathcal{G}^*$
where $f^* (K_i )⊆G_i$ that is, a basis open set containing $f^*$. By the above
construction, the set
$V^*=\{f:f(K_1 )⊆V_1 \}∩…∩\{f:f(K_n )⊆V_n\}$
is an open set such that $f^*∈V^*⊆(V^* ) ̅⊆\mathcal{G}^*$.
I am trying to understand the above proof. I understand most of the proof what we are trying to do but I fail to understand the quoted part and how it is related to the rest of the proof. Could you please explain to me the quoted part. Another presentation of the prrof.
Comment: Define $\delta(X,Y)$?
Comment: $f(K) \in V$ makes no sense. You mean $f[K] \subseteq V$ perhaps? I use $[]$ for images of subsets, $()$ for images of points in the domain, etc.
Comment: @HennoBrandsma It's a common practice to denote the image of a subset $A$ of the domain of $f$ as $f(A)$.
Comment: @jjagmath It might be common but I find it confusing. And $\in V$ instead of $\subseteq V$ (or $\subset V$ ) is not common but just plain wrong.
Comment: @HennoBrandsma Just saying that since it's a common notation (even if you don't like it), you should have focused your comment on the wrong part: to use $\in$ instead of $\subseteq$.
Comment: I mention the wrongness of $f(K) \in V$. The $\in$ is nonsense here and the $f(K)$ should  really be $f[K]$ for clarity. We *can* have maps with sets as input parameter.
Answer: The quoted part just shows that $\{f : f[K] \subseteq \overline{V}\}$ is closed in the compact-open topology. It does this by sowing that its complement is even pointwise-open so in particular compact open. As $\{f: f[K]\subseteq V\}$ is a subset of this closed set, the closure of it is also a subset of $\{f: f[K]\subseteq \overline{V}\}$ and finally that set is itself trivially (by definition) a subset of $\{f: f[K]\subseteq G\}$ as $\overline{V}\subseteq G$. Etc.
So for the subbasic sets of the compact-open topology we can find, for each point, some subbasic open set that contains it and whose closure sits inside that first subbasic open set; it's a first step towards doing this for all open sets (as we need to do; do we reduce this to the base generated by the subbasic sets at the end).
Comment: Here is the orginal proof https://i.imgur.com/ZVVXlnj.png
Comment: @gbd You already had it in the question.
Comment: My question is about this part https://i.imgur.com/hrBrxlb.png. Is it trying to prove that $C(\{f:f(K)⊆V\}) ⊆\{f:f(K)\subseteq C(V) \}$?
Comment: @gbd a set $C$ is closed in any space iff for each $p\notin C$ we can find an open set containing $p$ and disjoint from $C$. That fact is applied there.


Fermat's Little Theorem Problem with an exponent of an exponent

Question: How do you solve this?
$$2^{5^{2017}} \bmod 11$$
I tried my own method, and I got that:
$$2^{5^{2017}} \equiv 10\pmod{11}$$
But I'm not sure it's the correct answer.
Thanks!
Comment: Please show your method and explain why you are unsure about it.
Comment: Use the linked mod order reduction method to reduce the expt $\bmod 10,\,$ using $$\large  5^{\large 1+n}\bmod  10 = 5(5^{\large n}\bmod 2) = 5(1^{\large n}\bmod 2) = 5(1)\ \ {\rm for}\,\ n\ge 0$$ by the [mod distributive law](https://math.stackexchange.com/a/2059937/242) $\ \ $
Comment: First, I applied FLT to 5^(2017) mod 11, and got that 78125 ≡ 1(mod 11). Second, I applied FLT to 2^(78125) mod 11, and finally got that the whole thing 2^(5^2017)) ≡ 1 (mod 11)
Answer: Note that since $11$ is a prime, $2^{10}\overset{11}{\equiv}1$ Hence because $5^{2017}\overset{10}{\equiv}5$, we have $2^{5^{2017}}\overset{11}{\equiv}2^5\overset{11}{\equiv}10$ and you are right!


Como Fazer dois ou mais Select categorizados na mesma consulta

Question: Preciso pegar todas as palavras com 'A' e jogar em 'PalavrasComA' e todas com 'B' e jogar PalavrasComB, e pode ter C, D E... O mais perto até agora foi isso, porem funcioana só com a primeira.
SELECT
    w1.wd as PalavrasComA,
    w2.wd as PalavrasComB
From ptbr as w1, ptbr as w2

where left (w1.wd, 1) = 'a'

and left (w2.wd, 1) = 'b';

Comment: Vai ser variável ou você sabe todas as combinações?
Comment: Vai ser variável, pois eu vou digitar palavras num campo de busca e vai retornar pelo numero de palavras que começa com cada letra.
Comment: Alguma das resposta lhe foi útil? Não esqueça de escolher uma e marcar o ✅ para que possa ser utilizada caso alguém tenha uma dúvida similar!
Answer: Se você quiser trazer todas em uma mesma query fixa pode fazer como no exemplo:
SELECT COUNT(CASE WHEN left(w.wd, 1) = 'a' THEN 1 END) AS a,
       COUNT(CASE WHEN left(w.wd, 1) = 'b' THEN 1 END) AS b,
       COUNT(CASE WHEN left(w.wd, 1) = 'c' THEN 1 END) AS c
  FROM ptbr w

Se quiser retornar as palavras:
SELECT left(w.wd, 1) AS letra,
       GROUP_CONCAT(w.wd SEPARATOR ',') AS palavras,
       COUNT(CASE WHEN left(w.wd, 1) = 'c' THEN 1 END) AS c
  FROM ptbr w
 GROUP BY left(w.wd, 1)

Se quiser separar por colunas:
SELECT GROUP_CONCAT(IF(left(w.wd, 1) = 'a', w.wd ,'') SEPARATOR ', ') AS palavrasComA,
       GROUP_CONCAT(IF(left(w.wd, 1) = 'b', w.wd ,'') SEPARATOR ', ') AS palavrasComB,
       GROUP_CONCAT(IF(left(w.wd, 1) = 'c', w.wd ,'') SEPARATOR ', ') AS palavrasComC
  FROM ptbr w

Ou se quiser apenas a primeira palavra:
SELECT MIN(IF(left(w.wd, 1) = 'a', w.wd, NULL)) AS palavrasComA,
       MIN(IF(left(w.wd, 1) = 'b', w.wd, NULL)) AS palavrasComB,
       MIN(IF(left(w.wd, 1) = 'c', w.wd, NULL)) AS palavrasComC,
  FROM ptbr w

Comment: Neste caso aqui só retornou o numero, e não as palavras.
Comment: @MarcusViniciusTavares adicionei uma segunda opção, verifique por favor
Comment: Todas as palavras com a letra 'a' na Coluna 'pA',
Comment: Todas as palavras com a letra 'b' na Coluna 'pB',
Comment: Todas as palavras estão na mesma tabela que é um dicinonario
Comment: @MarcusViniciusTavares verifique a terceira opção
Comment: A terceira é quase perfeita para meu caso. Pórem gostaria de uma palavra por linha em cada coluna.


Erro ao executar aplicação ASP.NET Core

Question: Estou começando a jornada para aprender ASP.NET Core e quando tento executar a aplicação tenho o seguinte erro:

An unhandled exception occurred while processing the request.
  SocketException: Nenhuma conexão pôde ser feita porque a máquina de
  destino as recusou ativamente
  System.Net.Http.ConnectHelper.ConnectAsync(string host, int port,
  CancellationToken cancellationToken)
HttpRequestException: Nenhuma conexão pôde ser feita porque a máquina
  de destino as recusou ativamente
  System.Net.Http.ConnectHelper.ConnectAsync(string host, int port,
  CancellationToken cancellationToken)
HttpRequestException: Failed to proxy the request to
  http://localhost:4200/, because the request to the proxy target
  failed. Check that the proxy target server is running and accepting
  requests to http://localhost:4200/.
The underlying exception message was 'Nenhuma conexão pôde ser feita
  porque a máquina de destino as recusou ativamente'.Check the
  InnerException for more details.
  Microsoft.AspNetCore.SpaServices.Extensions.Proxy.SpaProxy.PerformProxyRequest(HttpContext
  context, HttpClient httpClient, Task baseUriTask,
  CancellationToken applicationStoppingToken, bool proxy404s)

Pensei que talvez pudesse ser algum problema com CORS, porém tanto cliente como servidor estão juntos, então não deve ser esse o problema.
Comment: Esse erro pode ser causado se algum serviço estiver usando a mesma porta
Comment: Creio que não, usei NESTAT pra ver e não tem ninguém usando essa porta. O ISS gera duas opções de porta e o problema acontece nas duas.
Comment: Use p `nestat -anb` depois de iniciar o IIS para ver se está rodando e com a porta esperada. Isso pode ser porta errada, pode ser um firewall bloqueando a conexão, pode ser que não esteja realmente ativo...
Comment: Tem uma VM (vmware) rodando nessa porta, com o comando nestat -anb apareceu. Infelizmente não posso parar e nem mudar a porta desse serviço. É possível mudar a porta da aplicação?
Comment: uma pergunta boba... você está tentando acessar a aplicação partindo da mesma máquina em que ela está rodando, certo?
Answer: Comigo aconteceu a mesma coisa, passa rodar eu fiz da seguinte forma, separe os projeto e rodei cada uma em uma janela do Visual Studio 2019 diferente e funcionou pois cada um utiliza uma porta diferente. Eu não consegui achar outra forma melhor, e quando os dois projetos estavam na mesma Soluction eu não consegui configurar o IIS Express para rodar cada um em uma porta diferente.

Erro ao executar aplicação ASP.NET Core


Suggestion on how to play triplets?

Question:
History: I am learning electronic keyboard(kinda piano) from past 5-6 years and now I am learning on my own.

I have tried playing triplets(crotchet) on 4/4 but am unsure how to practice them or how to get them correct.I know they are split like 3 beats in place of a crotchet thus making 3x4=12 beats in a measure, whereas the backing beats(accompaniment) plays a 4/4 in a 4x4=16 fashion.Also I have tried playing first with metronome; then only with the backing beat but I kinda mix the triplets slowly into 1-e&-aor1e-&-aor 1-e-&a because I get some kind of intuition to fix the triplets to start on an emphasis(beat).Any help?
Answer: The triplets do start on a beat. All of them. And you are right that there are 12 of them in a measure of 4/4. However, make sure your math is correct. A triplet is:
ONE - 2 - 3 - TWO - 2 - 3 - THREE - 2 - 3 - FOUR - 2 - 3.
Each of the capital letters represents a beat of four. I suggest you do not try counting with "1-e-+-a". Instead, simply count "one-two-three". I usually would count the beat with an emphasis as above. "ONE-two-three-TWO-two-three" etc.
If this is difficult for you, you should be able to find a metronome that can help you get a firmer grasp of the grid. Or, you can set a metronome to a FAST pace, accent every 3 beats. Then consider every three clicks to be one beat.
If this is still difficult, you're probably just not hearing enough use of the triplet in music you know. Try listening to music with lots of triplets. Classical music has plenty of examples. In modern music, the eighth-note triplet is probably used most often in a blues context.
Keep practicing. What was frustrating and disappointing one day is amazingly easy the next, and I think learning beat divisions are a perfect example. Once you've learned it, you won't forget it.
One more thing: check to see if the technique you are using fits your goals. It's perfectly natural that you should use three fingers to play a triplet. Try with one hand, and then both hands playing the same triplet in unison. In addition, chord arpeggios going up and down can be a great way to learn the triplet because they tend to fall into a pattern of 6, which can be thought of as two triplets:
Answer: A set of triplets is three notes, equally spaced in this case, over one beat. Thus, 12 in a bar full of triplets.(4/4, with quaver triplets). Try counting 1,2,3,4 with 'triplet' counted evenly in between. As ONE-trip-let,TWO-trip-let,THREE-trip-let, FOUR-trip-let.The count will coincide with the main beats of the bar, but the 'trip-let' will not match to quavers or semis in each beat. If you're talking crotchet triplets, there will be 6 of these in a 4/4 bar, the first and 4th coinciding with beats one and three respectively. They are slower than quavers, quicker than crotchets.
Crotchet=1 beat=quarter note. Quaver=1/2 beat=eighth note. Semi=1/4 beat=sixteenth.
If your metronome is clever enough, and you play slowly, which gives more thinking time, set it, for example, at 180 bpm, for a song at 60 bpm. The clicks will be spot on triplets for each beat. Then you can keep to them.If it has a ping as well, set it for 3 time for even more support !
Answer: It may help to start by thinking in 12/8, then make the switch to 4/4 with triplets.
Set a metronome to a quite fast tempo, and count a 12 beat bar in threes: 123123123123
Once you feel it, you feel it. Try playing piano in that rhythm.
Then make the switch to thinking in 4/4, with each beat being 3 metronome ticks. One-and-a two-and-a three-and-a four-and-a. Play the same piano patterns over this.
Slow the metronome down to a third of the tempo, but keep counting at the same tempo: now you are feeling the triplets.
Some metronomes and most drum machines have 12/8 patterns that will help with this.

It should be noted that 4/4 does not mean 4 * 4 = 16 ticks to a bar. It means 4 beats, each one a quarter-note long. So do not think that whenever you see 4/4 it would be appropriate to set a metronome to tick 16 times a bar.
To play a triplet pattern over a 16th-note beat is quite advanced musicianship. It doesn't happen often in Western classical music, or rock and pop. It happens sometimes in jazz, African music, and dance music inspired by these. Don't worry about it yet.
To play a triplet pattern while simultaneously playing a 16th-note pattern (perhaps with the other hand) is even more advanced. I'm certain there are lots of professional musicians who can't do it.
Answer: Just to clarify your problem: you are struggling to do 16ths of a bar on the left hand whilst doing 12ths on the right hand?
Let's break this down to one beat: four notes on the left hand, three on the right. This naturally means we should split our beat into 12 sections:
RH: o---o---o---
LH: o--o--o--o--

Start off by setting your metronome to just tick (i.e. no tocks every 4th beat) and playing the above on just one note in each hand (like C3 and C5).
If you prefer vocal counting then this would be, with emphasis on where the triplets hit:
ONE  -and  -a    -two  -AND  -a    -three-and  -A    -four -and  -a    -
Once you have perfected that move on to doing a major chord in each (in the right hand C3 E3 G3 C3 E3 G3 and C5 E5 G5 C6 C5 E5 G5 C6 in the left.
From here you should be able to do more complicated things as per the piece of music. Best of luck!

Suggestion on how to play triplets?


Derive the indefinite integral of a Heaviside Function

Question: How can I prove that
$$\int H(x-a)dx=(x-a)H(x-a)+constant$$
where $H(x-a)$ represents a jumped Heaviside function
Thanks in advanced.
Comment: Can you write what you have tried so far ?
Answer: The Heaviside function is a piecewise step: $\mathcal H(x-a)=\begin{cases}1 &:& x-a\geqslant 0\\ 0 & :& x-a<0\end{cases}$
So consider the two cases, $x\geqslant a$ and $x<a$ for the directed integral $$\int \mathcal H(x-a)\mathrm d x = \mathscr c+ \begin{cases}\phantom+\int_a^x \mathcal H(s-a)\,\mathrm d s &:& x-a\geqslant 0\\ -\int_x^a \mathcal H(s-a)\,\mathrm d s & :& x-a<0\end{cases}$$
Answer: Consider Ramp function
\begin{align}
R(x)
&= \dfrac{x+|x|}{2} \\
&= \begin{cases}x&x\geq0,\\0&x<0\end{cases} \\
&= x{\bf H}(x)
\end{align}
It's easy to see for $x\neq a$, $\dfrac{d}{dx}R(x-a)={\bf H}(x-a)$ then
$$\int{\bf H}(x-a)dx=R(x-a)+C=(x-a){\bf H}(x-a)+C$$
Comment: Thanks! I can understand more clearly from this answer
Comment: Your welcome.!.
Answer: The function $H$ is piecewise constant, so that it is the derivative of a piecewise linear function. Furthermore, the slopes are $0$ then $1$.
We have
$$I(x):=\begin{cases}x\le a\to C_-,\\x\ge a\to C_++x.\end{cases}$$
To ensure continuity at $a$, $C_-=C_++a$ and
$$I(x):=\begin{cases}x\le a\to C,\\x\ge a\to C+x-a.\end{cases}$$
This is equivalent to
$$I(x)=C+(x-a)H(x-a).$$


ObservableCollection não está populando

Question: Quero popular um ObservableCollection para posteriormente exibir quando a tela for carregada. Dentro do meu ViewModel estou definindo os dados para teste, porém quando vou fazer o print não tem conteúdo.
Eu executo NoticeShow() quando a página / ContentPage é carregado.
    protected override void OnAppearing()
    {
        base.OnAppearing();

        ChannelViewModel ViewModel = new ChannelViewModel();
        ViewModel.NoticeShow();
    }

Dentro do meu ViewModel
    public class Notice
    {
        public string NoticeMessage { get; set; }
    }

    private ObservableCollection<Notice> Notices;

    public void NoticeShow()
    {
        Notices = new ObservableCollection<Notice>()
        {
            new Notice { NoticeMessage = "Teste de mensagem 1" },
            new Notice { NoticeMessage = "Teste de mensagem 2" },
            new Notice { NoticeMessage = "Teste de mensagem 3" }
        };

        Console.WriteLine("Console log -> "+Notices);
    }

Retorno do Console writeline
Console log -> System.Collections.ObjectModel.ObservableCollection`1[iSequi.ViewModels.ChannelViewModel+Notice]

Answer: Olá @RRV
No construtor da sua View você deve setar o BindingContext para a sua ViewModel:
public partial class MinhaView{
   public MinhaView(){
     ChannelViewModel ViewModel = new ChannelViewModel();
     BindingContext = ViewModel;
   }
}

Em seguida no evento Appering, você pode utilizar seu código:
protected override void OnAppearing()
{
    base.OnAppearing();
    ViewModel.NoticeShow();
}

Em seguida você deve realizar o binding do Notices na sua View, apenas lembrando de definir a propriedade Notices presente na ViewModel como pública, ao invés de privado:
public ObservableCollection<Notice> Notices;

Comment: Olá Vinicius Dutra.. Adicionei  BindingContext direto no OnAppearing,as não teve efeito.
       protected override void OnAppearing()
        {
            base.OnAppearing();

            ChannelViewModel ViewModel = new ChannelViewModel();
            BindingContext = ViewModel;
            ViewModel.NoticeShow();
        }
Comment: Você definiu a propriedade `public ObservableCollection Notices; ` como publica e realizou o bindind na view ` ... ` segue link com exemplo completo [https://docs.microsoft.com/pt-br/xamarin/xamarin-forms/user-interface/listview/customizing-cell-appearance#custom-cells](https://docs.microsoft.com/pt-br/xamarin/xamarin-forms/user-interface/listview/customizing-cell-appearance#custom-cells)

ObservableCollection não está populando


python - type error

Question: this is my code:
def get_num():
    number = int(raw_input(" ")),
    print "|"
    return number
list_of_letter = ['a',   'b',   'c',    'd',    'e',    'f',    'g',    'h',    'i',    'j',    'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' 'x' 'y' 'z']
num = -1
print "welcome to the sudoko maker!!!"
print "I will start asking you information."
for lines in range (9):
    for ask in range(9):
        if num == 25:
             num = 0
        num = num + 1
        print list_of_letter [num],
    print

and when I run it python writes:
IndexError: list index out of range
why????
Comment: @Guandalino: Hey, don't be so quick to judge. Maybe Python 3.4 changes the default error description for `IndexError` from `'list index out of range'` to `'list index out of range why???'`. :)
Comment: @Roey, mine is not an answer but still can be helpful: for this kind of issues consider to use a Python module called [pdb](http://docs.python.org/2/library/pdb.html). It's the debugger (basically you'll use `pdb.set_trace()` and some keys like l, n, c, s, and so on). It's a very didactic, self aid and not too complex tool. If you still have problems add details to your question sharing your discoveries. Maybe some downvote will disappear, too.
Comment: don't waste question marks uselessly!
Comment: This should have been closed as a typo.
Answer: You are missing a couple of commas from the list_of_letter list; there are no commas starting from element 'k' onwards. As a result, list_of_letter does not have 25 items, but only 11.
Comment: Yes, this is the problem, but you still need to explain _why_ he's getting this error: he has an 11th "letter" `'klmnopqrstuvwxyz'` and no more after that, because adjacent strings are concatenated.
Comment: No need to write all those characters. Just use `string.ascii_lowercase`.
Comment: +1 Matthias. And if you really want a `list` (which you probably don't, because `ascii_lowercase[3]` is the same `'d'` as `list_of_letters[3]`), you can just use `list(string.ascii_lowercase)`.
Answer: In addition to Tamas answer, it would be easier to read and function the same if you made list_of_letter a single string (which can be indexed the same way):
list_of_letter = 'abcdefghijklmnopqrstuvwxyz'

Comment: This is the same thing as `string.ascii_lowercase`, but easier to get wrong.

python - type error


Solving a second order differential equation using complex numbers

Question: Can i have help solving this second degree differential equation?
$y''+2\lambda y'+ \omega_0^2 y=-N/I$
Where $ y''(\inf)=y'(\inf)=0 $
According to the paper the solution is
$$ a(t)=2a_0 e^{-\lambda t}(\cos(\omega_n t)+\lambda/\omega_n \sin(\omega_n t))-a_0 $$
where $ \omega_n^2=\omega_0^2-\lambda^2$ and $a_0=N/(I \omega_0^2 )$
The equations is about a Oscillation
where $y''(t)->0$ and $y'(t)->0$ for $t-> infinity$
This solves the partial part of the equation by
$y''+2\lambda y'+ \omega_0^2 y=-N/I$
$0+2\lambda 0+ \omega_0^2 y=-N/I$
$ y=-N/(\omega_0^2I)$
Therefore a partial solution is
$f(x)_{particial}=-N/(\omega_0^2I)$
Not quite sure if this totally ruins the equation
Comment: Hint: make an *ansatz* $y(t)=e^{Rt}$ for $R \in \mathbb{C}$, and later on use the supersition principle.
Comment: Are you sure about the initial consitions (as they are typed) ?
Answer: $$
y'' +2\lambda y' + \omega^2_0 y = -N/I
$$
first lets change of variables to tidy up the equation, namely $v = y+\frac{N}{I\omega^2_0}$
$$
v'' + 2\lambda v' +\omega^2_0v = 0
$$
then use the assumption that the solution is of the form
$$
v = u(t)\mathrm{e}^{rt}
$$
(see comment section above)
then we have
$$
u''\mathrm{e}^{rt} +2ru'\mathrm{e}^{rt} +r^2u\mathrm{e}^{rt} + 2\lambda r u\mathrm{e}^{rt} + 2\lambda u'\mathrm{e}^{rt} + \omega^2_0 u\mathrm{e}^{rt} = 0
$$
thus we get
$$
u'' + 2(r + \lambda)u' + \left(r^2 + 2\lambda r + \omega^2_0\right)u = 0
$$
lets try getting rid of the first derivative by setting $r = -\lambda$ (tip for future try using the parameters to remove terms that may not be ideal)
this results in
$$
u'' + \left(\lambda^2 - 2\lambda^2 + \omega^2_0\right)u = u''  + \left(\omega^2_0 - \lambda^2\right)u  = 0
$$
solutions have the form
$$
u(t) = A\sin\left(\sqrt{\omega^2_0 - \lambda^2}t\right) + B\cos\left(\sqrt{\omega^2_0 - \lambda^2}t\right)
$$
therefore we have
$$
y(t) = \mathrm{e}^{-\lambda t}\left[ A\sin\left(\sqrt{\omega^2_0 - \lambda^2}t\right) + B\cos\left(\sqrt{\omega^2_0 - \lambda^2}t\right)\right]-\frac{N}{I\omega^2_0}
$$
usually you define initial conditions instead of the long-term solution at $t\rightarrow \infty$ since you will $\textbf{not}$ satisfy that for any $A,B$. So the trick is that if we write in the form you have in the paper
$$
y(t) = B\mathrm{e}^{-\lambda t}\left[\cos\left(\sqrt{\omega^2_0 - \lambda^2}t\right) + \frac{A}{B}\sin\left(\sqrt{\omega^2_0 - \lambda^2}t\right)\right]-\frac{N}{I\omega^2_0}
$$
$$
B = 2\frac{N}{I\omega^2_0},\\
A = \frac{\lambda}{\sqrt{\omega^2_0 - \lambda^2}}\frac{I\omega^2_0}{2N}
$$
$\textbf{Edit:}$
Since we now have $y'(0) = y(0) = 0$ we can compute the constants again
$$
y(0) = B -\frac{N}{I\omega^2_0} = 0
$$
thus
$$
B = \frac{N}{I\omega^2_0}
$$
using
$$
y' = -\lambda \left(y+\frac{N}{I\omega^2_0}\right) +\mathrm{e}^{-\lambda t}\left[ A\sqrt{\omega^2_0 - \lambda^2}\cos\left(\sqrt{\omega^2_0 - \lambda^2}t\right) -B\sqrt{\omega^2_0 - \lambda^2}\sin\left(\sqrt{\omega^2_0 - \lambda^2}t\right)\right]
$$
setting $t=0$
$$
\begin{align}
y'(0) &=& -\lambda \left(y(0)+\frac{N}{I\omega^2_0}\right)+A\sqrt{\omega^2_0 - \lambda^2}\\
&=& -\lambda\frac{N}{I\omega^2_0} +A\sqrt{\omega^2_0 - \lambda^2} = 0
\end{align}
$$
resulting in
$$
A = \frac{\lambda\frac{N}{I\omega^2_0} }{\sqrt{\omega^2_0 - \lambda^2} }
$$
A simple check of your initial equation/solution..applying your initial conditions we find
$$
y(0) = 2a_0 - a_0 = a_0 \neq 0
$$
so i think your original solution is wrong, or the initial conditions are..but you checked them already.
Comment: Talked to the lector who wrote the paper, y(0) is not 0, but a_0
With this knowledge i ran throuth the calculations and got the same answer as in the paper

Thanks a lot for your help, I´m myself started learning about second degree differential equations a few weeks ago, and i must say that your walkthrough and troubbleshooting helped a lot understanding the problem:)
Comment: I can follow the first haft of the answer, but how do you get from equation (4) (labeled from botton) to end result? And is there any mathematical way to define A and B, without just making it "add up" to the paper?

@Chinny84
Comment: I compared the general solution with the case with initial conditions (in the paper). The A and B was the result of the comparison. If I had some time..I could back out the solutions based on a pair of combinations of the following $y''(0), y'(0)$ and $y(0)$. But to be honest Reread that bit of the paper to try and see explicitly the defining ng of the constants..post a link also of the paper.
Comment: I have gone through the paper, and sure enough, its also stated that y'(0) and y(0)=0. And with that in mind i tried to calculate A and B

If you start with y(0)=0 you get
y(0)=0=B-N/(I*w^2) -> B=N/(I*w^2) which is a 2 short from your calculation? i also tried entering the equationen into a CAS-solver to check, and it also spits out that answer?
Answer: I am a high schooler and I don't know much about it, but shouldn't the solution look like this:
A general equation looks like this:
$$\ddot{x} + a \dot{x} + b x + c = 0$$
Let's substitute $y=x+\frac{c}{b}$ into the differential equation to get rid of $c$ term:
$$\ddot{y} + a \dot{y} + b \left(y - \frac{c}{b}\right) + c = 0$$
$$\ddot{y} + a \dot{y} + b y = 0$$
This is a second-order linear homogeneous differential equation with constant coefficients. We can assume a solution of the form $y=Ae^{rt + \phi}$, where $r$ is a constant. Substituting this into the equation, we get:
$$r^2 Ae^{rt + \phi} + r Ae^{rt + \phi} + b Ae^{rt + \phi} = 0$$
$$r^2 + a r + b = 0$$
Thus
$$r_{1,2} = \frac{-a \pm \sqrt{a^2 - 4b}}{2}$$
The general solution of the differential equation is a linear combination of the two solutions:
$$y(t) = A_1 e^{r_1 t + \phi} + A_2 e^{r_2 t + \phi}$$
where $A_1$, $A_2$ and $\phi$ are constants determined by the initial conditions.
Substituting $y=x+\frac{c}{b}$, we get:
$$x(t) = \left(A_1 e^{r_1 t + \phi} + A_2 e^{r_2 t + \phi}\right) - \frac{c}{b}$$
This is the general solution of the given differential equation.


A function that is one to one but not onto $\mathbb{Z}$ to $\mathbb{N}$

Question: Can someone please tell me if I can have a function that is one to one but not onto $\mathbb{Z}$ to $\mathbb{N}$?
I tried these formulas
\begin{align*}
F(x) & = x^2+1\\
F(x) & = x^2 -1
\end{align*}
But it always gives me a function that is onto but not not one to one, and I don't want it to be like this.
Comment: Try something that is not continuous. You can always take a bijection from $\mathbb Z$ to $\mathbb N$ and make it miss $1$ by pushing all the values up.
Comment: How can i do it ??
Comment: You're close. How about something like $F(x)=x^2+\mathop{sign}(x)$?
Comment: will sin or cos or any works in Discrete Mathematics? Because i am new with it .
Comment: Sure, you just have to make sure your answer comes out in the right set, but otherwise go for it. Things like $\cos(\pi n)$ can be a nice shortcut for the equivalent statement written with powers of $(-1)$.
Comment: "not onto $Z$ to $N$" ? I think you mean  from $Z$ into, but not onto $N$. For example $f(z)=2 |z|+17$ if $z\leq 0$ and $f(z)=2 z$ if $z>0$.
Answer: If $k\ge 0$, let $f(k)=2^k$. If $k\lt 0$, let $f(k)=3^{-k}$.
Answer: f(n) = 3|n| + sign(n), where sign(n) is -1, 0, or 1, according to whether n is negative, zero, or positive. All the positive multiples of 3 will have no preimage.
Answer: Take any bijection from $\mathbb Z \rightarrow \mathbb N$, and then double the value of the images for every point. It'll still be injective because unique points will have unique images, even after the doubling, but now it misses the odd naturals.
Comment: Or start with any injection and add $1$ to each image.
Answer: How about
$f(n) =
\begin{cases}
  n+3,  & \text{if } n \in \{-2, -1, 0, 1, 2\}\\
  n^2+1, & \text{if } n \ge 3 \\
  n^2-1, & \text{if } n \le -3 \\
\end{cases}$
$f(n) = (4+sgn(n))^{|n|}$
$f(n) =
\begin{cases}
  2n+2,  & \text{if } n\ge 0\\
  1-2n, & \text{if } n \lt 0 \\
\end{cases}$


How can I configure qmail to send using a different IP per domain?

Question: I would like to configure qmail to send email for certain domains using specific IPs for the outbound traffic.  All other domains could continue to use the system's primary IP as usual.  Is this possible?  If so, how would I configure it?
Answer: If your qmail include the bindroutes patch, and if you know the IP address if the MX you want to connect to, then you could do it, using /var/qmail/control/bindroutes (220.127.116.11 is the IP of the distant MX, 220.127.116.11 is the IP you want to bind, 126.96.36.199 is your "normal" IP):
22.214.171.124:220.127.116.11
:220.127.116.11

Answer: From my experience and what I searched in the manual, this doesn't seem possible with the unpatched version of qmail.
But, if you use patches from this page (which I use and would recommend anyway because it supports so much sane and interesting features), you can search in that page for the string 'newbind.patch'. The second match will probably give you a good solution to your problem. The main difference from the bindroutes patch is that you can configure IP address binding according to the recipent domain name instead of its IP address (which I find more convenient).
Anyway, I find that the site http://qmail.jms1.net is really useful. It had become my main source of documentation/script/patch in regard to qmail. It definitely deserve a not-so-short visit.


Matrix Exponential using the Cayley-Hamilton theorem

Question: For the matrix $$P=\left( \begin{matrix} 0&1&0 \\ 0&0&1 \\ 0&1&0 \end{matrix} \right)$$ how do you find $e^{Pt}$ using the Cayley-Hamilton theorem?
I have found it by diagonalising $P$, but the question states to use the Cayley-Hamilton theorem.
Comment: You don't need to use the Cayley-Hamilton theorem, you just need some annihilating polynomial to of the matrix to rewrite the power series. Since you are going to need the monomials $I,P,P^2$ anyway, computing the minimal polynomial directly can actually save you the (admittedly not very hard) work of computing the characteristic polynomial.
Answer: If you calculate the characteristic polynomial $\chi_A(x)=x^3-x$, you know from Cayley-Hamilton theorem that $P^3-P=0$, i.e. $P^3=P$.
This implies that $P=P^3=P^5=\dots$ and $P^2=P^4=P^6=\dots$. Hence
$$
\begin{align}
e^{Pt}
&= I+Pt + \frac{P^2t^2}2 + \frac{P^3t^3}{3!} + \dots = \\
&= I + P\left(t+\frac{t^3}{3!}+\frac{t^5}{5!}+\dots\right) + P^2\left(\frac{t^2}2+\frac{t^4}{4!}+\frac{t^6}{6!}+\dots\right) = \\
&= I+ P \frac{e^t-e^{-t}}2 + P^2 \left(\frac{e^t+e^{-t}}2-1\right) = \\
&= I+ P\sinh t + P^2(\cosh t-1)
\end{align}
$$
Using
$P=\begin{pmatrix}0&1&0\\0&0&1\\0&1&0\end{pmatrix}$
and
$P^2=\begin{pmatrix}0&0&1\\0&1&0\\0&0&1\end{pmatrix}$
I get
$$e^{Pt}=
\begin{pmatrix}
1&\sinh t&\cosh t-1\\
0&\cosh t&\sinh t\\
0&\sinh t&\cosh t
\end{pmatrix}.$$
If I did not miss something, this seems to be the same result as WolframAlpha returns. (Up to some algebraic manipulation.)
Comment: Thank you for your help! how did you get from the line P(t+t^3/3!+t^5/5!+.... to the following line?
Comment: It is more or less standard trick: In one of the expressions I want to get rid of all terms in Taylor series of $e^x$ with odd exponent, in another one I want to cancel out the terms with even exponents. (Or you may simply notice that they are Taylor series of [hyperbolic functions](http://en.wikipedia.org/wiki/Hyperbolic_function), if you remember those. They are very similar to Taylor series for $\sin x$ and $\cos x$, but there are different signs.)
Comment: Nice answer!!$\;$


multiplying 2 integers of the same value by 300 yields different results

Question: I am trying to figure out why a difference of 283 happens when I decide to multiply rather than divide.
Here is some Python code from my terminal. As you can see both variables are integers, but depending on whether I divide one to get to the other or multiply the other changes the value slightly.
>>> type(times), times
(<type 'int'>, 1512296383)
>>> type(payout), payout
(<type 'int'>, 5040987)
>>> [times / 300 - payout, times - payout * 300]
[0, 283]
>>> [times / 300, payout, times, payout * 300]
[5040987, 5040987, 1512296383, 1512296100]

Comment: @SilvioMayolo Not correct: `//` is explicit integer division and behaves the same in Python 2 and 3; `/` is integer or floating point division in Python 2, depending on the argument types, and is explicit floating point division in Python 3.
Comment: Possible duplicate of [Python division](https://stackoverflow.com/questions/2958684/python-division)
Comment: What did you expect to happen?
Comment: Also related: https://stackoverflow.com/questions/183853/in-python-2-what-is-the-difference-between-and-when-used-for-division, https://stackoverflow.com/questions/1267869/how-can-i-force-division-to-be-floating-point-division-keeps-rounding-down-to-0
Answer: You are performing integer division, which discards everything after the decimal point. Since times isn't divisible by 300, you'll get a truncated result. Here's a simpler way to see it:
>>> 1512296383 / 300 * 300
1512296100

Answer: Your issue is that in Python 2.x, integer division does not return an exact floating point result. Casting one value to a float shows that the division does not exactly equal 300:
>>> float(1512296383)/5040987
300.0000561397996

Therefore when you do 1512296383/5040987, you'll get the integer 300, which will introduce a small error.
Comment: `1512296383.` or `5040987.`is enough.
Comment: @Kanak True, I did an explicit cast since I figured it'd be more helpful for the example in the question, since they'd need to do something like `float(times[0])`.


If a function $f(x,y,z) = F(r)$ depends on distance from the origin, $r = \|\vec{r}\| = \sqrt{x^2 + y^2 + z^2}$, then $\nabla f = F'(r)e_{\vec{r}}$

Question: How do I prove the above? I've tried this:
Given $\vec{r} = \langle x, y, z \rangle \quad e_{\vec{r}} = \frac{\vec{r}}{\|\vec{r}\|}\quad r = \|r\| = \sqrt{x^2 + y^2 + z^2}$
Since $F(r) = f(x,y,z)$, then
$$F'(r)e_{\vec{r}} = \frac{\partial f(x,y,z)}{\partial r}e_{\vec{r}} =  \left(\frac{\partial f}{\partial x}  \frac{\partial x}{\partial r} + \frac{\partial f}{\partial y} \frac{\partial y}{\partial r} + \frac{\partial f}{\partial z} \frac{\partial z}{\partial r} \right)
\frac{\vec{r}}{\|\vec{r}\|}
=\nabla f \cdot \langle \frac{\partial x}{\partial r},\frac{\partial y}{\partial r}, \frac{\partial z}{\partial r} \rangle \frac{\vec{r}}{\|\vec{r}\|} = \nabla f$$
This is not exactly correct because I don't know how $\frac{\partial x}{\partial r}\frac{x}{r}$ reduces to 1 or if it does.
Comment: I'd recommend starting from the other "direction". I.e. calculate $\nabla f$. Note that, for example, $\frac{\partial f}{\partial x} = \frac{\partial f}{\partial r} \frac{\partial r}{\partial x} $... See Chilango's post below (which was typed as I typed this comment).
Answer: Start with the definition and then use the chain rule on each term:
$$\nabla f=\frac{\partial f}{\partial x}\vec i+\frac{\partial f}{\partial y}\vec j+\frac{\partial f}{\partial z}\vec k=\frac{\partial f}{\partial r}\frac{\partial r}{\partial x}\vec i+\frac{\partial f}{\partial r}\frac{\partial r}{\partial y}\vec j+\frac{\partial f}{\partial r}\frac{\partial r}{\partial z}\vec k=\frac{\partial f}{\partial r}\left ( \frac{x}{r}\vec i+\frac{y}{r}\vec j+\frac{z}{r}\vec k \right )=\frac{\partial f}{\partial r}\vec e_r$$
Answer: $$
\nabla F
=
\begin{pmatrix}
\frac{\partial F}{\partial x}\\
\frac{\partial F}{\partial y}\\
\frac{\partial F}{\partial z}
\end{pmatrix}.
$$
By the chain rule, $\frac{\partial F}{\partial x}=F'(r)\frac{\partial r}{\partial x}=F'(r)\cdot \frac{x}{r}$. Therefore,
$$
\nabla F
=
\frac{F'(r)}{r}
\begin{pmatrix}
x\\
y\\
z
\end{pmatrix}=\frac{F'(r)}{r}\mathbf{r}=F'(r)\mathbf{e}_r
$$


What connection is there between SpongeBob SquarePants and the NFL?

Question: I havent played Madden for years, but I picked up last year's Madden and saw they had a Nickelodeon field with Spongebob characters.

I ask this respectfully - what does Spongebob have to do with Madden or the NFL?
Comment: I think it's okay; the poster is asking what the connection between SpongeBob and the NFL is, which is a sports entertainment question.
Comment: I'm voting to close this question because it is a video game question, not a sports question.
Answer: Nickelodeon has, since 2021, occasionally broadcast NFL games. During those broadcasts, they often feature SpongeBob SquarePants, possibly the most well-known Nickelodeon original character.
The stadium was added to Madden to coincide with the first Nickelodeon game, a wildcard playoff between Chicago and New Orleans in January 2021.  Although not public, it is reasonable to guess this might have been a paid tie-in.
Comment: To add: CBS is a long-standing "broadcast partner" of the NFL. ViacomCBS owns Nickelodeon, home of SpongeBob.
Comment: Wow... I would have never guessed that Nickelodeon broadcast NFL games (I'm assuming that was in the USA).  I think most professional sports could be improved with the gratuitous addition of brightly coloured slime...


Addition fails in controller

Question: I got a loop in a create-action in a rails controller like this:
def create
  @day = current_user.days.build(day_params)
  id = @day.tasks.first.id
  begin
    id = id + 1
  end until id = @day.tasks.id
  @day.save
  ...
end

when the code reaches id = id + 1 it fails and I get the error:

undefined method `+' for nil:NilClass

I have no idea why this should not work...
Could there be an issue because it is a nested model?
Answer: It's because id isn't previously declared.
Do this:
id = 0

begin
  id = id + 1
end until ...

Once you assign an integer to a variable (in this case, id) it becomes an Integer type, which then allows you to increment in that manner
Update
After seeing your edits to your question, the problem is because id is still blank.
The id of a record does not get assigned until you actually create the record. Using build will not generate an ID because it has not yet been added to the database.
Comment: of course i declared it previously, sry I forgot that in my post
Comment: @Max you're saying that in spite of having declared it, you're still seeing this `nil:NilClass` problem?
Comment: @MarsAtomic yes, thats the case and I doublecheckt that the declaration is working
Comment: @Max OK, then we need to see the actual code. Where and how did you declare ID?
Comment: @Max I've updated my answer to reflect your updated question

Addition fails in controller


NHibernate entity mapping: Customer with latest order

Question: I am developing a MVC3 application in c# and I am using NHibernate for the ORM part. I need to generate a list of all registered customers and their latest order. On the application side, this would require to go through all customers and retrieve all their orders to extract the latest one.
Unneeded overhead, isn't it?
On the database, I could create a view and model the entity accordingly, but then I cannot create new customers due to the fact that populating a view is not possible. So, any ideas or best practices how you solved such issues? Here's a sql query that would serve the needed information:
SELECT c.id, c.name, c.description, m.ordernumber AS latest_order, m.unixtime, m.id AS latest_order_id
FROM dbo.customer c
LEFT JOIN dbo.mailorder m ON c.id = m.customer_id
WHERE m.unixtime = (SELECT MAX(unixtime) FROM dbo.mailorder)

Any help is very much appreciated!
Best regards,
Martin
Answer: You can use formula to get last order for customer, something like this:
<property name="LatestOrder" formula="(SELECT MAX(dbo.mailorder.unixtime) FROM dbo.mailorder where dbo.mailorder.customer_id = ID)" />

Comment: Works like a charm. Great tip, thanks. Never used formular before but seems quite useful. Do you have an idea about it's performance?
Comment: @Martin Horvath No problem just ask. I think performance bit slower (for a few milliseconds :) )


How do I measure distance in this problem?

Question: I am posting here again after a long time. I have this distance measuring problem that I have been trying to solve. Please help me out here. TIA.
***A bullet covers distance of 1540 feet per second. Given the measurement, a person fired a shot and heard the sound of hitting the destination point after 3 seconds of firing. Speed of sound is 1100 feet per second.
What is the distance of destination point here?***
Waiting for your kind replies.
Regards
Imran
Comment: You have to visualize what happens: First, the **bullet** travels to the destination (you have to calculate how long this takes) and then the **sound** of the impact travels back to the shooter (again, you have to calculate how long this takes). The total time is known, and you have to solve for the distance. So you will have the sum of two terms, and the sum is equal to 3 seconds.
Comment: I changed the tag to correctly reflect the category to which the problem belongs. (The tag 'measure-theory' is related to abstract theory of integration.) Hope this helps. @SujitBhattacharyya, Sorry, I edited the tag and accidentally rendered your comment no longer relevant. Hope you don't mind this.
Comment: Sorry about tags. I am new here and not so familiar with tags.
Comment: @Imran you are welcome. I removed my comment.
Answer: Let $d$ denote such distance. Then the total time for the bullet to reach the destination and for the person to hear the sound of hitting is simply
$$\frac{d}{1540}+\frac{d}{1100}.$$
By condition, this should equal $3$. The answer will follow after your solving the equation about $d$:
$$\frac{d}{1540}+\frac{d}{1100}=3.$$
Comment: Thank you very much. The equation worked. Answer is 1925 feet. One more thing, how much time should it take to solve? It appeared in our BCS exam where I get 30 seconds for this kind of problems.
Comment: @Md. Imran Hossain  I thinks it costs you less than 20 seconds with a calculator.
Comment: Sadly, we are not allowed to take calculators in the exam.


Setting up and enabling Google CSE

Question: Is it possible to fully set up and enable Google CSE module before a website is launched? Or would I have to wait until it's launched and submitted to Google's search engine?
Answer: You can set it up now but it would be much use until your content is fully indexed by Google
Answer: Sort of doable question to answer. The answer is specif to the site that you are building. I would set up Google CSE module when I think my site has adequate contents and almost ready to go live.

Setting up and enabling Google CSE


It is possible to GROUP BY multiple columns separately and aggregate each one of them by other column with django ORM?

Question: I know how to GROUP BY and aggregate:
>>> from expenses.models import Expense
>>> from django.db.models import Sum
>>> qs = Expense.objects.order_by().values("is_fixed").annotate(is_fixed_total=Sum("price"))
>>> qs
<ExpenseQueryset [{'is_fixed': False, 'is_fixed_total': Decimal('1121.74000000000')}, {'is_fixed': True, 'is_fixed_total': Decimal('813.880000000000')}]>

However, If I want to do the same for other two columns, it only returns the last:
>>> qs = (
...     Expense.objects.order_by()
...     .values("is_fixed")
...     .annotate(is_fixed_total=Sum("price"))
...     .values("source")
...     .annotate(source_total=Sum("price"))
...     .values("category")
...     .annotate(category_total=Sum("price"))
... )
>>> qs
<ExpenseQueryset [{'category': 'FOOD', 'category_total': Decimal('33.9000000000000')}, {'category': 'GIFT', 'category_total': Decimal('628')}, {'category': 'HOUSE', 'category_total': Decimal('813.880000000000')}, {'category': 'OTHER', 'category_total': Decimal('307')}, {'category': 'RECREATION', 'category_total': Decimal('100')}, {'category': 'SUPERMARKET', 'category_total': Decimal('52.8400000000000')}]>

It is possible to accomplish what I want with only one query instead of three?
Expected result:
<ExpenseQueryset [{'category': 'FOOD', 'total': Decimal('33.9000000000000')}, {... all other categories ...},
{'source': 'MONEY', 'total': Decimal('100')}, {... all other sources ...}, {'is_fixed': False, 'total': Decimal('1121.74000000000')}, {'is_fixed': True, 'total': Decimal('813.880000000000')}]>

Optimally, it could be split into something like:
<ExpenseQueryset ['categories': [{'category': 'FOOD', 'total': Decimal('33.9000000000000')}, {... all other categories ...}],
'sources': [{'source': 'MONEY', 'total': Decimal('100')}, {... all other sources ...}], 'type': [{'is_fixed': False, 'total': Decimal('1121.74000000000')}, {'is_fixed': True, 'total': Decimal('813.880000000000')}]]>

But this is just a big plus.
Comment: It's not that it cannot be done in Django. I don't see a way you can achieve this in raw SQL. A single query allows you to group by one or more columns, but even when you group by multiple columns, you just tell the database to put all the rows, that have the same value in those columns, into a single group. The only option you have is to split it into three queries.
Comment: chaining multiple fields to values doesn't help? for example: `values('is_fixed', 'source', 'category')`.
Comment: No, because it will GROUP BY all the fields together: `{'is_fixed': False, 'category': 'FOOD', 'source': 'SETTLE_UP', 'total': Decimal('33.9000000000000')}`
Comment: What's your expected result?
Comment: @Crash0v3rrid3 I just update the question.
Comment: as @Crash0v3rrid3 mentioned, i also dont see a way to do this in raw SQL maybe with union all, but that would also imply multiple queries.

You could then concatenate the 3 querysets into a single dictionary, but not into a single queryset. Maybe you could have a more complex queryset with a custom ModelManager, but that might be too much effort.

what is your end goal? return that ExpenseQueryset in a view?
Comment: @Alucarder, yeah I'm doing 3 queries now and returning the results in a dict. And yes, my end goal is to return data to a view.
Answer: The Answer is NO, Cause it's not possible with SQL
But you can use the below approach combined with python coding:
I don't think it's possible even in raw SQL, Cause in each query you can group by one or multiple fields together, but not with separated results for each.
But it's possible to do it with one query and use little python codes to merge results in the format u want. below I described how u can use it step by step. and in the next section wrote a python method that u can dynamically use for any further usages.
How it works
The only simple solution I can mention is that you group by those 3 fields you want, and do a simple python programming to sum results together for each field.
In this method, u will have only one query but separate results for each field group-by.
from expenses.models import Expense
from django.db.models import Sum

qs = Expense.objects.order_by().values("is_fixed", "source", "category").annotate(total=Sum("price"))

Now the result will be something like below:
<ExpenseQueryset [{'category': 'FOOD', 'is_fixed': False, 'source': 'MONEY', 'total': Decimal('33.9000000000000')}, { ...},

Now we can simple aggregate each field result by iterating on this result
category_keys = []
for q in qs:
    if not q['category'] in category_keys:
        category_keys.append(q['category'])

# Now we have proper values of category in category_keys
category_result = []
for c in category_keys:
    value = sum(item['total'] for item in qs if item['category'] == c)
    category_result.append({'category': c, 'total': value)

And the result for the category field will be something like this:
[{'category': 'FOOD', 'total': 33.3}, {... other category results ...}

Now we can continue and make result for other group by fields is_fixed and source like below:
source_keys = []
for q in qs:
    if not q['source'] in source_keys:
        source_keys.append(q['source'])
source_result = []
for c in source_keys:
    value = sum(item['total'] for item in qs if item['source'] == c)
    source_result.append({'source': c, 'total': value)

is_fixed_keys = []
for q in qs:
    if not q['is_fixed'] in is_fixed_keys:
        source_keys.append(q['is_fixed'])
is_fixed_result = []
for c in is_fixed_keys:
    value = sum(item['total'] for item in qs if item['is_fixed'] == c)
    is_fixed_result.append({'is_fixed': c, 'total': value)

Global solution
Now that we know how to use this solution, here is a function to just give fields you want to it and will make proper results for u dynamically.
def find_group_by_separated_by_keys(key_list):
    """ key_list in this example will be:
        key_list = ['category', 'source', 'is_fixed']
    """
    qs = Expense.objects.order_by().values(*tuple(key_list)).annotate(total=Sum("price"))
    qs = list(qs)
    result = []
    for key in key_list:
        key_values = []
        for item in qs:
            if not item[key] in key_values:
                key_values.append(item[key])

        key_result = []
        for v in key_values:
            value = sum(item['total'] for item in qs if item[key] == v)
            key_result.append({key: v, 'total': value})

        result.extend(key_result)
    return result

Now just simple use it like below in ur code:
find_group_by_separated_by_keys(['category', 'source', 'is_fixed')

And it will give a list of values like the proper format u wanted
Comment: It's a solution, but I'm just wondering if it's worth it: I have only one query, but I got `4*len(key_list)` loops + greater code complexity. Anyway, thanks!
Comment: `4*len(key_list)` will not cause much trouble. The only case that causes a problem is when `key_list` is like million choices and have many value options. and code complexity is not a problem cause I provide a ready-to-use function.
Comment: Code complexity is not about the possibility to "plug-and-forget" some code, but also who are going to maintain it, etc...
Comment: May I know which part is complex maybe it can be written better. And also If this approach is not going to work for you, then this question should be closed, As it never has an approach with SQL to give u the result in the way u want. Cause Django ORM is based on SQL and this operation is not handled with SQL. But u can also w8 for others to give same answer.
Comment: I updated the answer as it's not possible with SQL. But will gladly w8 to see if any other person has an approach with SQL.
Comment: The code is not complex by itself, is just more complex than doing 3 queries. Yes of course that django's ORM can't do magic if it can't be accomplished with pure SQL. I agree it should've been closed by now but I was unable to do so because of the current bounty.
Comment: so either way I guess the answer I provided should be accepted. Cause I mentioned in detail that it's not possible and I provided the alternative solution with python.


How to extend entityreference field by another custom field?

Question: I want to add another field, which needs to be accessible by views (for display and ordering), to the entityreference table field_data_field_FIELDNAME. Structure of that table is:

entity_type VARCHAR(128)
bundle VARCHAR(128)
deleted TINYINT(4)
entity_id INT(10)
revision_id INT(10)
language VARCHAR(32)
delta INT(10)
field_FIELDNAME_target_id INT(10)

I want to have a column storing DateTime information here, so I can attach information about when this reference was added/ updated for that referenced entity. There also needs to be a way to save the newly added field directly in the array structure for that reference such as:
<code>$node->field_reference['und'][] = array(
  'target_id' => 123,
  'my_new_column' => '2014-03-13 15:29:29'
);
</code>
I know I could solve this by using field_collections or relation module, but both would cause significant performance issues.
Answer: Gave an approach here https://www.drupal.org/node/2001822#comment-9165509
Hope that it will work for you
Comment: thank you, you should probably post the contents in your answer on stackexchange as well to help others, luckily I managed to finish this task a few month ago - but didnt have time to answer my own question. code is here: https://www.drupal.org/sandbox/baumeier.it/2078043
Comment: Link-only answers are discouraged, even when linking to your own post. Keep the link, but summarize it here, and you'll have my upvote. See https://drupal.stackexchange.com/help/how-to-answer


Condição IF em javascript só funciona uma vez

Question: Estou tentando fazer um Side Navigation, então em pesquisa na internet, achei um tutorialzinho no site: How TO - Side Navigation
Porém, no meu exemplo queria que um unico botão abrisse, e fechasse, então fiz as seguintes modificações:
function closeNav()
{
    if (document.getElementById("mySidenav").style.width < 250)
    {
        document.getElementById("mySidenav").style.width = "250px";
    }
    else
    {
        document.getElementById("mySidenav").style.width = "40px";
    }
}

Mas, ele so funciona uma vez, ou seja, ele abre e fecha depois não funciona mais.
Comment: Nunca faça a side-nav aparecer e desaparecer através da alteração do width, use o css translateX do transform. Quando você faz a alteração da width você gera vários Paints custosos que são feitos pela CPU, se você usar translateX você terá Paints extremamente leves executados pela GPU.
Comment: Onde é que tem Java aí?
Comment: Você pode fazer um exemplo no JSFiddle?
Answer: O valor que .style.width retorna é uma string. Tens de usar um conversor de tipo para teres um numero e usar o operador <.
Podias fazer isso assim:
function closeNav() {
    var sideNav = document.getElementById("mySidenav");
    if (parseInt(sideNav.style.width) < 250) {
        sideNav.style.width = "250px";
    } else {
        sideNav.style.width = "40px";
    }
}

Comment: Amigo, funcionou perfeitamente, porém, para funcionar a primeira vez, tenho que clicar duas vezes. sabe o porque?
Comment: @ThomasErichPimentel provavelmente porque esse elemento `#mySidenav` não tem um estilo definido de inicio. Somente no CSS não vai ser lido pelo `.style.width`. Testa colocar `style="width: ..."` no HTML. Se tiver percebido mal faz um jsFiddle para ser mais claro.


Chocolate Bar Algorithm - Minimum Number of breaks

Question: I am trying to design an algorithm that solves the following with the minimum number of bar breaks.
A chocolate bar with $n * m$ pieces must be broken into $nm$ $1*1$ pieces to share with $n * m$ people. The bar must be broken only in a straight line, and once broken, only one piece at a time can be further broken. What is the minimum number?
I understand that using properties of a binary tree would best justify my solution and that a divide-and-conquer approach should be used.
Comment: If it is the chocolate bar problem I am familiar with, all algorithms are equally efficient.
Answer: Unfortunately, no matter how you do it, you will always use exactly $nm-1$ breaks.
The reason? Every break increases the number of pieces by one!


Difference between return and enter keys in Selenium

Question: What is the difference between return and enter keys in Selenium? This related SO answer and the provided link state that they are different. I also noticed that enter key will send an HTML form while return doesn't when using Firefox 24.2.
Comment: with all due respect and honesty, it's bad automated test logic to simulate a key press.  You should always click the submit button associated with a search field or something of the sort.
Comment: The user interface I am testing contains an input field for selecting multiple keywords. When using it normally with a browser, enter key selects a single keyword and adds it to the list of keywords. With Selenium however enter key sends the form and return key selects a single keyword.
Comment: You may use ```\n``` rather.
Answer: Normally these keys are interchangeable. I believe the original implementation the Keys. Enter was the enter key on the number pad and the Keys.
Return was the one next to the letters. It's also fine to use these keys in Selenium testing, if it matches a user flow or requirement, which is the goal of testing through the UI.


What are the benefits of using 2 LTO-5 in parallel for pure CIFS backup?

Question: I use a NetApp FAS3240 as a storage system, and I'd like to attach an LTO-5 NDMP backup system (with Backbone) in Fiber Channel.
What will be the difference of using 1 LTO-5 or 2 LTO-5 streams?
Will it improve performance a lot?
Is there any kind of LTO-5 technical database with some information?
Thanks a lot in advance for your help.
EDIT: The amount of data could reach 30TB per backup job, no tape backup used yet.
Answer: Well, the benefit would be speed if you can keep both drives spinning from the NDMP streams.
I don't think your storage system can split one job into 2 concurrent NDMP streams so each NDMP stream would be a separate job.
The possible downside would be having to manage 2 tapes for your data, 2 tapes to restore from, 2 big, expensive tapes for data that (might) fit on 1 tape, etc.  (This may not be an actual downside for you, depending on what you are trying to achieve.)
How much data are you backing up and how long does it take to back it up to one drive?
(multiple drives is often useful with longer backup jobs so that you have a drive available for restores while a long job is running and/or so shorter jobs don't pile up waiting for the long job to finish)
Comment: Thanks for the answer, I edited my question: the amount of data could reach up to 30TB.


AWS/Step function: Access passed-over header value

Question: I have python code to trigger a step function, and pass in custom headers.
client = boto3.client('stepfunctions')
response = client.start_execution(
    stateMachineArn=stateMachineArn,
    name=name,
    input={'id': 'my-id'},
    headers={'mode': 'normal'}
)

I have a step inside the step function to trigger a lambda:
"trigger-lambda": {
    "Type": "Task",
    "Resource": "arn:aws:lambda:us-east-1:...:function:my-lambda",
    "Parameters": {
        "id.$": "$.id"
    }
}

I can access the "id" from the step function's input. But  how to pass "mode" back to the lambda.
Answer: Step Functions Start Execution does not support a request parameter called headers. You need to include this information in the input if you want it to be available within your workflow. Something like this:
client = boto3.client('stepfunctions')
response = client.start_execution(
    stateMachineArn=stateMachineArn,
    name=name,
    input={'id': 'my-id','mode': 'normal'},
    headers={'mode': 'normal'}
)

and then:
"trigger-lambda": {
    "Type": "Task",
    "Resource": "arn:aws:lambda:us-east-1:...:function:my-lambda",
    "Parameters": {
        "id.$": "$.id",
        "mode.$: "$.mode"
    }
}


What does imply mean in maths?

Question: What does it mean for something to imply something else in maths? I don't think I've grasped this concept and it's making understanding theorems and proofs really difficult for me. I know that a statement is a sentence which is either true or false, but not both. I think it might be the word 'imply' that's throwing me off. I've searched for definitions and examples, but they don't seem to make anything clearer for me. Thank you.
Comment: If you have two properties, $P,Q$ then $P \implies Q$ means that if $P$ is true then $Q$ is true. For example, $P$ could be the property $x >0$ and $Q$ could be the property $x > -1$. Then we see that $P \implies Q$ is always true.
Comment: It's not supposed to mean one thing. Logic is varied.
Comment: @copper.hat In other words, letting $\mathsf{False Blockquote 5 > 4. This implies: 5 > 3, 5 > 2, and 5 > 1. If any of those statements after the first is useful in a proof, you are allowed to pull that statement out of thin air and use it. That use of implies is pretty confusing when you first start doing proofs, because for the first time the student is free to use what they know of numbers and counting to prove something is true. An original statement created as part of proving a hypothesis true.
Answer: In most mathematical proofs, $P\implies Q \space \equiv\space \neg[P\land \neg Q]$.
There is also no causal relationship assumed between the antecedent $P$ and consequent $Q$, i.e. we do not assume that $P$ causes $Q$.
From the above definition we have:

If we assume $P$ is true and can prove that $Q$ is also true, then
we can infer that $P\implies Q$.
If $P$ is true and $[P\implies Q]$ is true, then can infer that $Q$
is true.
$P \implies Q\space$ follows from any of the following:

$\neg Q \implies \neg P$
$\neg P \space \space$
$Q \space \space $
Answer: In math, the fact that a statement $A$ implies a statement $B$ is written this way: $A \implies B$
The meaning of $A \implies B$ is defined by this truth table:
$$
    \begin{matrix}
     A & B & | & A \implies B\\
     T & T & | &T\\
     T & F & | &F\\
     F & T & | &T\\
     F & F & | &T\\
    \end{matrix}
$$
That means that $A \implies $B is false only when $A$ is true and $B$ is false. In the other cases $A \implies $B is true.
So let's say I have a theorem that states "If $n$ is a multiple of $6$ then it must be a multiple of $2$" ($n$ multiple of $6 \implies n$ multiple of $2$). For this theorem to be true, if you encounter a multiple of $6$ then it must be also a multiple of $2$ because if not the implication would be false. But if you encounter a number that is not a multiple of $6$ then it can be a multiple of $2$ or not without invalidating the theorem, because the theorem says nothing about numbers that are not multiple of $6$.
You can also see what the implication means by looking at sets:
Answer: A statement $A$ implies another statement $B$ (written as $A\Rightarrow B$), if from the truth of the former, it necessarily follows the truth of the latter.
Example. If I am in London, I am necessarily in England. So the statement "I am in London" implies the statement "I am in England".
On the other hand, if it is possible for $B$ to be true, while simultaneously $A$ is false, then $A$ is not implying $B$.
Example. If I am in England, I am not necessarily in London (I could be in Oxford). Hence, the statement "I am in England" does not imply the statement "I am in London".
Answer: If you take two statements $P$ and $Q$ then saying "$P$ implies $Q$" or equivalently $P \implies Q$ means that if $P$ holds then $Q$ holds. For instance, the following are some factual implications.

"$x$ is a real number greater than zero" implies "$(-1)\cdot x$ is a real number less than zero." This is true because if the first statement holds then one may conclude the second holds as well.
"x is an odd number" implies "There exists a natural number $k$ such that $x = 2k + 1$." Again, from the first statement one can conclude the second.

Here is an example of an incorrect implication:

"x is a real number" implies "$x$ is less than zero." Here, one cannot conclude the second statement from the first, so it is incorrect to write this. What if $x = 0$?
Comment: Your second example of an incorrect implication is actually a correct implication.
Comment: Oops, you're totally right. Thanks.
Answer: Fundamentally, mathematics is a guide to reducing the unknown. When we have a statement "If $P$ then $Q$", that means if we somehow already know that $P$ is true, then we now can be assured that $Q$ is true. Each theorem that proves an implication allows us  to expand our knowledge of true facts by using chains of implications. We start with known supposed true facts and, using chains of implications, we can conclude many other true facts on the basis of the suppositions. And finally arriving at what we want to prove to be true also. The Achilles' heel of this method is that we are dependant of the starting true facts, and if any one of them turns out to be false, then the results of our implications are now not assured to be true. Another weakness is that we could make several kinds of errors in applying the implications because "to err is human" and "a chain is as strong as its weakest link".

What does imply mean in maths?


Alternate picking while palm muting

Question: I've been practicing alternate picking and palm muting for a while now, but I have extreme difficulties when combining these two techniques together. My picking hand can't move freely when resting on the bridge. My hand hurts and it just feels like a struggle, so I must be doing something wrong. However, if I keep my hand floating in the air I have no difficulties with alternate picking...
Should I stick to downpicking when palm muting at the same time or do you have any advice on combining these two techniques together?
Comment: Practice. You're doing everything right. Just keep doing it until it sounds good to you.
Answer: Holding the pick just between thumb and one finger gives enough movement to play across two or three strings without moving the part of the palm that is muting. If you move, say, to the top three strings, then slide the whole hand downwards so that the palm mute part of your hand is over those strings. When you move to the E, A and D strings, slide the muting palm up over them. Holding the pick too tightly will hamper movement, so relax as much as possible. It's not a technique that one wakes up one morning able to do it, so keep practising. Maybe also, you are pressing too much when muting.
Answer: Its tricky, I need to alter my palm mute hand shape and finger position for picking depending on what sound I want.
Just play around and experiment until your get the right sound for the most comfort, this will change depending on what your doing & make sure your not tensing your muscles. (If I learn something new I have to repeatedly and consciously remember to relax muscles)
Answer: Some stuff is too fast to just use downstrokes.
I will assume that you play metal, the technique isn't used very much outside of those genres. Then one thing to consider is string gauge. It might seem intuitive to have thick strings to pound away on, but a lot of metal players actually use quite thin strings. Then palm muting will be easier both up and down.
The next thing to consider is that almost all players are better at downpicking, since that is used more (and possibly since you have gravity working in your favour :)). In order to strengthen the upwards palm muting, alternate between playing only downstrokes and only upstrokes, in order to get an even sound. Try different combinations e.g. 4 down 4 up, 4 down 8 up, 2 down 2 up and finally 1 down 1 up. Like always, start slowly where you feel in control, and increase the speed as you build stamina.
As others pointed out, it is important to stay relaxed, otherwise you will wear out. The motion should mainly be in your wrist. It's common to tighten up and use the entire forearm when tempo's reach the outer limits of ones ability.
Using a quite heavy and pointed pick is recommended for precision. I personally use Dunlop Jazz III, but there are a lot of different types and shapes out there.
Comment: I usually play between drop D and drop B. I'm a huge fan of .09 gauge strings on standard tuning, but they bend too much on drop B tuning and detune really fast... I bought heavy core .11 strings, they don't detune quickly but they are very thick and more difficult to pick. Do you have a recommendation for some good strings I could try? High-five for the Dunlop Jazz III pick, I use it as well and I love it! :D
Comment: @muffin: Try a set with 046 for the low E string for drop D, and 054 for B. What scale length guitars are you using? Gibson type scale (24.75") needs thicker strings than Fender (25.5"). Adjust upward/downward in size depending on how the strings feel. I think it's best to use different string gauges for drop D and drop B tunings.
Comment: Isn't 54 extremely thick? Well those who I have now are 50 on the low E, and that's already hard to play... I have an Epiphone SG 400, so Gibson scale.
Comment: @muffin: What's the low E string gauge on your 011's you use now for dropped tunings, and the 009's you use for standard E? I'm guessing for the 009's it's 042 and for the 011's 049 or 052. If 042 is too loose for detuning, try to go one step up, to 046. It's difficult to accomodate both D and B tuning with one set of strings, I believe. Then it's going to be a compromise that's a bit too tight in B and a bit too loose in D. It might work, but the only way is to do some trial and error.
Comment: SHARKFIN PICK!!! They seem to be dissapearing from shops I have to specially order them
Comment: @MeaningfulUsername: My low E string gauge is 042 on standard tuning and 048 on drop B tuning (too hard when tuned higher)
Comment: @muffin: If 042 is too lose and 048 is too tight, then it's 046 left in the middle, and that's not going to make a huge difference. Seems you have to work on them muscles! :)
Answer: Picking is a trifecta of finger memory, pinky relation, and palm base. Mind your pinky position most. Try hooking your pinky under, or resting it near, the high E string to give yourself a point of "reference". This often makes it easier to pick freely while still allowing accuracy, palm/muting, dig-in, and more string reach. This is easier on Gibson style bridges, but regardless it helps some folks.
In addition it allows you to control the high E, for example if you wanted to strum/chug all strings without having the high E ring out.

Alternate picking while palm muting


Drupal 8 translation for routing titles

Question: In Drupal 8, I installed all translation modules (Configuration Translation, Content Translation, Interface Translation, Language) and cleared all caches and run cron again.
But the titles defined in routing YML files are still missing from the User interface translation configuration page (/admin/config/regional/translate)
Any idea?
Answer: Just figured it out.
After installing all above modules, we still have to visit the page defined by the routing and switch it to another language (non-English).
Then system would automatically pick up all strings in the page needed to translate, including the title.
The source string is case sensitive.

Drupal 8 translation for routing titles