Restriction of diagonalizable transformation to invariant subspace is diagonalizable

Question:
Let $V$ be a vector space with $\text{dim}(V)=n$ and $T: V \to V$ be a linear transformation. Let $W \subseteq V$ be a $T$-invariant subspace, i.e. $T(W) \subseteq W$, with $\text{dim}(W)=k$.
Show, that if $T$ is diagonalizable, then there exists a basis for $W$ consisting of eigenvectors of $T$. Show also that $T_W: W \to W, T_W(w):=T(w)$ is diagonalizable.

I found only a proof using the minimal polynomial which I haven't learned yet and couldn't find a proof without it. Can somebody check my attempt below?

Since $T$ is diagonalizable, there exists a Basis $B=\{v_1,\ldots,v_n\}$ for $V$ consisting of eigenvectors of $T$. Also the characteristic polynomial splits in linear factors. If we denote with $\lambda_1,\ldots,\lambda_n$ the corresponding eigenvalues to $v_1,\ldots,v_n$, then $p_T(t)= p_{[T]_B}(t)=(t-\lambda_1) \cdots (t-\lambda_n)$.
Construct from some $w_j \in V$ a basis $C=\{w_1,\ldots,w_k\}$ of $W$ and $T_W:W \to W$ with $T_W(w)=T(w)$. Since $T(W)\subseteq W$, we have $T(w_j)=\sum_{i=1}^k c_iw_i$ for some scalars $c_i$, which means
$$[T_W(w_j)]_{C}=\begin{bmatrix} c_1 \\ \vdots \\ c_k \end{bmatrix}$$
And by definition $[T_W]_C=\begin{bmatrix} [T_W(w_1)]_{C} & \ldots & [T_W(w_k)]_{C} \end{bmatrix}$
We can extend $C$ to a basis of $V$ with additional $v_i$'s (since $B$ is a basis of $V$ already). Assume for the sake of simplicity of notation that it's the first $n-k$ basis vectors, i.e. $B':=C\cup\{v_1,\ldots,v_{n-k}\}$ forms a basis for $V$. Then
$$[T]_{B'} = \begin{bmatrix} \vert & & \vert & \vert & & \vert \\ [T(w_1)]_{B'} & \ldots & [T(w_k)]_{B'} & [T(v_1)]_{B'} & \ldots & [T(v_{n-k})]_{B'} \\ \vert & & \vert & \vert & & \vert \end{bmatrix}$$
But since $T(W)\subseteq W$, we have $T(w_j)=\sum_{i=1}^k c_iw_i$ for some scalars $c_i$, which means
$$[T(w_j)]_{B'}=\begin{bmatrix} c_1 \\ \vdots \\ c_k \\ 0 \\ \vdots \\ 0 \end{bmatrix} = \begin{bmatrix} \vert \\ [T_W(w_j)]_{C} \\ \vert \\ 0 \\ \vdots \\ 0 \end{bmatrix}$$
And $T(v_j)=\lambda_j v_j$ and so $[T(v_j)]_{B'}$ has only a $\lambda_j$ in the $k+j$-th entry and everywhere else zeros. So we get
$$[T]_B = \begin{bmatrix} \ulcorner & & \urcorner & & & \\ & [T_W]_C & & & & \\ \llcorner & & \lrcorner & & & \\ & & & \lambda_1 & & \\ & & & & \ddots & \\ & & & & & \lambda_{n-k} \end{bmatrix}$$
If we compute the characteristic polynomial we get
$$\begin{align} p_{[T]_B}(t) &= (t-\lambda_1) \cdots (t-\lambda_n) = p_{[T]_{B'}}(t) = \text{det}\left([T]_B-tI_n\right) \\&= (-1)^{n-k}(t-\lambda_1) \cdots (t-\lambda_{n-k}) \cdot \text{det}\left([T_W]_C-t I_k\right) \\&= (-1)^{n-k}(t-\lambda_1) \cdots (t-\lambda_{n-k}) \cdot p_{[T_W]_C}(t) \end{align}$$
And so $p_{T_W}(t) = p_{[T_W]_C}(t) = (-1)^{n-k}(t-\lambda_{n-k+1})\cdots(t-\lambda_{n})$, which means $T_W$ has eigenvalues $\lambda_{n-k+1},\ldots,\lambda_n$.
Let $u_{n-k+1},\ldots,u_n \in W$ be the corresponding eigenvectors of $T_W$, i.e. $T_W(u_j)=\lambda_j u_j$. Since for all $w \in W$ we have $T_W(w)=T(w)$, we have $\lambda_j u_j = T_W(u_j) = T(u_j)$ for all $n-k+1 \le j \le n$. But $T(v_j)=\lambda_j v_j$ and therefore $u_j = c v_j$ for some scalar $c$.
We have found $n-(n-k+1)+1 = k$ eigenvalues of $T_W$ which are also eigenvalues of $T$ and the corresponding $k$ eigenvectors of $T_W$ are also exactly eigenvectors of $T$. Since $\text{dim}(W)=k$, we can construct a basis for $W$ of eigenvectors of $T_W$ and therefore $T_W$ is diagonalizable.
Comment: Your argument will only work if the eigenvalues are all distinct.  Otherwise, how do you know that $T_W$ has linearly independent eigenvectors corresponding to $\lambda_{n-k+1},\dots,\lambda_n$? You must argue that the geometric multiplicity of each such eigenvalue equals its algebraic multiplicity. Obviously, the fact that $T$ is diagonalizable has to get used here!
Comment: @TedShifrin Yes, I didn't write it clearly enough. When I wrote in the beginning there are $n$ eigenvalues $\lambda_1,\ldots,\lambda_n$, I meant including multiplicity. So $\lambda_5=\lambda_6=\lambda_7$ is possible, but since $T$ is diagonalizable, there are also linearly independent $v_5,v_6,v_7$. And in the end where we've got $k$ (not necessarily distinct) eigenvalues, there are $k$ linearly independent eigenvectors associated with them. I tried to avoid keeping track of algebraic multiplicities by writing the eigenvalues one by one.
Comment: But you need to prove that there will be sufficiently many eigenvectors for $T_W$. That's the key part of the proof. Having $k$ linearly independent eigenvectors for $T$ in the first place doesn't help you if they're not in $W$.
Comment: @TedShifrin Isn't this exactly the second last paragraph? We have those $k$ eigenvalues of $T_W$ and say $u_j$ are the corresponding eigenvectors in $W$. Then we show that those $u_j=v_j$ and since the $u_j$ are in $W$ the $v_j$ must be too and those $v_j$ are exactly the $k$ eigenvectors of $T$ we can use to build a basis of $W$.
Comment: Nope. This is a "proof by wishful thinking." Never have you proved that the geometric multiplicities are equal to the algebraic multiplicities. You are forgetting that with repeated eigenvalues, you no longer have "unique" eigenvectors for each eigenvalue.
Comment: @TedShifrin I thought about it again but I don't fully see the issue... Maybe I'll need to see the correct version to understand what's wrong. I'd appreciate if you could write a quick answer with the corrected part so that I can understand what's not working yet. Thank you!
Comment: @TedShifrin Maybe I could argue like this: "Since appending $\{v_1,\ldots,v_{n-k}\}$ to $C$ sufficed to make it a basis of $V$, we know that $v_{n-k+1},\ldots,v_n \in \text{span}(C) = W$. Also we know that they are linearly independent. Now $T_W(v_j)=T(v_j)=\lambda_j v_j$ for all $n-k+1 \le j \le n$. So $v_j$ are also $k$ linearly independent eigenvectors of $T_W$.". But this is probably not it as well...
Answer: If you start with a basis $\{w_1,\dots,w_k\}$ for $W$ and extend it to a basis $\{w_1,\dots,w_k, v_{k+1},\dots,v_n\}$ for $V$, we get the matrix representation
$$[T]=A=\left[\begin{array}{c|c} B & D \\ \hline O & C \end{array}\right]\,.$$
(You are correct that you can actually assume $v_{k+1},\dots,v_n$ are eigenvectors, but that's actually unnecessary.)  Fix an eigenvalue $\lambda$ of $B$. Let $d_A$, $d_B$, and $d_C$ be the respective geometric multiplicities for $\lambda$, and let $m_A$, $m_B$, and $m_C$ be the respective algebraic multiplicities for $\lambda.$ We want to see that $d_B = m_B$.
As you pointed out, $p_A(t) = p_B(t)p_C(t)$, so $m_A=m_B+m_C$. Moreover, since $T$ is diagonalizable, $d_A=m_A$. And, as always, $d_B\le m_B$ and $d_C\le m_C$.
Now $\text{rank}(A-\lambda I) \ge \text{rank}(B-\lambda I)+\text{rank}(C-\lambda I)$ (why?). Since $d_A = n-\text{rank}(A-\lambda I)$, $d_B = k-\text{rank}(B-\lambda I)$ and $d_C = (n-k)-\text{rank}(C-\lambda I)$, we have $d_A\le d_B+d_C$.  But since $d_A=m_A$, we must have $d_B=m_B$ (why?).
Comment: Thanks! I think I found where I made a wrong assumption in my proof. When I built $B'$ with some eigenvectors of $T$, I assumed that there are no more eigenvectors corresponding to the eigenvalues of those chosen eigenvectors left, i.e. all would be in this extended basis. This would mean that the remaining eigenvectors not in $B'$ would all have different eigenvalues than those that are in $B'$. But for a repeated eigenvalue some of its eigenvectors could be in $B'$ and some not. I hadn't thought of that. It would have helped if I had written the multiplicities explicitly. Thanks anyways!


BAM EventBus Service

Question:
Execute event error.Error(s) occurred while executing events, see TDDS_FailedTrackingData table for more details.SqlServer:'server name',database:BizTalkDTADb."

How can get rid of this error? In past we are using BAM portal and we just removed BAM but some of tracing will be there to generate this type of error message ?
Answer: All Exceptions sendport was the culprit. It contains a pipeline component called
                  "ESB BAM Tracker"
that was enabled by default. The solution was to disable this pipeline component:

BAM EventBus Service


JavaScript MD5 differs from Python/Bash md5sum

Question: I have the following snippet
    function runUpload( file ) {
        key_name = file.name
        if( file.type === 'image/png'  ||
                file.type === 'image/jpg'  ||
            file.type === 'image/jpeg' ||
                file.type === 'image/gif'  ||
                file.type === 'image/bmp'  ){
            var reader = new FileReader(),
                    image = new Image();
            reader.readAsDataURL( file );
            reader.onload = function( _file ){
                keyhash = md5(atob(_file.target.result.split(',')[1]));
                ZZ('key').el.src = _file.target.result;
                ZZ('key').el.style.display = 'block';
            }
        }
    }

The reason that the split happens is because if I left it at just:
_file.target.result

The resulting string would be:
data:text/plain;base64,SEVMTE8=

It uses https://raw.githubusercontent.com/blueimp/JavaScript-MD5/master/js/md5.min.js
The value of keyhash is different from when I do:
cat file.png | md5sum

Also when doing the python below, it gives me a different value to the JS version but the same as Linux
import hashlib

def md5Checksum(filePath):
    with open(filePath, 'rb') as fh:
        m = hashlib.md5()
        while True:
            data = fh.read(8192)
            if not data:
                break
            m.update(data)
        return m.hexdigest()

print('The MD5 checksum of text.txt is', md5Checksum('000000.png'))

Am I missing something obvious or should they all return the same value?
JS: dc839221df178f70c08fa510a3d76a3b
Python and MD5SUM: 9310dad66d4a73e29a761fb724f2825
In fact, if I have a file called HELLO.txt and the only content in there is: HELLO
base64'ing it in Linux/Python give the same result which is different to when JS does it.
SEVMTE8K vs SEVMTE8=

I think it may be something to do with new lines, break likes, return carriages etc
JavaScript has it as one continuous stream whereas editing the file in an text editor shows line breaks
Thanks
Comment: `_file.target.result.split(',')[1]`, what is this for?
Comment: The Javascript function brings back data:image/png;base64 (or similar) at the start and then the content of the file, all of which is separated by the comma
Answer: The only explanation is that encoding is different. Figure out encoding in JS (ISO-8859-1) to that in python (UTF-8).


Getting ID of last insert

Question: I am implementing an auto save feature which saves every minute on a form that is being edited or created.
I am doing an insert of a null value beforehand in an auto-incremented db table. From here after the null insert, I need to retrieve the id that was inserted so that I can update off of that ID. How Can I go along of getting this ID with the code I have provided?
I have tried using mysqli_insert_id as shown below, but no luck.
// insert null into database to create the save point
if ($stmt = $mysqli->prepare("INSERT INTO test_table (name, email, notes) VALUES ('x', 'x', 'x')"))
{
    $stmt->execute();
    $stmt->close();
}
// show an error if the query has an error
else
{
    echo "ERROR: Could not prepare Auto-Save SQL statement.";
}

//GET LAST ID
printf("Last inserted record has id %d\n", mysqli_insert_id());

Comment: RTM http://php.net/manual/en/mysqli.insert-id.php `printf ("New Record has id %d.\n", mysqli_insert_id($link));`
Answer: Posting as a community wiki.
printf ("New Record has id %d.\n", mysqli_insert_id($mysqli));

You didn't pass your db connection to it.
Reference:

http://php.net/manual/en/mysqli.insert-id.php

Object oriented style

mixed $mysqli->insert_id;

Procedural style

mixed mysqli_insert_id ( mysqli $link )
Answer: //this query will get the auto increment value of the specific table
SELECT `AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbname'
AND   TABLE_NAME   = 'tblname';

Getting ID of last insert


Erro ao carregar fonte: OTS Parsing error: cmap: Failed to parse format 4

Question: Estou tendo problema para que o browser use um fonte personalizada! Na pasta css eu tenho a pasta fonts, e dentro da pasta fonts está o arquivo prompt.ttf porém na hora que subo o arquivo pro servidor, eu faço o teste e a fonte não aparece. Ela é substituída pela fonte padrão sans-serif.
Código no CSS do INDEX:
@font-face {
font-family: 'prompt';
src: url('fonts/prompt.ttf');
}
#name {
font-family: 'prompt', sans-serif;
font-size:10px;
text-indent:10px;
text-align:left;
z-index:1;
position:absolute;
font-weight:normal;
width:120px;
height:20px;
top:110px;
right:75px;
border-radius: 5px 5px 5px 5px;
-moz-border-radius: 5px 5px 5px 5px;
-webkit-border-radius: 5px 5px 5px 5px;
border: 0px solid #000000;
}

Print do erro:
Comment: tenta usar https://www.fontsquirrel.com/tools/webfont-generator, e muda o seu css, não custa tentar haha
Answer: De fato resolvi o erro adicionando o formato da fonte que queria usar, (true type).
Ficou assim o CSS:
font-family: 'prompt';
src: url('fonts/prompt.ttf') format('truetype');

Testei com open type e também funcionou:
font-family: 'menufont';
src: url('fonts/myriad.otf') format('opentype');

Enfim, era só adicionar o format que parava o erro!


Weird "flutter" in guitar amp when a note is ringing out

Question: I recently bought a used guitar (a Sterling JP60) and I just noticed this problem - I am hearing a strange, irritating "flutter" like sound through my amp when a note is ringing out. Particularly obvious on the first two strings, and when the sustained note is after a pull off but also happens during bends and normal playing sometimes. Here is an example
https://vocaroo.com/i/s1GX45TQkB61
Any thoughts on what's causing this and how it can be fixed?
Comment: I would recommend trying to reproduce the problem with a clean sine wave if you think it's the amp. If it's not the amp, try making the sound without any distortion or effects.
Answer: I've listened to the link and it sounds to me like a problem I had when I blew my speaker. When the voice coil in a speaker over heats they can become warped and start rubbing internally. When that happens, the speaker can respond unevenly as it gets stuck and breaks loose repeatedly.
A good repair technician can be worth his weight in gold when it comes to sorting this kind of thing out.
Comment: I just tested it again and I can hear it through headphones too, but it is a little less obvious through phones
Answer: It could be the action (distance from the fretboard) of your 1st and 2nd string is too low and the string is slightly coming into contact with other frets higher up the neck, this can be adjusted with an allen key either by yourself or a guitar tech.
P.S It's hard to tell if that's the issue with all the distortion going on in the clip but that would be my first guess.


When to use libmemcached in non-blocking mode?

Question: I'm starting to integrate libmemcached into my application and reading the documentation, there is a non-blocking mode flag. After a quick google, there seems to be a performance advantage to non blocking mode, but are there any disadvantages to running libmemcached in non blocking mode?
Answer: Of course there are.  The disadvantage would only arise if you needed to ENSURE that the written value actually was written to memcached and did not fail.  For example - you're using memcached to store a counter variable which has a sentinel that checks to see if the counter has reached a certain value before performing an operation.
In blocking mode - the memcached client will wait to get a write success response from memcached before proceeding and produce an error if it fails. This way you know the counter was updated. If you tell it to write in non-blocking mode, the client sends the request to increment the counter, but never waits to ensure that it really occurred.  Because it doesn't wait, you code execution after the call resumes more quickly, but with the uncertainty of not knowing for sure the counter was ever incremented.
However, since memcached values are destroyed on a service restart (think system crash) you can't ever really be sure a value will be there. Also, with low-memory pruning you also cannot ever be sure the value is 100% correct as it may get pruned by the LRU algorithm - you'd need persistent storage to alleviate this uncertainty.
Given this inherent uncertainty, many people use non-blocking mode to get the performance gain because they can't ever be totally certain the counter value in memcached isn't reset/innacurate anyway, so why not get some performance for the tradeoff.
Hope this clarifies the issue.  As a side note - MongoDB has non-blocking writes in persistent storage - which while awesome in its flexibility, gives people using non-blocking mode more of a false sense of security that the write will always succeed...
R


Confused about Wikipedia page on differential forms

Question: I know next to nothing about differential forms, but I saw them being mentioned repeatedly on this site, so I went to Wikipedia to try to understand what a differential form is. Most of it is going pretty smooth, but there's a paragraph I don't understand:

Since any vector $v$ is a linear combination $\sum v^je_j$ of its components, $df$ is uniquely determined by $df_p(e_j)$ for each $j$ and each $p \in U$, which are just the partial derivaties of $f$ on $U$. Thus $df$ provides a way of encoding the partial derivatives of $f$. It can be decoded by noticing that the coordinates $x^1, x^2, \dots , x^n$ are themselves functions on $U$, and so define differential 1-forms $dx^1,dx^2,\dots,dx^n$. Since $\frac{\partial x^i}{\partial x^j} = \delta_{ij}$, the Kronecker delta function, it follows that
$$ df = \sum_{i=1}^n \frac{\partial f}{\partial x^i}dx^i $$

I don't understand the bit about the coordinates being functions themselves. What does that mean?
Answer: For a vector $y=(y_1,\ldots,y_n) \in \textbf{R}^n$, the i-th coordinate function $x^i$ simply picks out the i-th entry, that is, $x^i(y)=y_i$.
Thus, if $e_1,\ldots,e_n$ is a basis for $\textbf{R}^n$, then any vector $y=(y_1,\ldots,y_n)$ can be written as
$y=\sum_{i=1}^n x^i(y)e_i$.
Comment: So, just to make sure I understand: Suppose we're working in $\mathbb{R}^2$, and instead of $x,y$ I call them $f_1, f_2$ for clarity, so they're functions from $\mathbb{R}^2$ to $\mathbb{R}$. Then we can say that $f_1(a, b) = a$ and $f_2(a,b)=b$?
Comment: Yes, that's correct.


Make the number of columns dynamic

Question: I work with django and django-tables2, and I have a question:
How I can render the number of columns dynamic?  Each column represents a year.
I aggregate some number over years, but I don't now how many years are relevant for this subset.
Sometimes there are two years so I want to get a table with 3 columns:
Data, 2011, 2012. But sometimes there are four years so I want to have a table with five columns: Data, 2009, 2010, 2011, 2012. I want to say that the number of columns depends on the data, I can't predefine the columns.
I look only for a possibility to display that data as table.
The database-table is like
The pk of the row (to identify which student)
The year for which this is the average
The value, in this example the average

Comment: I would assume OP means "make dynamic"
Answer: I misread the question; this doesn't answer it.
As I understand it, you want a value for each row for each year? Let's say each row is a student, and you want the average grade for each year for each student.
Not really an answer to the question, but an alternative (easier?) way to do this is to have a table with three columns:

The pk of the row (to identify which student)
The year for which this is the average
The value, in this example the average

Here pk and year are unique together (a student can have only one averge per year).
Do you want the database to enforce that each student has an average for each year, or can there be empty years (NULL values in your database setup)?
I don't know much about your situation, but in many cases I think this is the simpler solution, as it does not require the structure of your database to change each year, just the data in it.
Comment: Thanks for answer. My database model is like You describe. I ask now for a possibility for representation. I extend now my question.
Comment: Understood it wrongly sorry. I don't know if what you ask is possible.

Make the number of columns dynamic


Get the return values from another function - Haskell

Question: I'm trying to get the values from this function, so, when i call that function "prompt" a send a message and this function return an value according with the supposed question that i made.
But i can't receive that value, so why ?
I'm noob with haskell.
module Main (main) where
import System.IO (stdout, hSetBuffering, BufferMode(NoBuffering))
type State = Double

main::IO()
prompt::Read a =>  String ->  IO a

main = do putStrLn "Testing"
          v <- prompt "Whats your name?"
          return ()

prompt str = do putStrLn str
                valor <- readLn
                return valor

Comment: Presumably, you want `v` to be of type `String`, but the compiler has no way of knowing that.
Answer: Your problem, I believe, is confined to your type signatures.
prompt :: Read a => String -> IO a

This type signature says that prompt is a function which takes a string, does some I/O magic, and then returns a value of type a, for any readable type a the user wishes. However, your implementation gets a string from the user and returns it.
If your intention is that prompt return a string, simply change your type.
prompt :: Read a => String -> IO a

If your intention truly is that prompt return a value of some arbitrary user-specified type, you need to resolve the ambiguity when you actually read the value.
prompt :: Read a => String -> IO a
prompt str = do putStrLn str
                valor <- readLn
                return valor

You'll get an ambiguity error in main, since Haskell can't figure out what type you want v to be. This can be resolved by explicitly specifying.
v <- prompt "Whats your name?" :: IO String

(or, equivalently, IO Int for an integer, IO Double for a double, or any other readable type)
However, more than likely you intended that prompt always return a string. So I recommend the first solution, as it will be more intuitive to users.
Comment: Perhaps you were thinking of `getLine`? It *does* have type `IO String`
Comment: The `read valor` step is redundant. `readLn` already has type `Read a => IO a`
Comment: @4castle I learned something today then. I don't think I've ever used `readLn` for anything other than strings. Thanks for the correction! :)


Changing ASP.NET tag formatting

Question: When I drag a Label control to my document, I get the following code :
<asp:Label ID="Label1" runat="server" text="Label"></asp:Label>

I prefer my code to look like the following instead :
<asp:Label ID="Label1" runat="server" Text="Label" />

How can I get .NET to do this by default? I looked in Tools -> Options -> Text Editor, where you'd expect to find it, but I couldn't find anything relevant there.
Comment: Perhaps I'm wrong, but I wouldn't expect to find that option anywhere. I believe the format is defined by the control itself. Some controls that don't expect to contain anything within the tags probably already do what you're looking for by default.
Answer: Go back to Tools|Options|Text Editor, and expand the HTML node in the tree. Go to the Format node, and the click the Tag-Specific Options button. In the dialog that opens up, expand the ASP.NET controls tree and find asp:Label. You can set how you want the closing tag in the selector at the top on the right.
alt text http://philippursglove.com/stackoverflow/tagspecificclosingoption.png

Changing ASP.NET tag formatting


What's the measure of the $\angle BAC$ in the question below?

Question: For reference (exact copy of question): In $\triangle ABC$, $\angle B $ measures $135^{\circ}$.
The cevian $ BF$ is traced so that $AF = 7 $ and $FC = 18.$
Calculate $\angle BAC$, if $\angle BAC = \angle FBC$. (answer:$37^{\circ} $)
My progress:
Here is the drawing I made according to the statement and the relationships I found

$\triangle ABC \sim \triangle FBC:\\
\frac{BC}{AC}=\frac{FB}{AB}=\frac{FB}{BC}\\
\frac{BC}{25}=\frac{FB}{AB}=\frac{18}{BC}\implies BC = 15\sqrt2$
it seems to me that the path is by auxiliary lines
Comment: you are close given you already found $BC$. Drop a perp from $C$ to $AB$ extend.
Comment: @MathLover..Yeah..sometimes we try to find "miraculous" solutions but suddenly the simplest is the most efficient..thanls
Answer:
Extend side $AB$ to point $X$ such that $CX\perp AX$. Since $\angle ABC=135^{\circ}$,
$$\angle XBC=\angle XCB=45^{\circ}\implies BX=CX.$$
You have shown that $BC=15\sqrt{2}\;$ (using $\triangle ABC\sim \triangle FBC$). Hence,
$$BX=CX=15.$$
In $\triangle AXC$,
$$\sin \angle XAC=\frac{XC}{AC}$$ $$\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\implies\angle XAC=\sin^{-1}\frac{15}{25}=\sin^{-1}\frac 35$$
$$\therefore\; \angle BAC\approx 37^{\circ} $$
Comment: great view...grateful
Answer: Draw altitude from $B$ to $AC$ and let the foot be $D$. Say $DF=DB=x$. Now applying Pythagorean theorem to $\triangle BCD$ $$(18+x)^2+x^2=(15\sqrt 2)^2\implies x=3$$ So $BD=3$ and $AD=7-3=4$. It can be easily seen that $\triangle BDA$ is a $3:4:5$ triangle and hence $\theta\approx 37^\circ$
Comment: Very good...I tried to plot the height but I was using the other triangle...
Grateful


How to perform a meta regression with a random effect model?Which model should I use?How to start? (beginner)

Question: I have to perform a meta-regression, using mixed or random effects model, but I don't have any software (except Matlab) and I'm new on this topic (having a relativelly poor statistics background).
Briefly the problem I'm addressing is as follows.
I've collected several effect sized from different studies. In my case, the effect size are percentages of adoption of a specific behaviour.
For example, one study analysed a sample of 100 individuals and concluded that 35 % adopt the behaviour under analysis, whereas another study analysed a sample of 150 individuals and concluded that 45 % adopt the behaviour. My goal is to determine the average of adoption of the behaviour. All the studies are observational (no control groups).
I have to perform a meta-analysis because its study have different characteristics, as for example, the sample size or for instance the average level of education of the sample. Some of the dependent variables are dummy variables.
I read many things about meta analysis/regression but I'm so confused and I don't know how should I start my analysis, which model should I follow, what are the adequate formulation to calculate variance and the weights etc. How the heterogenity is included in the model?
I thought about using this model:
y=b0+b1x+b2x+...+u+e (fixed+random effect model)
Is the way I'm thinking correct? Do you have any suggestion for me? If not, what is the step-by-step procedure? (in matlab or excel).
I would appreciate if you could guide me on this analysis.
I'm sorry if I wasn't clear or specific enough.
Comment: Velcome to our site!
Answer: There is a lot to say about what you want to do ! So I will adress what I know:

First, what you call effect size does not seems to be a standardized effect size. I mean that % from different studies can't be compared that easily. I suggest you consult the classic book of Borenstein et al to learn a bit more about what standardized effect size you should use:
Borenstein, M., Hedges, L. V., Higgins, J. P., & Rothstein, H. R. (2011). Introduction to meta-analysis. John Wiley & Sons.
Second, I think you need to read a bit more about meta-analysis. The terminology is somewhat different from what you can find in classic ANOVA. You will have to decide between a fixed effect and a random effect model. That decision will have strong implications on the way you weight your effect size.Again, read Borenstein et al 2011.
Finally. for actually doing the analysis, I suggest you take a look at the Metafor package in R (http://www.metafor-project.org/doku.php/metafor) and at this reference article:
Viechtbauer, W. 2010. Conducting meta-analyses in R with the metafor package. — Journal of statistical software 36:
It will cover some of the question you need to answer before actually doing a model.

Good luck !
Comment: Thank you for your thoughtful comments and the references you provide.  Welcome to our site!
Comment: Thank you for your suggestions for reading. I think it will help me.


Converter decimal para binário - python

Question: Olá pessoal sou novo em python meu código abaixo exibe os valores da tabela ASCII para uma string digitada. Como posso pegar estes valores e converter para binário
valor = input("Insira o valor a ser criptografado: ")
print(valor)
list=[ord(ch) for ch in valor]
print("Valores da tabela ASCII para:", valor, "são:", list, ".")

resultado (VALOR DIGITADO = teste):
Valores da tabela ASCII para (VALOR DIGITADO) são: [84, 69, 83, 84, 69] .
Agora preciso pegar 84 >> passar para binário e assim sucessivamente
por que posteriormente vou fazer uma função com uma chave e criptografar os valores etc.
Comment: Não é só fazer `bin(84)`?
Comment: Não sei te responder amigo , por isso perguntei, mas pesquisando sua dica..funcionou muito bem. Obrigado!
Comment: @Woss coloque sua sugestão como resposta para que ele possa escolher como resposta correta e fechar a pergunta. Ou então LeoMouraIOT coloque o que fez para resolver e marque como resposta correta para fechar a pergunta.
Answer: A função "bin" dá a representação binaria de um número como uma string. Mse ssa representação como string é útil apenas para mostrar os "0" e "1" na tela, para serem vistos por pessoas. Internamente, os algoritmos que trabalham com as letras, sejam de criptografia, ou outros, tem que usar os números - um número não tem uma "base" ele é uma quantidade - a representação dele como texto vai acontecer naturalmente em decimal, e a representação do número para os algoritmos que manipulam números bit a bit já é em binário.
O que você precisa, sim, é converter seu texto para uma codificação em Bytes. Se você usar só o "ord", você tem o codepoint Unicode que representa seu caractere, mas esse número - o codepoint- não tem uma largura fixa, e aí a maioria dos algoritmos de criptgrafia não vai funcionar (você pode assumir cada codepoint como uma largura de 32 bit, o equivalente  a usar utf-32, mas vai gastar espaço).
Resumindo, se pretende trabalhar com o texto com uma sequência de números, o melhor é transformar em um objeto do tipo "bytes", usando uma codificação adequada (por exemplo, "utf-8", que cobre todos os caracteres conhecidos). Um objeto "bytes" se você acessa cada elemento, já te dá o número, e não um objeto bytes de comprimento "1":
In [138]: for x in "maçã".encode("utf-8"):
     ...:     print(x, end=", ")
     ...:
109, 97, 195, 167, 195, 163,

Já, voltando na pergunta original, se você quiser, para fins de visuaçização, ver a representação binária dos números, é só usar a função "bin":
In [140]: for x in "maçã".encode("utf-8"):
     ...:     print(x, bin(x), sep="\t")
     ...:
109     0b1101101
97      0b1100001
195     0b11000011
167     0b10100111
195     0b11000011
163     0b10100011

Comment: esse negócio de codificação é IMPORTANTÌSSIMO de entender, independente de você querer trabalhar com criptografia, etc... recomendo ler com muita atenção esse artigo aqui: https://papacharliefox3.wordpress.com/2009/03/28/o-minimo-de-conhecimento-basico-que-todo-desenvolvedor-de-software-deveria-saber-sem-qualquer-sombra-de-duvida-sobre-unicode-e-character-sets-sem-desculpas-esfarrapadas/
Answer: Sei que a resposta anterior já responde suficientemente a questão. Porém, resolvi a questão com uma nova roupagem. O código é:
valor = input('Insira um valor a ser criptografado: ')
for c in valor:
    v = ord(c)
    print(c, v, f'{v:b}', sep='\t')

Observe que neste código não utilizei a função bin(). Neste código utilizei f-string formatando para binário. Desta forma, podemos controlar a exibição do prefixo "0b".
A parte do código que de fato converte um valor para binário é:
f'{v:b}'

Utilizando esta notação o valor binário será exibido sem o prefixo 0b.
Agora, se preferirmos exibir o prefixo 0b, basta utilizar o carácter "#" imediatamente antes da letra "b". Neste caso o código ficaria:
f'{v:#b}'

Se preferirmos que todos os valores binários se apresentem com 8 dígitos, podemos utilizar o seguinte formato:
f'{v:08b}'

Desta forma, todos os valores binários terão 8 dígitos.
Comment: para exercitar as f-strings, pode aproveitar e colocar um exemplo de como garantir 8 dígitos binários  - se olhar no exemplo da minha resposta, as letras "ma" tem só 7 dígitos - pderiam estar com o 0 na frente pra todas terem a mesma largura.
Comment: @jsbueno, formatação de valores binários com `8 dígitos`, realizada com sucesso.

Converter decimal para binário - python


Will the info I want about an incoming email survive in the envelope?

Question: I have a situation where emails bound for several recipients will arrive in one mailbox.
I want to go through and deal with them according to who they were sent to, but I'm not sure I will always have the correct info.
Suppose I have one recipient  firstname.lastname@example.com .
if someone bcc's him on an email, I know that fred will not see any To: field in his email BUT I will be able to find   email@example.com  in the envelope.  No problem.
Now, what if fred has some email forwarding service.  Or lets say he asks gmail to forward a copy of every email he receives at gmail on to his firstname.lastname@example.com address.
The original message that was sent to him may have said  firstname.lastname@example.com in the envelope, and will still say it in the To: but once gmail has forwarded it, can I be sure I will always find firstname.lastname@example.com in the envelope for the "final leg" of its journey ?
email@example.com it would be no use to me, you see.
Or will I find (somewhere in the envelope) references to both the gmail AND the domain1 addresses ?
TIA
Answer: I believe MTAs add Delivered-To or X-Forwarded (or similar, depends on the MTA) for the forwarded message. To: headers usually stay as-is.


How do I use PickleDB with Rocket/Juniper Context?

Question: I'm trying to write a Rocket / Juniper / Rust based GraphQL Server using PickleDB - an in-memory key/value store.
The pickle db is created / loaded at the start and given to rocket to manage:
fn rocket() -> Rocket {
    let pickle_path = var_os(String::from("PICKLE_PATH")).unwrap_or(OsString::from("pickle.db"));
    let pickle_db_dump_policy = PickleDbDumpPolicy::PeriodicDump(Duration::from_secs(120));
    let pickle_serialization_method = SerializationMethod::Bin;

    let pickle_db: PickleDb = match Path::new(&pickle_path).exists() {
        false => PickleDb::new(pickle_path, pickle_db_dump_policy, pickle_serialization_method),
        true => PickleDb::load(pickle_path, pickle_db_dump_policy, pickle_serialization_method).unwrap(),
    };

    rocket::ignite()
        .manage(Schema::new(Query, Mutation))
        .manage(pickle_db)
        .mount(
            "/",
            routes![graphiql, get_graphql_handler, post_graphql_handler],
        )
}

And I want to retrieve the PickleDb instance from the Rocket State in my Guard:
pub struct Context {
    pickle_db: PickleDb,
}

impl juniper::Context for Context {}

impl<'a, 'r> FromRequest<'a, 'r> for Context {
    type Error = ();

    fn from_request(_request: &'a Request<'r>) -> request::Outcome<Context, ()> {
        let pickle_db = _request.guard::<State<PickleDb>>()?.inner();
        Outcome::Success(Context { pickle_db })
    }
}

This does not work because the State only gives me a reference:
26 |         Outcome::Success(Context { pickle_db })
   |                                    ^^^^^^^^^ expected struct `pickledb::pickledb::PickleDb`, found `&pickledb::pickledb::PickleDb`

When I change my Context struct to contain a reference I get lifetime issues which I'm not yet familiar with:
15 |     pickle_db: &PickleDb,
   |                ^ expected named lifetime parameter

I tried using 'static which does make rust quite unhappy and I tried to use the request lifetime (?) 'r of the FromRequest, but that does not really work either...
How do I get this to work? As I'm quite new in rust, is this the right way to do things?
Answer: I finally have a solution, although the need for unsafe indicates it is sub-optimal :)
#![allow(unsafe_code)]
use pickledb::{PickleDb, PickleDbDumpPolicy, SerializationMethod};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::env;
use std::path::Path;
use std::time::Duration;

pub static mut PICKLE_DB: Option<PickleDb> = None;

pub fn cache_init() {
    let pickle_path = env::var(String::from("PICKLE_PATH")).unwrap_or(String::from("pickle.db"));
    let pickle_db_dump_policy = PickleDbDumpPolicy::PeriodicDump(Duration::from_secs(120));
    let pickle_serialization_method = SerializationMethod::Json;
    let pickle_db = match Path::new(&pickle_path).exists() {
        false => PickleDb::new(
            pickle_path,
            pickle_db_dump_policy,
            pickle_serialization_method,
        ),
        true => PickleDb::load(
            pickle_path,
            pickle_db_dump_policy,
            pickle_serialization_method,
        )
        .unwrap(),
    };
    unsafe {
        PICKLE_DB = Some(pickle_db);
    }
}

pub fn cache_get<V>(key: &str) -> Option<V>
where
    V: DeserializeOwned + std::fmt::Debug,
{
    unsafe {
        let pickle_db = PICKLE_DB
            .as_ref()
            .expect("cache uninitialized - call cache_init()");
        pickle_db.get::<V>(key)
    }
}

pub fn cache_set<V>(key: &str, value: &V) -> Result<(), pickledb::error::Error>
where
    V: Serialize,
{
    unsafe {
        let pickle_db = PICKLE_DB
            .as_mut()
            .expect("cache uninitialized - call cache_init()");
        pickle_db.set::<V>(key, value)?;
        Ok(())
    }
}

This can be simply imported and used as expected, but I think I'll run into issues when the load gets to high...


Obter X e Y da tela usando PYTHON

Question: Eu quero criar um bot(macro) que execute algumas tarefas de click, para isso estou usando o pyautogui em python!
Porém não tenho muita experiencia em X e Y, e ficar testando isso manualmente e chato.
Eu gostaria, de obter o x e y clicando na tela, por exemplo, eu dou um click em tal local da tela e apresente no console o X e Y do local do click.
Possível?
Answer: Bom uma forma de fazer isso em pyautogui seria basicamente assim:
#pega o retorno da posicao atual de x e y do mouse e passa o valor da tupla para as duas variaveis
x, y = pyautogui.position()
print "Posicao atual do mouse:"
print "x = "+str(x)+" y = "+str(y)

#retorna True se x & y estiverem dentro da tela
print "\nEsta dentro da tela?"
resp = pyautogui.onScreen(x, y)
print str(resp)

Referência: pyautogui
Answer: Uma solução rápida usando PyUserInput e sem entrar em especificidades de sistema operacional: instâncias de mouse possuem o método position(), que retorna a posição (X, Y) a cada chamada:

$ pip install git+https://github.com/PyUserInput/PyUserInput.git

>>> import pymouse
>>> mouse = pymouse.PyMouse()
>>> mouse.position()
(562, 528)
>>> mouse.position()
(1259, 195)
>>> mouse.position()
(157, 259)

Answer: Fz muito tempo que voce perguntou mais editei o codigo acima para usuarios inicantes. So copiar e jogar no IDLE ou IDE.
codigo:
import pyautogui
import time
#pega o retorno da posicao atual de x e y do mouse e passa o valor da tupla para as duas variaveis
print('Posicione o MOUSE')
time.sleep(2)
x, y = pyautogui.position()
print ("Posicao atual do mouse:")
print ("x = "+str(x)+" y = "+str(y))

#retorna Truee se x & y estiverem dentro da tela
print ("\nEsta dentro da tela?")
resp = pyautogui.onScreen(x, y)
print (str(resp))

Comment: Não entendi a necessidade de copiar uma resposta apenas para adicionar um `print` e parênteses nos outros `print`s
Answer: Copiei o primeiro código dos comentarios e coloquei dentro de um While:
import pyautogui
while True:
input('POSICIONE O MOUES E EM SEGUIDA TECLE ENTER: ')
#pega o retorno da posicao atual de x e y do mouse e passa o valor da tupla para as duas
x, y = pyautogui.position()
print( "Posicao atual do mouse:")
print("x = "+str(x)+" y = "+str(y))
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Obter X e Y da tela usando PYTHON


How to have restricted time duration in antd TimePicker?

Question: I am using antd TimePicker in my application. The requirement is to allow user to select time from a specific time duration and not from 24 hours. I tried using hoursStep but that only gives intervals between the hours.
Currently the behaviour is:

Here the list shows from 00 to 23 if I scroll further which is default. Is there a way I can restrict this to 08 to 17 i.e only for a sepcific time duration.
Any help would be appreciated.
Answer: Okay so here is the fix that I did, first I disabled the hours I did not want using the property hoursDisabled.
disabledHours={ () => [0, 1, 2, 3, 4, 5, 6, 7, 18, 19, 20, 21, 22, 23] }

This disabled the hours. Then I used another property hideDisabledOptions and set it to true to also hide the disabled hours. And voila! That did it.
Answer: For minutes and seconds interval you can use following two properties.
minuteStep={15} secondStep={10}


Why does my site redirect to www when I go to example.com but not when I go to https://example.com

Question: I have a site that I'm trying to re-direct to www subdomain.
I'm using Namecheap as my URL registar and my DNS.
I've set up this rule

When I navigate to paperbet.site, it goes to https://www.paperbet.site - which is what I'm after.
However, when I navigate to https://paperbet.site, it does not resolve to www subdomain.
What is the difference between https://url.com and url.com - and why won't the former follow the redirect domain rule?
Answer: Namecheap's URL redirection doesn't support HTTPS. Do the redirect yourself in your own web server.


Piano Concertos: Why is Brahms 2 considered more mature than Rachmaninoff 3?

Question: These two titanic concertos are two of the most difficult often played concertos in piano literature, so they are talked about a lot. In most discussions, forums, or interviews with pianists I've seen, many pianists really love both.
In Alexis Weissenberg's commentary on the Rach 3, he writes "the Rachmaninoff Third has kept, and will keep forever and without the slightest doubt, a place apart in my heart.  I still think it is the most gloriously written concerto for the piano." Most everybody calls it the hardest concerto that is performed often (perhaps due to the movie Shine), and a ton of people love, admire and respect (and fear) it.
Almost everything I've read about the Brahms 2 describes it as a very mature and grand work, requiring only the best and most mature musical interpretations. On the other hand, I've never seen the Rach 3 described as mature; glorious, saccharine, passionate, beautiful yes, but never mature. A lot of pianists seem to enjoy performing Rach's works, but they too will say that it's just "excessive climaxes" or "sugary drivel" or something like that. Furthermore, people will never attribute "musical depth" to Rachmaninoff, but I've seen it a couple times in reviews of composers ranging from Brahms to Scriabin.
Why, in these two very technically difficult, powerful, popular, romantic, and dare I say similar works, is there such a seemingly unanimous opinion people think that Brahms's concerto is mature and musical while Rachmaninoff's is less mature, "frivolous", "schmaltzy", or "film score - esque"? Given that this opinion is so prevalent, is there something inherent about maturity in music that is objective and not subjective? Should maturity be something that music should strive for?
I'm intrigued by one of the ideas below that Brahms's stature as a composer is due not only to his music but also and maybe even more importantly his critics. If it is so that critics are so powerful and can sway opinions ("incorrectly" or "correctly") centuries after their deaths, isn't that super detrimental to excellent but unlucky composers?
(This question isn't limited to these two composers; late Beethoven is almost always described as extremely profound or transcendental, but rarely (if ever) Rachmaninoff or Liszt)
~~ I know this is a subjective question, but I hope that I've asked it well enough that it is a more constructive subjective question, which is allowed by site rules.
Comment: Interesting question. One answer might be found in music history: thanks to music critics like Eduard Hanslick, Brahms had a reputation of being the height of refined (and perhaps "mature") music, and perhaps this sentiment has extended to the present. The absolute music debate may also be rearing its head here.
Comment: I'm really looking forward to reading answers. Is it reasonable & correct to interpret this question as asking: *for those who perceive Brahms 2 more mature than Rach 3 (a consensus), what is the basis/evidence/reason for their view?*
Comment: You cannot hope to find an objective comparison of these two works based *solely* on their content. The mere fact that Brahms was 12 years older than Rach at the time of composition, and that it was published 28 years earlier, will inevitably influence people's judgement of their merit, and is impossible to disentangle from their perception of the relative merits.
Comment: @jdjazz yes, basically
Comment: @jdjazz it seems like there are currently not that many answers, or views. Do you think this question is worth a bounty?
Answer: Calling the Brahms Second "mature", or the Rachmaninoff Third "film score - esque" is of course subjective. These old chestnuts can often be traced back to prominent critics whose work has simply been echoed by later generations. It is after all much easier to copy an authority's opinion than to form one's own.
You can check the old Grove's Dictionary entry for Rachmaninoff for an example of the conceited view of his music once prevalent. It was considered more tasteful to suggest an effect than to execute it outright. Rachmaninoff wore his heart on his sleeve and his music didn't please those for whom great restraint was a virtue. Deriding his music through comparison to film scores is ridiculous because it was he who influenced the film score composers.
I have a perspective on the Brahms Second as I studied it for a competition as a piano student. I will comment on it as a partial answer. I have read through but not studied the Rachmaninoff Third so have no perspective on it other than the opinion that it is much more difficult than the Brahms Second technically. Horowitz in his interview book with David Dubal even said that "the Brahms Second is not difficult at all", but let's not take him as the normal case!
The technical difficulties of the Brahms Second are generally unrewarding to the player in terms of effect. Subjectively, glittering virtuosity from the pianist-composers like Rachmaninoff and Liszt sounds good to the player, feels good to play, and on a superficial level impresses the audience. Much of the difficulty in the Brahms Second occurs in mere accompaniments, in passages which are far more difficult to play than they sound, and in arguably unpianistic writing in which ugliness or roughness of tone is very difficult to avoid. There is no easy success awaiting someone who studies this concerto. This suggests one motivation for calling it "mature".
The integration of piano and orchestra in the Brahms Second is at a high level. I can't find the reference just now, but I believe the Brahms concertos were derided by the opposing Liszt/Wagner faction as chamber music on a large scale. This judgement has been repeated many times since, but came to be seen as a virtue. Before studying this concerto, I had played his A major and C minor trios. The concerto felt like a continuation of the same kind of work. As I hinted above, much of the work in this concerto is spent in unforgiving accompaniment. Superficially, the chamber music players willingly submitting to the common cause might appear more "mature" than the flashy soloists insisting on their own part's prominence.
The conception of the Brahms Second is that of an older person, in my opinion. Over and above the general eschewal of obvious virtuosity, consider the crucial role of the last movement. How does it relate to the rest of the concerto? There is this comment by Tovey in one of his essays:

What tremendous triumph shall it express? Brahms's answer is such as
  only the greatest of artists can find; there are no adequate words for
  it (there never are for any art that is not itself words - and then
  there are only its own words). But it is, perhaps, not misleading to
  say here, as so often of Beethoven's finales, something like this: 'We
  have done our work - let the children play in the world which our work
  has made safer and happier for them.'

The music of a "mature" person, then. Tovey was a very influential critic in his time. These views spread easily.
I've suggested reasons from the points of view of restraint, pianism, composition, and conception for why this "mature" label might have come about.
Comment: From a performer's perspective: maturity is just a by-product. It makes sense to seek constant growth, but young instrumentalists can suffer from the attempt to accelerate the process. Brendel spoke of an important realization early in his life that all his favorite performers happened to be at least 40 or 50 years old. He concluded that he had to cultivate patience, work constantly, and set himself a goal twenty years in the future rather than two. Youth is the time for piling up repertoire and solving every possible technical problem. [cont]
Comment: This opportunity can be lost if instead of mastering Chopin etudes, for example, a 15-year-old agonizes for months over the start of Schubert D960. In general, a 20-year-old debutant may compete with a 40-year-old professional in virtuosity but very, very rarely in richness of playing. Unfortunately, the exigencies of the modern competition circuit mean that young players feel they must grapple with the richest things in the repertoire (like Op111) because their competitors will if they don't. This is happening all the time.
Comment: Thank you for your answer on this old post! Your ideas are very interesting and a valuable addition to the discussion.  Rachmaninoff's 4th concerto is I think more "restrained" and less scintillating, and with a more active piano part (https://www.wrti.org/post/pianist-daniil-trifonov-talks-about-very-difficult-rachmaninoff-concerto). I wonder how that one will compare with Brahms ;) Do you think (personal opinion of course) maturity should be something musicians and composers strive for?
Answer: Thanks for an interesting question.
The music of Beethoven and Brahms are described as much by their biographies as by the music itself.  I think of Brahms 2 as valedictory, especially when one compares it to the torturous path followed by his first piano concerto.  It is definitely a mature work but I think the context it fits into in Brahm's life and work makes mature just that much more apt a description.  The words triumphant or mature just naturally seem to lend themselves to Brahms the person as much as to any of his creations.
Beethoven is an almost mythological personage with an epic backstory.  The late string quartets are so unusual that the usual adjectives don't really apply; combine this with the totally soundless environment of their creator and you get adjectives like otherworldly.
Rachmaninoff, on the other hand, doesn't have nearly this much emotion wrapped up in his biography.  The fact that he created a lot of his finest works for his own concerts can, under a certain light, come off as rather businesslike.  I don't think his works have the depth of emotion to begin with and combine that with a lack of backstory drama, he suffers by comparison with a Brahms or a Beethoven. Its almost like he was there to sell concert tickets and the more bang and wow and flash the better his returns, bang/wow/flash not being totally consistent with beauty and artfulness.  I don't know enough about Rachmaninoff's bio or his music but I'd guess that his work wasn't of such depth that you can say it matured as he went along.
You mention Liszt and that's an odd one.  His best works are as full of beauty and emotion as anything in, say, Chopin.  But whereas nearly everything of Chopin's rather smallish output is a gem, Liszt suffers because of the substantial volume of works he produced.  Many of his works, like Rachmaninoff's, were simply commercial ventures designed to wow his recital audiences.  And Liszt himself, at least in the popular mind, was a successful and somewhat spoiled artist-ocrat, something that no doubt enters into his image today.  And as far as maturing, Liszt's later piano work was almost experimental and not well understood.
Comment: I think many would disagree with the claim that Rach didn't have as much of a emotive backstory; it was the a poorly conducted premiere of his 1st Symphony that led to a 3 year long depression where he refused to write anything. It haunted the rest of his life, leading him to rewrite or cut many of his major works (symphony 2, 4th piano concerto, sonata 2, etc). You do raise an interesting point about showiness. Both Rach and Liszt were considered one of the greatest pianists alive at their time, so perhaps their ability to profit off of their virtuosity paints a negative view of their works.
Comment: @LukeSawczak he wrote a 50 minute long trio for the death of Tchaikovsky, but it's relatively unknown. He also fled his home (on a sled, to Finland, with a suitcase of manuscripts and his family) because of the Stalinist regime, and I personally think his work reflects the sadness of being completely out of place, culturally and musically. I'm sure he had his fair share of tragedies, and I don't think it completely explains the difference between Brahms and Rach.
Comment: A late comment I know, but thanks to Moiseiwitsch and Horowitz the general biographical view today is that the First Symphony problems were secondary in the formation of Rachmaninoff's character, and that the crucial event in his early life was the uprooting from his opulent, noble beginnings to a nasty little flat when he was ten years old, combined with family tragedies at that time. This early home, not Russia itself, was what he missed, and what Moiseiwitsch interpreted as the basis for the "Return" prelude Op 32 No 10.
Comment: @D.R. An artist who considered the rejection of their work to be enough of an emotional grounding for their next work would be a bit of a ham. Not that I know enough about Rachmaninov to say that comment applies to him, but artistic failrue isn't the same as some of these musicians (deaths of lovers, friends, children for example...).
Comment: @D.R. Fair enough.


return value in compare() function of SplHeap class

Question: "Hello Everybody"
in the first note of php manual : splheap class there is example I can't understand the line of return in compare() function of splheap subclass
the line I can't understand
return $values1[0] < $values2[0] ? -1 : 1;

The example :

To have a good idea what you can do with SplHeap, I created a little example script that will show the rankings of Belgian soccer

<?php
/**
* A class that extends SplHeap for showing rankings in the Belgian
* soccer tournament JupilerLeague
*/
class JupilerLeague extends SplHeap
{
    /**
     * We modify the abstract method compare so we can sort our
     * rankings using the values of a given array
     */
    public function compare($array1, $array2)
    {
        $values1 = array_values($array1);
        $values2 = array_values($array2);
        if ($values1[0] === $values2[0]) return 0;
        return $values1[0] < $values2[0] ? -1 : 1;
    }
}

// Let's populate our heap here (data of 2009)
$heap = new JupilerLeague();
$heap->insert(array ('AA Gent' => 15));
$heap->insert(array ('Anderlecht' => 20));
$heap->insert(array ('Cercle Brugge' => 11));
$heap->insert(array ('Charleroi' => 12));
$heap->insert(array ('Club Brugge' => 21));
$heap->insert(array ('G. Beerschot' => 15));
$heap->insert(array ('Kortrijk' => 10));
$heap->insert(array ('KV Mechelen' => 18));
$heap->insert(array ('Lokeren' => 10));
$heap->insert(array ('Moeskroen' => 7));
$heap->insert(array ('Racing Genk' => 11));
$heap->insert(array ('Roeselare' => 6));
$heap->insert(array ('Standard' => 20));
$heap->insert(array ('STVV' => 17));
$heap->insert(array ('Westerlo' => 10));
$heap->insert(array ('Zulte Waregem' => 15));

Can you help me please to understand this line ??
Answer: It's a ternary statement. It means:
if ($values1[0] < $values2[0]) {
    return -1;
} else {
    return 1;
}

The ternary operator is not specific to SplHeap. It's just a general use PHP operator.
Answer: It's a conditional ternay operator ?(a ternary if).
How does it works?:

In computer programming, ?: is a ternary operator that is part of the
  syntax for a basic conditional expression in several programming
  languages. It is commonly referred to as the conditional operator,
  inline if (iif), or ternary if.
It originally comes from CPL, in which equivalent syntax for e1 ? e2 : e3
  was e1 → e2, e3.
Although many ternary operators are possible, the conditional operator
  is so common, and other ternary operators so rare, that the
  conditional operator is commonly referred to as the ternary operator.

Source: Wikipedia
For example, using your code:
return $values1[0] < $values2[0] ? -1 : 1;

It's similar to say:
if($values1[0] < $values2[0]){
     return -1;
}
else{
     return 1;
}

The ? works as a then, and the : works as a else


Probability that the second ball is red

Question: n balls, each equally likely to be red or black, are added to a box containing one red ball. Given that the first ball withdrawn from the box is red, what's the probability that the second ball withdrawn from the box is red?
I figured that the answer is (n+3)/(2n+4), but I don't know how to prove that.
Comment: Well, if you "figure" that's the answer, then you must have some reason.  Why don't you show us your reasoning, and we can help with the rest.
Answer: Let $A_1$ denote the event that the first chosen ball is red; and $A_2$ the event  that the first chosen ball is red. I assume no replacement.
Let $B_k$ (for $k \in \{0,...n\}$) denote the event that $k$ of the $n$ balls added to the box are red.
Then
$$P(A_2| A_1) = \dfrac{P(A_1 \cap A_2)}{P(A_1)}.$$
Now
$$P(A_1 \cap A_2)  = \sum_{k=0}^n P(A_1 \cap A_2|B_k)P(B_k) = \sum_{k=1}^n P(A_1 \cap A_2|B_k)P(B_k),$$
the second inequality being true because you can't pick two red balls if there is only one in the box.
Now
$$P(A_1 \cap A_2|B_k) = \dfrac{k(k+1)}{n(n+1)}, $$
and
$$P(B_k) = {n \choose k}(\dfrac{1}{2})^n.$$
So
$$P(A_1 \cap A_2) = \sum_{k=1}^n \dfrac{k(k+1)}{n(n+1)} {n \choose k}(\dfrac{1}{2})^n.$$
By similar reasoning,
$$P(A_1) = \sum_{k=0}^n \dfrac{k+1}{n+1} {n \choose k}(\dfrac{1}{2})^n.$$
It shouldn't be too hard to calculate these sums explicitly. Then you just need to take the quotient.
I hope this helps,
Frank.
Comment: I arrived at your answer too. But I don't know how to calculate the sums.
Answer: The number $Y$ of added red balls has binomial distribution, parameters $n$ and $\frac{1}{2}$. We assume that the withdrawing is done without replacement.
Let $A$ be the event the first ball withdrawn is red, and let $B$ be the event the second ball withdrawn is red. We want $\Pr(B|A)$, which is $\Pr(A\cap B)/\Pr(A)$.
Now compute. The probability of $A$ is
$$\sum_0^n \frac{k+1}{n+1}\binom{n}{k}\frac{1}{2^n}.\tag{1}$$
The probability of $A\cap B$ is
$$\sum_0^n \frac{(k+1)(k)}{(n+1)(n)}\binom{n}{k}\frac{1}{2^n}.\tag{2}$$
Divide.
That's the answer, but presumably we want to simplify. To calculate $\Pr(A)$, we want to calculate $\sum_0^n (k+1)\binom{n}{k}$.
Recall that $(1+x)^n=\sum_0^n \binom{n}{k}x^k$ and therefore $x(1+x)^n=\sum_0^n \binom{n}{k}x^{k+1}$. Differentiate, and set $x=1$. We find that $\sum_0^n(k+1)\binom{n}{k}=2^n+n2^{n-1}=(n+2)2^{n-1}$.
Thus $\Pr(A)=\frac{n+2}{2(n+1)}$.
A similar but somewhat more tedious argument gets us a closed form for $\Pr(A\cap B)$. Differentiate twice instead of once.
Answer: Hint:  You can imagine that the ball that started out in the box is green, and it is the first ball drawn.  Then what is the chance the next ball drawn is red?

Probability that the second ball is red


For binomial success / fail data, how to calculate if the time since last success is out of the normal range

Question: Struggling to figure this out.
I have data sets that are essentially
ObjectId, Date, Pass/Fail (1/0)
The data is normally daily.
What I want to figure out is IF the number of days since the last pass is normal, or, out of the ordinary
For some of the data, it might show that we, on average, it passes every day..  In this case, a fail in the last 1 or 2 days is out of the ordinary
For other data, we might only have a pass on average every 10 days.  For this data, what is out of the ordinary?
I tried just averaging the pass/fails into an average number.  But in this case, roughly 50% of cases end up showing on my report
So - Any ideas for a formula to calculate some confidence that a particular object has had too many days since it's last pass? (based on the average number of days that it usually passes)
Let's say, for sake of argument that I look at a 90 day window.
The current things I have tried to calculate is:
Number of of passes divided by total tries (pass rate)
Number of total tries divided by passes (avg days between passes)
I assume some standard deviation calculation comes into play?
Answer: If the ordinary probability of Pass is $p,$ then you are right that on average you should expect a Pass every
$1/p$ days. So roughly speaking, if $p = 1/10$ you might start to get suspicious something is wrong if you haven't seen a pass in 'many' more than 10 days.
Here is one way to quantify 'many'. The probability of a Fail on any one day is $1-p$ and the probability of a run of $x$ consecutive failures is $(1-p)^x,$ so maybe you should get
suspicious if $(1 - p)^x < .05.$
For $p = 1/10 = 0.1,$ that's about 29 days, because $0.9^{28} = .052$ and $0.9^{29} = 0.047 < .05.$ [Computations in R.]
<code>.9^28;  .9^29
## 0.05233476
## 0.04710129
</code>
For $p = 1/5 = 0.2,$ you should sound the alarm at about 14 successive Fails:  $0.8^{14} = 0.044.$
Using the same criterion, you should suspect that $p$ must be below $1/2$ if you see five fails in a row.
Of course, you might choose an 'error' probability
other than $0.05$ and then results would differ accordingly.
Note: More formally, this is a test the hull hypothesis $H_0: p = p_0$ against the alternative
$H_1: p < p_0$ at the 5% level.
The relevant probability distribution is the geometric distribution. Notice that there are two forms of the distribution, one counting the number of tosses until the first Pass appears, and the other counting the number of Fails before the first Pass. (In R, the grometric distribution uses the latter formulation.)
Comment: Note - Although I originally asked this nearly 3 years ago...   I am putting it to use today in a new setting...   Initial trails seem to be working great, in my case I am using a very small threshold.. (1-p)^x < .`0.000001` to be exact.   I have a service that sends data at some frequency...   I am using this to determine if this service has likely stopped or not.
Comment: This is not the setting of a single test on a single sample: it's an ongoing *process.*  Different concepts and methods need to be applied (motivated, perhaps, by quality control techniques).


Disable navigation keys on datagridview cell edit

Question: I am displaying a list box with suggestion while typing in datagrieview cell. So I want when I press Down Arrow key, focus should go to the first item of list box. But focus is going to below cell of current cell as a default funcationality of datagridview. I have tried this...
private void dgvHP_OPDPrescriptionDiagnosis_Detail____KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyData & Keys.KeyCode)
        {
            case Keys.Up:
            case Keys.Right:
            case Keys.Down:
            case Keys.Left:
                e.Handled = true;
                e.SuppressKeyPress = true;
                break;
        }
    }

It's not working.
Comment: Have you tried enabling auto-complete mode of TextBox instead of showing a ListBox?
Comment: @RezaAghaei I don't want AutoComplete.
Answer: The method to override is ProcessDataGridViewKey which is responsible for navigation keys:
public class DataGridView2 : DataGridView
{
    protected override bool ProcessDataGridViewKey(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Down)
        {
            // return true; // do nothing
            // or
            return false; // pass it to the editing control
        }
        return base.ProcessDataGridViewKey(e);
    }
}

If you passed the key to the editing control, then the next event to handle is EditingControlShowing which raises when the editing control is showing:
private void DataGridView1_EditingControlShowing(object? sender,
    DataGridViewEditingControlShowingEventArgs e)
{
    //Check if the editing column is the one you are interested
    if (dataGridView1.CurrentCell.ColumnIndex == 0)
    {
        var txt = (DataGridViewTextBoxEditingControl)e.Control;
        txt.KeyDown -= Txt_KeyDown;
        txt.KeyDown += Txt_KeyDown;
    }
}
private void Txt_KeyDown(object? sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Down)
    {
        e.Handled = true;
        if (listBox1.SelectedIndex + 1 <= listBox1.Items.Count - 1)
        {
            listBox1.SelectedIndex += 1;
        }
    }
}


Apache serving different directory

Question: I have defined a single vhost configuration (see below) for a domain. All HTML files in the root get served properly. But I can't access any files within a particular sub-directory called 'icons'.
example.com/index.html or example.com/pix.jpg work fine but example.com/icons/somefile.jpg gives a 'File not found error' despite the file actually being there.
Moreover, when I try to access example.com/icons/ , instead of getting an error, a file listing of the apache icon directory is displayed!
example.com should serve from /var/www/example.com/public and
example.com/icons/ should serve from /var/www/example.com/public/icons but instead a directory listing of /var/www/icons is shown.
example.com/test/somefile.html works and serves correctly from /var/www/example.com/public/test
Another funny this is, directory listing is disabled but a listing of the icon directory is still displayed for example.com/icons.
DocumentRoot "/var/www/html"

# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
    Order deny,allow
    Deny from all
    Options None
    AllowOverride None
</Directory>

<VirtualHost *:80>
     ServerAdmin firstname.lastname@example.com
     ServerName example.com
     ServerAlias www.example.com

     DocumentRoot /var/www/example.com/public

     <Directory /var/www/example.com/public>
     Order allow,deny
     Allow from all
     </Directory>

     WSGIDaemonProcess app display-name=%{GROUP}  processes=2 threads=5 maximum-requests=5
     WSGIProcessGroup app

     WSGIScriptAlias /app /var/www/app/app.wsgi

     <Directory /var/www/app>
     Order allow,deny
     Allow from all
     </Directory>

     ErrorLog /var/www/example.com/logs/error.log
     CustomLog /var/www/example.com/logs/access.log combined
</VirtualHost>

Answer: hehe..
search in your apache config directory for /icons. you'll probably find in one of the files something like:
Alias /icons/ "/usr/share/apache2/icons/"

in debian/ubuntu world this is set in /etc/apache2/mods-enabled/alias.conf
files served from that directory are used for icons in directories listings generated by apache. just comment out this line and restart the server.
Comment: For all XAMPP users: I've found an *icons* alias line in `apache/conf/extra/httpd-autoindex.conf`. If you don't find it, it'll be the best to search in the whole *conf* directory (e.g. using Notepad++).

Apache serving different directory


How/What to Practice to Get Better at Shifting Between Bar Chords on Different Frets?

Question: How/what can I practice to get better at playing a bar chord on the 4th fret, then a bar chord on 9th fret, for example, without it sounding like there's a 'gap' between them?
I've been practicing by playing a bar chord up and down each fret, one by one, sort of like a chromatic scale, but I'm not sure that's the best way to get better at what I'm wanting to do.
Thank you.
Answer: I'm guessing you'll be using exactly the same shape for the two chords - probably A♭ and D♭. The only way is practice, lots of it. Using the same shape, release the pressure of fingers, but keep in contact with the strings, just, and slide up as if on rails, before pressing down on the new position. Get so you can do it without looking. Develop muscle memory (whatever that is!) in your whole arm.
One of the plus points of guitars is that each chord has several places to be played. With (supposedly) the A♭ played on fret 4 with a barre, you'll use an E shape. Keep the same barre, move across to an A shape, and there's your D♭. That may or may not be what you want to achieve in the song, but it's another way round. The first way just needs lots of dedication, but there will always be a slight delay, it does take a few milliseconds to move a number of frets.
Answer: Let's assume a E form barre chord...
If you are playing on roots like G, G#, A, A#, B..., that might not be an effective practice pattern for two reasons:

The distance is only one fret. This may be too easy for you. When you can execute this without trouble repeating it for practice is sort of a waste of time.
Two major chords connected by a half step is a little uncommon, three or more in a row is definitely not common. You're missing the aural reinforcement - the musical reward you could call it - of hearing "real" chord progressions when you execute the change correctly.

You're 4th fret to 9th fret change is a good "real" progression. It's a root change by 4th, G# to C#.
If that feels too far, try instead dropping down 2 frets G# to F#. Of course it's a shorted distance and so should be easier. But also it's a "real" progression. Hopefully that will give you positive musical feedback.
Eventually you can try combining all three F#, G#, and C#. The are all in the same key and so will sound like real music.
But you can try some other things beside just altering the distance you must slide.
Tempo
The first obvious thing to alter is the tempo. Slow down the beat and experiment with just how slow you need to go before you can make the change. While it may sound counter-intuitive also try going faster! Focus hard and try to speed it up just for a few repeats, then drop back down to normal tempo. The idea is to acclimate yourself to a faster speed in gradual stages.
Where you're looking
Where are you looking? Probably at your hand making the barre chord. Try to not look at that hand and make the short 1 or 2 fret changes. Instead of seeing the distance you want to feel the size of the shift of your forearm.
If you do look, try to look at the target not your hand. If you are already on the 4th fret, what good does it do to look at your hand? It's already in place. Look at the empty place of the 2nd or 9th frets and then watch your hand with your peripheral vision move into place.
Grip
Part of the problem might be your "grip" on the barre chord while changing position. You want to release your grip for the change, but without your fingers falling out of the E form shape. You want minimal movement in the release, sort of a lightness in the grip. If that seems like a problem trying keeping the chord in place on a fret and then play it staccato where you squeeze the grip just for a moment to create the short staccato effect. A kind of bouncy squeeze for 4 or 8 strokes then change the chord. The point is to try to develop the slightest of movement and speed to release the chord without loosing the chord shape.


Change iOS Simulator Device Name

Question: I'm working on a big project with many view controllers. Progression through these views depends on data being filled in on lengthy forms.
In my not-so-clever way i'm autofilling data so that i can speed through to the current feature I'm working on. I was using a conditional like this...
if(
   [[[UIDevice currentDevice] name] hasPrefix:@"Rob"] ||
   [[[UIDevice currentDevice] name] hasPrefix:@"iPad Simulator"]
   )
{
    self.label.text = @"xxx";
    ...
}

...this worked great because I could test both on my iPad and in the simulator. Now the client wants to also be able to test on their simulator, so I can't leave my autofill in. I'm thinking the simplest solution would be to just change the name of the simulator.
In Settings.app on the simulator, it's not editable. I also haven't seen then text "iPad Simulator" or "Simulator" show up in any files in ~/Library/Application Support/iPhone Simulator/5.1. I've done searches on setting plist properties, but no luck.
Does anyone know how to accomplish this?
Comment: Very strange way for testing purposes, you should use `if(DEBUG) { ... }`
Comment: @Kashiv, I'm working in a team and not everyone needs or wants these autofilled in values. I checked and there also doesn't appear to be a way to set these compiler constants per user either. So putting logic in DEBUG blocks would still make all of my testing bit show for everyone (although that is the approach I originally opted for). Finally, I am putting #warnings around all of my testing blocks and as a last pass I'll delete them all when we're ready to do final testing.
Answer: You'll be able to check if it's running the iPhone Simulator by checking the model rather than the name of the current device. Something like the following should do:
if ([[[UIDevice currentDevice] model] isEqualToString:@"iPhone Simulator"]) {
    // Run for iPhone simulator
}

Note: You'll need to use "iPad Simulator" for when you use the iPad Simulator
Also, your current code with hasPrefix is not secure at all. Rob is a common name so if someone else has a device with the name of their device beginning with Rob then it'll expose your test information. I highly suggest you just target this autocomplete for the simulator only
Comment: Hi Suhail, thanks for the answer. I can already tell it's running in the Simulator, but I want to change the name of my Simulator and then write a conditional based off that new name. Also, although the hasPrefix approach isn't ideal, this is for a enterprise distribution app and we'll have control over the device names, so it's not an issue. Thanks!
Answer: Just create a new class and put your loading logic there.
After that, call this class from your delegate didFinishLaunchingWithOptions method.
With this, you can comment the above call whenever you want or better, check if the data is already loaded and ignore it.
Comment: I like this approach for keeping everything tidy and may still use it, but I don't think it helps towards the goal. Thanks!

Change iOS Simulator Device Name


How firebase real time database reads data?

Question: I am working on a chat app where messages store in firebase realtime database. Now if i make a node shown below ( chats-Between-A-and-B-Id are autogenerated chatroom keys ), so i want to know that when user S open chats with user T in chat app so Database will read only the messages stored in chats-Between-S-and-T-Id and will not read others chatroom messages !? am i right ? if yes then will it reduce the pricing?
chats-
      chats-Between-A-and-B-Id-
                 messageID1-…
                 messageID2-…
                 messageID3-…
                 ...
      chats-Between-o-and-p-Id-…
      chats-Between-s-and-t-Id-…
      chats-Between-x-and-y-Id-…

OR
If i store data like shown below then if user S open chats of user T in chat app so Database will read whole messages and
cahts-
      messageID1-…
      messageID2-…
      messageID3-…
      ...

sort them like (shown below) so it will read all messages and sort them and show in app to the user !? which will increase the pricing ?
if(chat.getReceiver() == senderID && chat.getSender() == receiverId ||
   chat.getReceiver() == receiverId && chat.getSender() == senderID)
                          {
                             (mChatList as ArrayList<Chat>).add(chat) //show chats
                          }

I  want  to  know  which  approach  can  save  my  money.
Edit
I am using the 2nd approach (i got it from a chat app tutorial). Where we sort messages according to senders and receiver but after reading the answer of @sharath i get that if i go with this it will read every message from chat node and then sort them according to sender-reciver and if there are 1 million messages from all the users then it will read 1 million messages and sort only some of them only for 2 users! It will make me poor. So i am thinking about using the 1st approach where i will get messages from chat>>roomIdBetween2Users so it will ont read others chat and give me secure, maintainable and affordable databse.
And this is the image of my database here chats is parent node contains all the messages of all the users and sort them as i mentioned in the code for 2 users. There are already approximately 500+ messages in chats. And it will be so dangerous in future.
Comment: It is more of a security thing than cost. You basically want the security rule to be as such that one can only access the message he has done with the other. So, chats of A and B stored as some_id_a_b can onl be accessed by A and B and neither of these users can access other users' chats as well. Limiting a node to two Ids instead of one, not mentioned in docs as well, I want similar security rule too.
Answer: Its a little tricky situation to answer this without knowing your firebase DB structure. Am making an assumption and generalising this answer.
Firebase is a No SQL Database which stores data in tree structure or Parent child manner
Main important logic you should think of while developing anything with NoSQL databases are you need to create the Firebase DatabaseReference to the deepest node possible. Firebase queries and reads data which comes under the referenced node.
For example : if you have firebase structure as below
See this image of Firebase sample structure
If you want to access chats of User S, Create Reference to ID_User_S node.
note: If you create reference top node "Chats" then snapshot returns all child information under it
Regarding pricing : Yes the lesser the data you read lesser the price you pay. If you are referencing to deepest node possible you read lesser data. Try to optimise all firebase queries to reach to deepest node possible for creating a reference.
Now coming to your structure
chats-
      chats-Between-A-and-B-Id-
                 messageID1-…
                 messageID2-…
                 messageID3-…
                 ...
      chats-Between-o-and-p-Id-…
      chats-Between-s-and-t-Id-…
      chats-Between-x-and-y-Id-…

If you create a database reference to Chats node then each one trying to access the chat will read every child under it which includes others chats as well.
So for efficient usage create reference to chats-Between-A-and-B-Id- so that you can get exact list of messages under those 2 users
Comment: Yes you got it right. If you create reference to top level parent node, your fetch query will read and return full tree structure which comes under it. That full data size is billable.So if you reach in inner most child node you can get which data exactly you need which in return avoid making you pay for unwanted data fetching. For additional information you can also use local Database for storing ones fetched data. So you may not have to fetch again and again.
Comment: Hope this solution give you an idea of how firebase reads data. If you still have doubt please post your Demo Firebase Structure. So that I can help you out with appropriate solution
Comment: Hey @sharath your answer is so expressive Thanks for that . Now after reading your answer i got some clearance. So you mean that if i get reference of a child node like parentNode>> anyOneChildNode>> manyChildren so here if i take reference of anyone child node so it will not read others childNode so there will only be reads of that oneChildNode so i have to pay lesser than if i get reference of parentNode than sort child it means it read every chil then sort them and show me. It means i have read every child then whatever i sort them to get some of them. Now i have to pay more. Right?
Comment: Thank you! you are absolutely right and thanks for counselling me to use local database. I was also thinking about it to use SQL to save some important and non realtime data snapshots. I will try to implement them. I like the way of your cooperation, it's really appreciable .
Comment: Glad I could help you. Good Luck


Dynamic configuration file in Nodejs and Express

Question: I am working with NodeJs with expressjs and I would like to use a middleware that will read a variable from dynamic configuration file before each request (some js file that holds an object that I can change manually while the server is running).
I would like to store a flag that will close down all requests (i.e send response without proceeding to next routes) until I change the variable value to true and then the middleware will call next() so all routes will work.
I prefer to avoid shutting down the server for that, and I also don't want to store this variable in a database...
Is there something similar to what I need?
Thanks
Comment: Take a look at other's responses below(but never read file synchronously though when you're processing the request!). I don't have time to provide you with exact implementation right now, but you should consider using `fs.watch` function to register callback for file changes and read file only when it's necessary.
Comment: What do you mean by "close down all requests"?
Comment: i will put this function(see below) as a middleware before all the get\post\put routes in my server.
function(req,res,next){
if (confFile.confs.registrationStatus==="open"){
next();
}else{
res.send("registration closed");
}
}

i also edited the question for clearity
Comment: it feels from the comments below that what i'm trying to achieve is a bad practice. i need something which is very simple, to control using middleware function a handling request by a dynamic property (i.e registration closed\registration open). what is the best option in your opinion? define a configuration table in a database, and read the property each time in the database or shutdown the server, change the code of the middleware and start it again?
reading a file every time using FS seems like a very bad option.
Answer: You will read config.json file each time, if you just put it inside function. If you will use require('config.json), then you will read this file only once on start.
<code>var fs = require("fs");

function (req,res,next) {

  var config = fs.readFileSync('./config.json');
  config = JSON.parse(config.toString());

  if (config.registrationStatus === "open") {
    next();
  } else {
    res.send("registration closed");
  }
}
</code>
Comment: does using Sync Fs is the best option? seems though to read this file on each request from client.
Comment: @user3286882 of course it is not option at all. I thought you need it just for testing or some kind of local project. Use DB instead or at least readFile (this will be async).
Answer: Check supervisor: https://github.com/petruisfan/node-supervisor
It will watch for file changes and crashes and will restart your application each time.
You will get much better performance.
Comment: it feels to me a very bad practice to restart the server for this kind of thing.
i might consider working with a different way than a configuration file (maybe database) ?
what do you thing would be the best option for me ?
Comment: @user3286882 it is not a good practice for your goal, because your full approach is wrong. But it definitely the best practice for applications in production environment at all.
You want to use either PM2 or supervisor to run your app. They will restart node server on each unhandled error, so you will not leak resources as crazy and your app will be always running.
Comment: can you please tell me what is wrong with my approach ?
how can i enable\disable a service of a web server dynamically?


What does it mean when a piece is written on a specific scale?

Question: All the music pieces and songs are written on some scale, say if we consider D major scale the Cs and Fs must be sharp and others natural. But the Cs and Fs in that piece might be flat or natural at some points as well, or some other natural notes may be sharp at some point. So if we don't write the piece using only D major scale notes, what does it mean for the piece to be in D major? we could even change the signs without changing the melody and hence change the scale as if it does not really matter what scale we consider for the piece, am I right?
Also, when some music is on a pentatonic scale, is it the same? can we use other notes than the ones in the pentatonic scale, or should we just use those five notes?
Answer: You use on, but should it be in?
Music is never written on a scale, or even, for that matter, in a scale. Tonal music is written in a key. And, yes, often other notes are used as well (although rarely C♭ or F♭ in key D!).
The key provides a couple of things - one, the likely notes that will fit together best, and two, a clue as to where 'home' will be expected. When we see two sharps at the beginning of a piece,  most of us would guess that it's likely to be 'in key D major', or 'in key B minor'. Those are the usual suspects for 2♯, and it helps the reading a lot.
It could, of course, actually be in E Dorian, or A Mixolydian, which would use the same sharps, but then 'home' would be on a different note for each.
Those accidentals you mention are often there to facilitate a modulation, or key change, but usually remain as accidentals unless there's a complete and utter key change, in which case, the key signature should change to signify a different set of notes - key or scale.


Averaging cosine with a randomly varying argument

Question: Suppose I have a function $y(t)=\cos (\delta(t))$. Here $y(t)$ and $\delta (t)$ are single valued functions but not necessarily continuous or differentiable. The function $\delta(t)$ is a "random function" (function as in there is exactly one output for every input) which provides an arbitrary values for different values of $t$. It is a single valued "function", but there is no computable relation between its argument$(t)$ and its value $(\delta(t))$.
If I want to average $y(t)$ over a large time interval $T$, how do I do it?
$$y_{avg}=\frac 1T \int_0^T \cos(\delta(t))dt$$
I know intuitively, that since $\delta$ varies randomly and rapidly (as compared to the interval over which it is averaged), the average should be zero as there are as many positive values of $y(t)$ as there are negative, and in the average it all sums to zero. But is there any way to show this mathematically? Or we with what constraints on $\delta(t)$ and $T$, will the average turn out to be zero?(eg. $T\rightarrow \infty$)
$\delta (t)$ takes any value randomly within those bounds. If allowed infinite selections, the output of the function will indeed be uniformly distributed. One of the ways to allow infinite outputs (to uniformly distribute the outputs) is the limit as $T\rightarrow \infty$. My question is how to deal with it if and if not uniformly spread, and what other conditions will allow this random-output function to be uniformly spread?
The physics tag is because this is what happens when two incoherrent light sources with random phase relation (which usually changes in $10^{-8}$ seconds) interfere on a screen. The cosine term is the "interference term" that appears when two waves with the same frequency and wavelength are superimposed.
Comment: This question is meaningless unless you know more about your "random function". You have to have some sort of a model.
Comment: @IgorRivin Only that it can take absolutely any value (within say a given upper bound $U_1$ and a lower bound $U_2$ somewhere of the order $10^4$) for each value of $t$. I don't know how do we *model* random numbers, but this *function* gives random numbers within the given bounds.
Comment: So, are you assuming that $f(t)$ is _uniformly distributed_ between $U_1$ and $U_2?$
Comment: @IgorRivin $\delta(t)$ takes any value *randomly* within those bounds. If allowed infinite selections, the output of the function will indeed be uniformly distributed. One of the ways to allow infinite outputs (to uniformly distribute the outputs) is the limit as $T\rightarrow \infty$. My question is how to deal with it if and if not uniformly spread, and what other conditions will allow this random-output function to be uniformly spread?
Answer: Think of chopping up the $t$ axis in preparation for approximating integrals by sums. To do this, let's consider a finite sequence $\{t_n\}_{n=1}^N$ with
$$
t_1=0,\\
t_n=t_{n-1}+\Delta t\\
\Delta t = \frac{T}{N-1},
$$
and another sequence that is in between the partition points, $\{t_n^*\}_{n=1}^{N-1}=n \Delta T/2$.  Then let's form the Riemann sum approximation to the integral:
$$
y_{avg}\approx\frac{1}{T}\sum_{n=1}^N \cos(\delta(t_n^*))\Delta t
$$
Caveat (Edit)
I'll admit that this is really dicey; the integrand has no smoothness or continuity, so the Riemann sum has no reason to converge to the integral. However, let's assume $\delta(t)$ is random but with some correlation time to smooth things out. I think the below would still be okay in this case.
By your construction, $\delta(t_n^*)$ is a sequence of random numbers. They way you defined $\delta(t)$, the sequence $\delta(t_n^*)$ can be represented as a collection of independent, identically distributed, uniform random variables $X_n=\delta(t_n^*)\sim U(\alpha_1,\alpha_2)$. We need the distribution of $$Y_n=\cos(X_n).$$
We don't worry exactly about the details of this distribution, but we note it's mean and variance by
$$
\mu_Y=\mathbb{E}[Y_n]\\
\sigma_Y^2 = \mathbb{E}[Y_n^2]-\mathbb{E}[Y_n]^2,
$$
and note that it's distribution must have support only on $[-1,1]$.
So we have
$$
y_{avg}\approx\frac{1}{T}\sum_{n=1}^N Y_n\Delta t=\frac{N}{N-1}\sum_{n=1}^N \frac{Y_n}{N}
$$
The above has a mean of $N$ independent, identically distributed random variables in it, each with finite means and variances, and we're going to take the limit as $N\rightarrow\infty$ to recover our original integral. This means that the central limit theorem applies in the following way
$$
Z = \sum_{n=1}^N \frac{Y_n}{N} \overset{C.L.T}{\Rightarrow} Z\sim\mathcal{N}\left(\mu_Y,\frac{\sigma_Y^2}{N}\right)
$$
Which leaves us with
$$
y_{avg}\approx \frac{N}{N-1}Z
$$
Now taking the limit:
$$
y_{avg} = \lim_{N\rightarrow\infty} \frac{N}{N-1}Z
$$
Clearly, the variance of $Z$ degenerates to zero as  $N\rightarrow\infty$, and $\frac{N}{N-1}\rightarrow 1$. I'll admit it's a bit handwavy to so say, and formally you'd have to appeal to the various convergence results in probability theory, but in the limit, $Z$ becomes a distribution with support only on a single number, it's mean $\mu_Y$. That is, $Z=\mu_Y$ in the limit as it's variance vanishes, and so
$$
y_{ave} = \mu_Y = \mathbb{E}[\cos(X_n)],
$$
which of course depends on the particulars of the uniform distribution from which you drew the angles $X_n$, i.e. how you defined $\delta(t)$. If you make the quite standard choice that the $X_n\sim U(-\pi,\pi)$, then it can be shown that $Y_n$ has a distribution with probability density function given by
$$f_Y(y)=\frac{1}{\pi\sqrt{1-y^2}},\;\;-1\leq y\leq 1$$
with
$$
\mu_Y = \int_{-1}^1 \frac{y}{\pi\sqrt{1-y^2}} dy = 0
$$
So $$y_{ave} = \mu_Y = 0$$ in this case. Note the result does not have to be zero, depending on the distribution of $\delta$. For example, suppose that $\delta(t)$ takes values on $(0,\pi/2]$, then $Y_n$ will be in the range $(0,1]$ and so will $\mu_Y$ and $y_{ave}$ meaning that you can contrive scenarios when $y_{ave}\neq 0$ by choosing $\delta(t)$ appropriately.