condition probability of a condition probability

Question: Given a probability space ($\Omega,\mathscr{F},\mathbb{P}$).Suppose A $\in\mathscr{F}$ satisfies $\mathbb{P}(A)>0$.Define $\mathbb{Q}(B):=\mathbb{P}(B|A)$ for any B$\in\mathscr{F}$.Prove for any $B\in\mathscr{F}$ and sub $\sigma$ algebra $\mathscr{C}\subset\mathscr{F}$,
$\mathbb{Q}(B|\mathscr{C})=\frac{\mathbb{P}(A,B|\mathscr{C})}{\mathbb{P}(A|\mathscr{C})}$.
I think, we must proof $\forall C\in\mathscr{C}$,$\mathbb{Q}(B,C)=\int_C\frac{\mathbb{P}(A,B|\mathscr{C})}{\mathbb{P}(A|\mathscr{C})}$,but I don't know how to calculate the last integral
Answer: Since OP asked Speltzu for an explanation I add how I would prove this:
By definition:
$$\tag1
\mathbb Q(B)=\mathbb P(B|A)=\frac{\mathbb P(B\cap A)}{\mathbb P(A)}\,.
$$
Claim. For a $\sigma$-algebra $\mathscr C$ we have
$$\tag2
\boxed{\phantom{\Bigg|}\quad\mathbb Q\big[B\,\big|\,\mathscr C\big]=\frac{\mathbb P[B\cap A\,|\,\mathscr C]}{\mathbb P[A\,|\,\mathscr C]}\,.\quad}
$$
Proof. By defintion of the conditional probability we have
for any $C\in\mathscr C$
$$\tag3
\int_C\mathbb P\big[B\cap A\,\big|\,\mathscr C\big]\,d\mathbb P=\mathbb P\big[B\cap A\cap C\big]\,.
$$
The measure $\mathbb Q$ has Radon-Nikodym density
$$\tag4
\frac{d\mathbb Q}{d\mathbb P}=\frac{1_A}{\mathbb P(A)}
$$
with respect to $\mathbb P\,.$
Then,
\begin{align}\tag5\require{cancel}
&\int_C \frac{\mathbb P[B\cap A\,|\,\mathscr C]}{\mathbb P[A\,|\,\mathscr C]}\,d\mathbb Q\stackrel{(4)}{=}
\int_C\,\frac{\mathbb P[B\cap A\,|\,\mathscr C]}{\mathbb P[A\,|\,\mathscr C]}\,\frac{1_A}{\mathbb P(A)}\,d\mathbb P\\[2mm]\tag6
&\stackrel{\textstyle\color{red}{(*)}}=
\int_C\,\frac{\mathbb P[B\cap A\,|\,\mathscr C]}{\cancel{\mathbb P[A\,|\,\mathscr C]}}\frac{\cancel{\mathbb P[A\,|\,\mathscr C]}}{\mathbb P(A)}\,d\mathbb P\\[2mm]\tag7
&=\int_C\,\frac{\mathbb P[B\cap A\,|\,\mathscr C]}{\mathbb P(A)}\,d\mathbb P
\stackrel{(3)}{=}
\frac{\mathbb P[B\cap A\cap C]}{\mathbb P(A)}\stackrel{(1)}=\mathbb Q(B\cap C)\,.
\end{align}
$$\tag*{
$\Box$}
\phantom{\quad}
$$
To answer the question by Speltzu why in the equals sign marked by
$\color{red}{(*)}$ we are allowed to switch from $1_A$ to
$\mathbb P[A\,|\,{\mathscr C}]\,:$
All other ingredients of that integral are ${\mathscr C}$-measurable. The very definition of $\mathbb P[A|{\mathscr C}]$ says
$$\tag8
\int_\Omega 1_C\mathbb P[A\,|\,{\mathscr C}]\,d\mathbb P=\int_\Omega 1_C1_A\,d\mathbb P\,,\quad \forall C\in{\mathscr C}\,.$$
This carries over from the indicator function $1_C$ to all simple ${\mathscr C}$-measurable functions and then to all ${\mathscr C}$-measurable functions.
Comment: How do you justify the change of $\mathbb{P}[A|\mathscr{C}]$ for $1_A$?
Comment: @Speltzu See edit.
Answer: Difficult problem where there are. I rectify my previous answer. The proposition is true.The reasoning would be as follows:
\begin{gather*}
\mathbb{E}_{\mathbb{Q}}\left[\frac{\mathbb{P}[A\cap B|\mathscr{C}]}{\mathbb{P}[A|\mathscr{C}]}. 1_C\right]
=\mathbb{E}_{\mathbb{Q}}\left[\frac{\mathbb{P}[A\cap B\cap C|\mathscr{C}]}{\mathbb{P}[A|\mathscr{C}]}\right]
=\int \left[\frac{\mathbb{P}[A\cap B\cap C|\mathscr{C}]}{\mathbb{P}[A|\mathscr{C}]}\right]d\mathbb{P}_{\Omega/A}=\\
=\frac{1}{\mathbb{P}(A)}\int 1_A.\left[\frac{\mathbb{P}[A\cap B\cap C|\mathscr{C}]}{\mathbb{P}[A|\mathscr{C}]}\right]d\mathbb{P}_{\Omega}
=\frac{1}{\mathbb{P}(A)}\int \mathbb{P}[A\cap B\cap C|\mathscr{C}]d\mathbb{P}_{\Omega}=\\
=\frac{\mathbb{P}(A\cap B\cap C)}{\mathbb{P}(A)}=\mathbb{Q}(B\cap C)
=\mathbb{E}_{\mathbb{Q}}[1_B.1_C]
\end{gather*}
By the way, this means that:
$\mathbb{Q}[B|\mathscr{C}]=\mathbb{P}[B|\mathscr{C},A]$.
Comment: Thanks for your answer, could you please explain the equation when $B\notin \mathscr{C}$ ?


Reentrant Read/Write locks in eclipse have two lock/unlock methods

Question: I noticed that while calling lock/unlock on a ReentrantReadWrite lock, I am prompt with two lock and unlock methods.
For example, in the WriteLock I have a Lock() with -75% and another Lock() with no %. Both of these have the same documentations. I tried to find a reason online, but could not find any explanation. Is it just a bug in eclipse?
Comment: this is just eclipse's prediction I believe, it ranks methods by relevancy of use.
Comment: the odd thing is that the ReadLock is 25%, and the unlock are 50% both. So I am trying to understand if this is a prediction of write vs. read (which sounds odd, because you perform more reads), or is it something else
Comment: this is just eclipse trying to predict what you're going to use for your convenience, much like microsoft's intellisense.
Answer: You might want to double-check those method names.
ReentrantReadWriteLock doesn't have a Lock method.  It has public ReentrantReadWriteLock.ReadLock readLock() and public ReentrantReadWriteLock.WriteLock writeLock().  Those both implement the Lock interface and have lock(), lockInterruptibly(), unlock(), and trylock() methods.
The WriteLock has a few extra methods since write locks are generally exclusive.
Comment: Powelord, you are right I should have included this in my question, but even for WriteLock the two writelocks calls differ by this %. I guess as rpg711 said it is a prediction.


C# - How can I call a method from another 'class ClassName where T : IComparable'

Question: In my 'Program.cs' I am trying to call method 'inOrder()' from another class 'BinTree.cs'.
Class BinTree starts with class BinTree<T> where T : IComparable
I've tried:
inOrder();

and
BinTree<T>.inOrder();

and
BinTree<int>.inOrder();

But none of these work.
Thanks for looking.
EDIT:
class Program
{
    static void Main(string[] args)
    {
        Node<int> tree = new Node<int>(6);
        tree.Left = new Node<int>(2);
        tree.Left.Right = new Node<int>(5);

        tree.Left.Right.Data = 3;

        tree.Right = new Node<int>(8);

        (new BinTree<int>()).inOrder();

    }

EDIT2:
    private Node<T> root;
    public BinTree()  //creates an empty tree
    {
        root = null;
    }
    public BinTree(Node<T> node)  //creates a tree with node as the root
    {
        root = node;
    }

Comment: _how_ and _where_ `inOrder()` declared ?
Comment: Related: http://stackoverflow.com/questions/9094232/generics-and-implementing-icomparable
Comment: If `inOrder` is an instance method, you need to create an instance first.  If it's static, it needs to be public, in which case `BinTree.inOrder();` should work.
Comment: 'inOrder()' is declared in class BinTree. 'public void inOrder()
        {
            inOrder(root);
        }'
Comment: Sorry not sure how to use code tags in the comments section
Comment: Ok.  So call it with `(new BinTree()).inOrder();`
Comment: inOrder is indeed public but it is not static
Comment: Yes, which means you need to call it off an instance.
Comment: Hmm that runs but now it is not using my tree which I'll post the code for above.
Comment: Do you have some sort of mechanism to add `Node` objects to a `BinTree` instance?
Comment: EDIT2 in top post. I'm new to all this so bare with me sorry.
Comment: Ok starting to make sense now.  See my answer.
Answer: From what I can tell, you need to create a BinTree<int> instance and pass in your Node<int> instance on the constructor.  Something like this:
class Program
{
    static void Main(string[] args)
    {
        // Create Node instances for tree
        Node<int> node = new Node<int>(6);
        node.Left = new Node<int>(2);
        node.Left.Right = new Node<int>(5);
        node.Left.Right.Data = 3;
        node.Right = new Node<int>(8);

        // Create tree, set root node
        BinTree<int> tree = new BinTree<int>(node);
        tree.inOrder(); // Call inOrder method of tree instance
    }
}

Comment: Worked a treat, thank you. Now I'll try and figure out why because my assigned work just says 'the user would call 'tree.inOrder();'.


Why Confidence Interval is always wider than Prediction interval?

Question: I was given a problem asking that and I'm not quite sure how to answer it. If anyone can please explain me
Comment: Since it seems to be a homework, please add `[self-study]` tag and check  http://stats.stackexchange.com/tags/self-study/info
Comment: Prediction intervals are actually always wider than confidence intervals. A detailed explantion is given here: https://stats.stackexchange.com/a/271232/180467
Answer: Is it?

I have seen someone compute a confidence interval for the mean, and
  use it as if it was a prediction interval for a future observation.
  The trouble is, confidence intervals for the mean are much narrower
  than prediction intervals, and so this gave him an exaggerated and
  false sense of the accuracy of his forecasts. Instead of the interval
  containing 95% of the probability space for the future observation, it
  contained only about 20%.

(source http://robjhyndman.com/hyndsight/intervals/)
Comment: Also: https://www.graphpad.com/support/faqid/1506/
Answer: I can be very, very confident what the average age of a United States citizen is if I've taken enough samples. But if you pick a person at random, I basically have no idea how old they are. One has almost nothing to do with the other.
Comment: Variance of sample mean vs variance of population.  Is this what the op was asking?
Comment: @innisfree That's pretty much what it comes down to.


Converter Data SQLServer

Question: Gostaria de converter02/01/2018 para 2018-01-02 00:00:00.000, o que eu encontrei na internet até agora foi:
select CONVERT (datetime, '02/01/2018', 120)

Que me retorna2018-02-01 00:00:00.000, um pouco diferente do que preciso.
Qual numero devo usar no lugar do 120?
Comment: Conheça os estilos de data e hora em https://docs.microsoft.com/pt-br/sql/t-sql/functions/cast-and-convert-transact-sql
Answer: Segundo essa resposta do SO, o código que você deseja é o 103:
select CONVERT (datetime, '02/01/2018', 103)

Answer: 108 trás as horas também.
SELECT CONVERT (DATETIME, '02/01/2018', 103) + ' ' +  CONVERT(VARCHAR, nomedacoluna, 108)

Converter Data SQLServer


Y over Y change in Pivot Table

Question: I have a pivot table and I'd want to create another pivot table of the same format but that now it contains Year over Year percent change.
This is a simple example:
my_data = {
    'date': [datetime.date(2000,1,7), datetime.date(2000,1,14),
             datetime.date(2001,1,5), datetime.date(2001,1,12)],
    'week_number': [1,2,1,2],
    'quarter_number': [1,1,1,1],
    'name': ['hi','bye','hi','bye'],
    'category': ['clothing','electronics','clothing','electronics'],
    'total sales': [123,456,180,350]
}
my_df = pd.DataFrame(my_data)
my_df.pivot_table(index=['date','week_number','quarter_number'], columns=['name', 'category'])

Resulting in following pivot table:
                                      total sales
name                                          bye       hi
category                              electronics clothing
date       week_number quarter_number
2000-01-07 1           1                      NaN    123.0
2000-01-14 2           1                    456.0      NaN
2001-01-05 1           1                      NaN    180.0
2001-01-12 2           1                    350.0      NaN

Now let us say I want to compute percent change Year over Year.  The resulting pivot table would look like:
                                      total sales pchg Y/Y
name                                          bye       hi
category                              electronics clothing
date       week_number quarter_number
2000-01-07 1           1                      NaN      NaN
2000-01-14 2           1                      NaN      NaN
2001-01-05 1           1                      NaN    0.463
2001-01-12 2           1                    -0.23      NaN

Note that in the general case we have N names, many years of data and K categories.
I provide here a more general case too to show that pct_change does not work in default mode since it'd not do percent change Year over Year.
my_data = {
    'date': [datetime.date(2000,1,7), datetime.date(2000,1,14),
             datetime.date(2001,1,5), datetime.date(2001,1,12),
             datetime.date(2000, 1, 7), datetime.date(2000, 1, 14),
             datetime.date(2001, 1, 5), datetime.date(2001, 1, 12),
             datetime.date(2000, 1, 7), datetime.date(2000, 1, 14),
             datetime.date(2001, 1, 5), datetime.date(2001, 1, 12),
             datetime.date(2000, 1, 7), datetime.date(2000, 1, 14),
             datetime.date(2001, 1, 5), datetime.date(2001, 1, 12)],
    'week_number': [1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2],
    'quarter_number': [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    'name': ['hi','hi','hi','hi','hi','hi','hi','hi','bye','bye','bye','bye','bye','bye','bye','bye'],
    'category': ['clothing','clothing','clothing','clothing','electronics','electronics','electronics','electronics',
                 'clothing', 'clothing', 'clothing', 'clothing', 'electronics', 'electronics', 'electronics','electronics'],
    'total sales': [123,456,180,350,123,456,180,350,123,456,180,350,123,456,180,350]
}
my_df = pd.DataFrame(my_data)
my_df.pivot_table(index=['date','week_number','quarter_number'], columns=['name', 'category'])

my_df.pivot_table(index=['date','week_number','quarter_number'], columns=['name', 'category']).apply(pd.Series.pct_change)
                                      total sales     ...
name                                          bye     ...              hi
category                                 clothing     ...     electronics
date       week_number quarter_number                 ...
2000-01-07 1           1                      NaN     ...             NaN
2000-01-14 2           1                 2.707317     ...        2.707317
2001-01-05 1           1                -0.605263     ...       -0.605263
2001-01-12 2           1                 0.944444     ...        0.944444

The pct_change is clearly wrong as it does not provide Y/Y changes but rather row i to row i+1.
Answer: You can achieve desired result with pct_change:
pivoted = pd.pivot_table(my_df, index=['date','week_number','quarter_number'], columns=['name', 'category'])
pivoted.groupby(level='week_number').transform(pd.Series.pct_change)
#                                      total sales
#name                                          bye        hi
#category                              electronics  clothing
#date       week_number quarter_number
#2000-01-07 1           1                      NaN       NaN
#2000-01-14 2           1                      NaN       NaN
#2001-01-05 1           1                      NaN  0.463415
#2001-01-12 2           1                -0.232456       NaN

Comment: I'd want the pct change year over year week 1 of year 2000 against week 1 of year 2001.  This pct_change as it is wouldn't do this for the general case, i'd just do pct change between row i and row i+1
Comment: @Dnaiel You are welcome, wasn't what would your actual data look like, now it's better :D
Comment: right, my example was too limited that's why I included a more general one below.

Y over Y change in Pivot Table


JavaScript string with new line - but not using \n

Question: I have a string that has new lines in. I am wanting to convert these to HTML
s, but I'm having a hard time detecting them.
Imagine a JavaScript string set like this:
var foo = "Bob
is
cool";

They are the kind of new lines that I need to detect. They aren't using the \n special character - they are just plain format.
Comment: That *is* `\n` (unless it's possibly also `\r`)
Comment: @Pointy: but the result would still be the same, provided this wasn't a syntax error.
Comment: "Plain format" newlines are simply the visible result of a \n special character. \n is just an alias of it.
Comment: I think he meant that they're not expressed with the `\n` escape sequence, but rather that the character is literally there in the source code.
Comment: @Evert yes I agree of course; I'm thinking syntax error too.
Comment: As of 2016 there is a way to do this: https://stackoverflow.com/a/40334713/1454514
Answer: The reason it is not working is because javascript strings must be terminated before the next newline character (not a \n obviously). The reason \n exists is to allow developers an easy way to put the newline character (ASCII: 10) into their strings.
When you have a string which looks like this:
//Note lack of terminating double quote
var foo = "Bob

Your code will have a syntax error at that point and cease to run.
If you wish to have a string which spans multiple lines, you may insert a backslash character '\' just before you terminate the line, like so:
//Perfectly valid code
var foo = "Bob \
is \
cool.";

However that string will not contain \n characters in the positions where the string was broken into separate lines. The only way to insert a newline into a string is to insert a character with a value of 10, the easiest way of which is the \n escape character.
var foo = "Bob\nis\ncool.";

Comment: Aug 2016 Update: There is NOW a way to do this: https://stackoverflow.com/a/40334713/1454514
Answer: UPDATE: I just came across a wonderful syntax design in JavaScript-ES6 called Template literals. What you want to do can be literally be done using ` (backtick or grave accent character).
var foo = `Bob
is
cool`;

In which case, foo === "Bob\nis\ncool" is true.
Why the designers decided that ` ... ` can be left unterminated, but the " ... " and ' ... ' are illegal to have newline characters in them is beyond me.
Just be sure that the targeting browser supports ES6-specified Javascript implementation.

P.S. This syntax also supports a pretty cool feature that is present in PHP, .NET, and some other scripting languages; namely "Tagged template literals" with which you can build a parameterized string like this:
var a = 'Hello', b = 'World';
console.log(`The computer says ${ a.toUpperCase() }, ${b}!`);
// results in "The computer says HELLO, World!"

Comment: Can I give you 10 upvotes for the backtick answer? It really works like magic! :)
Comment: best answer bro
Comment: @kiki so I suggest learning and using Babel in order to "transpile" ES6 to older versions of _compatible_ javascript for Google Apps scripts. You can also [ask a new](https://stackoverflow.com/questions/ask) question titled "How to use ES6 in Google Apps script IDE", maybe someone has a solution for it.
Comment: "Why the designers decided that ` ... ` can be left unterminated, but the " ... " and ' ... ' are illegal to have newline characters in them is beyond me."
 -
The developers of Javascript in 1995 were not the same as the ones in 2015. And changing old-style strings would break old code. Pretty clear reasoning.
Comment: I am trying to use `` in Google Apps script IDE and it says "Illegal character.". How to handle?
Comment: @kiki It seems that Google Apps _doesn't_ support ES6 syntax (the version of javascript that allows this),
Comment: @JimmieTyrrell In hindsight, you're clearly correct.  I guess I'm more infuriated by the fact that they decided against changing the older syntax to avoid breaking old code as you put it, despite that " ...  ... " and ' ...  ... ' were still invalid syntax, so I wouldn't see  the point of not changing them to allow the same newline syntax.
Answer: Check for \n or \r or \r\n.
There are several representations of newlines, see http://en.wikipedia.org/wiki/Newline#Representations
Comment: I'm doing that. I've checked for all three: `console.log(story.message.split(/\n/g));
     console.log(story.message.split(/\r/g));
     console.log(story.message.split(/\r\n/g));` They all return the same. No split.
Answer: I think they using \n anyway even couse it not visible, or maybe they using \r. So just replace \n or \r with

Answer: I don't think you understand how \n works. The resulting string still just contains a byte with value 10. This is represented in javascript source code with \n.
The code snippet you posted doesn't actually work, but if it did, the newline would be equivalent to \n, unless it's a windows-style newline, in which case it would be \r\n. (but even that the replace would still work).
Comment: Thanks. In that case, why won't this work?  `console.log(story.message.split(/\n/g)); console.log(story.message.split(/\r/g)); console.log(story.message.split(/\r\n/g));` They all return the same. No split
Answer: you can use the following function:
  function nl2br (str, is_xhtml) {
     var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '
' : '
';
     return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
  }

like so:
var mystr="line\nanother line\nanother line";
mystr=nl2br(mystr);
alert(mystr);

this should alert line
another line
another line
the source of the function is from here:
http://phpjs.org/functions/nl2br:480
this imitates the nl2br function in php...
Answer: This is a small adition to @Andrew Dunn's post above
Combining the 2 is possible to generate readable JS and matching output
 var foo = "Bob\n\
    is\n\
    cool.\n\";

Answer: The query string that I used to to escape the new line character in JS :
LOAD DATA LOCAL INFILE 'Data.csv' INTO TABLE DEMO FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 ROWS;
This involves new ES6 syntax - Template Literals `` and I tried changing '\n' to '\r\n' and worked perfectly in my case.
PS: This example is my query to upload CSV data into mysql DB.


Which of the following subsets are dense in the given spaces?

Question: Which of the following subsets are dense in the given spaces?

(a) The set of trigonometric polynomials in the space of continuous functions on $[−\pi, \pi]$ which are $2\pi$-periodic (with the sup-norm topology).
(b) The subset of $C^ ∞$ functions with compact support in $\mathbb{R}$ in the space of
bounded real-valued continuous functions on $\mathbb{R}$ (with the sup-norm topology).
(c) $GL(n;\mathbb{R})$ in $M(n;\mathbb{R})$ (with its usual topology after identification with $\mathbb{R}^{n^2}$ ).

$GL(n;\mathbb{R})$ maps $\mathbb{R}^*$ by determinant function which is dense, so (c) is true. But how can I able to verify (a) and (b)?
Answer: For (a): it is true, just apply Fejér's theorem.
For (b): it is false. Let $f \in C_b^0(\mathbb{R})$ be identically equal to $1$ and $g \in C_c^{\infty}(\mathbb{R})$. Then, there exists $x \in \mathbb{R}$ such that $f(x)=0$, hence $||f-g||_{\infty} \geq |f(x)-g(x)|=1$.
For (c): it is true. If $A \in M_n(\mathbb{R})$, use Gauss elimination to show that there exist $P,Q \in GL_n(\mathbb{R})$ such that $A=P \left( \begin{array}{cc} I_r & 0 \\ 0 & 0 \end{array} \right)Q^{-1}$ where $r= \text{rank}(A)$. Then, if $A_m= P \left( \begin{array}{cc} I_r & 0 \\ 0 & \frac{1}{m}I_{n-r} \end{array} \right)Q^{-1}$, notice that $A_m \in GL_n(\mathbb{R})$ and $A_m \underset{m \to + \infty}{\longrightarrow} A$.


JavaScript parseInt not working with "10"?

Question: I wrote the function that tokenizes arithmetic string expression into an array of tokens, such as numbers and operators. Everything's fine but I get a weird results when dealing with strings containing "10". Here's the code:

function tokenizeString(expressionString) {
    const tokenArray = [];

    let token = "";
    for (let i = 0; i < expressionString.length; i++) {
        if (parseInt(expressionString[i])) {
            token += expressionString[i];
        } else {
            tokenArray.push(parseInt(token));
            token = "";
            tokenArray.push(expressionString[i]);
        }
    }

    if (token !== "") {
        tokenArray.push(parseInt(token));
    }

    return tokenArray;
}

console.log(tokenizeString("14+2/8")); // [14, "+", 2, "/", 8]
console.log(tokenizeString("10+1")); // [1, '0', NaN, '-', 3] ??

For now I can't come up with an idea, why this happens.
Comment: because 0 is falsy.  `parseInt(expressionString[i] is false when 0`
Comment: @cmgchess Thank you! It works, I forgot about JS falsy values :)
Comment: maybe `typeof(parseInt(expressionString[i])) === 'number'`
Comment: [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173)
Answer: Instead of parseInt in the
if(parseInt(expressionString[i])){}
you could use isNaN() to check if the string is number or not
isNaN() returns true if not a number so your if would
be
if (!isNaN(expressionString[i])){}

function tokenizeString(expressionString) {
    const tokenArray = [];

    let token = "";
    for (let i = 0; i < expressionString.length; i++) {
        if (!isNaN(expressionString[i])) {
            token += expressionString[i];
        } else {
            tokenArray.push(parseInt(token));
            token = "";
            tokenArray.push(expressionString[i]);
        }
    }

    if (token !== "") {
        tokenArray.push(parseInt(token));
    }

    return tokenArray;
}

console.log(tokenizeString("14+2/8")); // [14, "+", 2, "/", 8]
console.log(tokenizeString("10+1")); // [10, '+', 1] ??


Azure App Service (WebSite) outbound ports

Question: Does the outbound ports closed by default in Azure AppServices(website)?
I am trying to stream the log directory from the APPService to my log aggregator (Logstash), it works fine locally but in azure, it is completely silent. Usually, that is NetworkSecurityGroup configuration in case of VM but in APP services I couldn't find the equivalent component
Answer: The only thing you can do with web app logs are logging to file system (inside the app service instance), or to blob storage. There's no component that lets you ship them to directly to logstash. You have various options of getting your logs from blob storage to logstash, but that's outside the scope of this question I guess.
Answer: The problem was not in outbound ports as I thought before. The problem was in the Serilog network sinks (https://github.com/pauldambra/Serilog.Sinks.Network) it can't open a socket in Azure APPservices. I have communicated the problem and the fix with the repo owner and it will be fixed in the next release of Serilog.sinks.network


Activity group throw ActivityNotFoundException?

Question: I want to change the current activity inside a tab in a tab activity,
after some research, I know that I need to use activity group to go this.
then I created a new class extends ActivityGroup with the code below:
public class FavShop extends ActivityGroup{
 protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       LocalActivityManager m = getLocalActivityManager();
       Intent i = new Intent(this, fav_shops.class);
       Window window = m.startActivity("favourite shop",i);
       setContentView(window.getDecorView());
  }
 }

then I run the program, the program throw the ActivityNotFoundException when the intent for the tab is launched
I have no idea how to solve this problem, could anyone help me?
Answer: Did you describe your new Activity in your AndroidManifest.xml?  I forget to do that nearly every time I create an Activity.
Comment: Yes, I did. I really don't know why it happen.
Answer: The solution which worked for me is to CLEAN the project.
In Eclipse, Menu (Project) > Select Clean
Once done, compile and run the project.
See if it works. It is weird though.


AngularJS: Confusion with $scope and radio button interactions

Question: Why won't the $scope change state in this very simple example? When I select each radio button, I would expect to see a console message showing the scope's value had changed. This seems pretty simple, not sure what I'm missing. That said, I'm very new to angular, so please correct me if I'm making assumptions I should not be.
HTML:

  Group by:
  <input type="radio" name="groupby" ng-model="groupby" value="1"/>Option 1
  <input type="radio" name="groupby" ng-model="groupby" value="2"/>Option 2

JS:

var app = angular.module('demo', []);

app.controller('SampleCtrl', function($scope) {
  $scope.groupby = 2;

  $scope.$watch($scope.groupby, function () {
    console.log($scope.groupby);
  });
});

Fiddle: http://jsfiddle.net/BLSully/WL7as/
Answer: the code should read
var app = angular.module('demo', []);

app.controller('SampleCtrl', function($scope) {
    $scope.groupby = 2;

    $scope.$watch('groupby', function () {
        console.log($scope.groupby);
      });
});

or, in the$watch expression you can use a function instead of a name
$scope.$watch(function () { return $scope.groupby }, function () {
    ...
});

using a function has advantages. you can, for example, watch for complex expressions, not just variables.
Comment: I knew it was going to be something stupid ;) Thanks for the answer. Assigning as answer for the extra tip about the ability for the first argument to be a function. Much appreciated!
Answer: The $watch is typically setup on the name of the scope property.  So, I'd expect to see something like this instead:
var app = angular.module('demo', []);

app.controller('SampleCtrl', function($scope) {
  $scope.groupby = 2;

  $scope.$watch('groupby', function () {
    console.log($scope.groupby);
  });
});

Here is an updated fiddle.
Comment: I knew it was going to be something stupid ;) Thanks for the answer.


Killing vector field of constant length on Riemannian manifolds

Question: I would like to solve next problem

A Killing vector field $X$ on a
  Riemannian manifold $(M, g)$ ($g$ is metric) has constant length if and
  only if every integral curve of the field $X$ is a geodesic
  in $(M, g)$.

I found here http://arxiv.org/pdf/math/0605371.pdf (Proposition 1) solution, but I don't understand what is $L$, how we define and use that $L$, and how from that (equation in proof) follows statement.
Or there is some alternative solutions?
My definiton of Killing vector field: Let $X$ be  vector field on a Riemannian manifold $(M,g)$ and $U$ neighbourhood of a point $p \in M$. Let $\varphi: (-\varepsilon, \varepsilon) \times U \to M$ is flow of vector field $X$. Then $X$ is Killing vector field if for every $t_0 \in (-\varepsilon, \varepsilon)$ mapping $\varphi_{t_0}:U \to M$ is isometry.
Comment: Where did you get that definition? Ordinarily $X$ is a Killing field if $\mathscr L_Xg=0$.
Comment: I was wondering the same thing, since I am familiar with $\mathscr L_X g = 0$ as well.  Perhaps the OP means *isometric immersion*?  Wouldn't we then have $\mathscr L_X g = 0$?
Comment: @TedShifrin That is definition from my class. But, I see now, there is problem in my book: Prove that $X$ is Killing vector field (my definition) iff $g(\nabla_Y X, Z)+g(\nabla_Z X,Y)=0$ for all $Y,Z \in \chi(M)$. Maybe to first show that? (I don't know how) One note: we didn't introduce Lie derivate $\mathscr L$ on class.
Comment: @RobertLewis I answered TedShifrin above. And YESSS, $\varphi_{t_0}$ is isometric, not immersion. My bad.
Comment: Sure. The flow by an infinitesimal isometry is an isometry :)
Comment: @user110822, since $\mathscr L_X g = \frac d{dt}\big|_{t=0} \phi_t^*g$, the Lie derivative condition is immediately equivalent to yours. That should be enough for you to figure out the proof in that paper.
Answer: Your definition of a Killing vector field $X$ implies that
\begin{equation}
g_t(Y,Z)=g_0(Y,Z)+O(t^2)\\\lim_{t \to 0}\frac{g_t(Y,Z)-g_0(Y,Z)}{t}=0
\end{equation}
the LHS is the definition of the Lie derivative i.e.
\begin{equation}
(L_Xg)(Y,Z)=0
\end{equation}
for any vector fields $Y$ and $Z$. So
\begin{equation}
(L_Xg)(X,Y)=0\\
Xg(X,Y)-g(L_XX,Y)-g(X,L_XY)=0\\
g(\nabla _XX,Y)+g(X,\nabla _XY)-g([X,X],Y)-g(X,[X,Y])=0\\
g(\nabla _XX,Y)+g(X,\nabla _YX)=0
\end{equation}
If the integral curve of $X$ is a geodesic, then $\nabla _XX=0$ and so
\begin{equation}
g(X,\nabla _YX)=0\\
0.5Yg(X,X)=0
\end{equation}
Then $X$ has constant length. Conversely, if $X$ has constant length then $Yg(X,X)=0$ and so $g(\nabla _XX,Y)=0$ for any vector field $Y$ and so $\nabla _XX=0$. the result.
Comment: Nice answer. Also, you might want to know that @-tagging only works in comments, not answers, unfortunately.


Como fazer um texto ficar de uma cor, e voltar à original?

Question: Eu estou tentando fazer, um "sistema" online, offline
Quando o usuário clica em "• Online", na qual a bolinha é verde, ela fica vermelha, e o texto atualiza para "• Offline"
Procurei, tentei, não achei e não conseguir fazer...
O que eu fiz foi isso:
 Online

Comment: Se alguma resposta resolveu seu problema marque-a como aceita. Veja como em https://i.stack.imgur.com/evLUR.png e porque em https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Answer: Pode fazer assim se quiser:

var icone = document.querySelector(".fa");
var texto = document.getElementById("foo");

icone.style.color = "green";  // inicializa com o botão verde
texto.textContent = " Online"; // inicializa com o texto online

function myFunction() {

  if(icone.style.color == "green"){
    icone.style.color = "red";
    texto.textContent = " Offline";
  } else {
    icone.style.color = "green";
    texto.textContent = " Online";
  }

}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Answer: Sua função possui um erro no if: o operador de comparação seriam dois sinais == e não apenas um (=). No JavaScript você compara se um valor é igual a outro com dois == — em alguns casos, até três: === (veja aqui os operadores usados em vários casos).
Outro problema é que dentro da função você está redefinindo o valor de online para 1, isso significa que ele sempre vai ser 1 no if seguinte.
Mesmo assim, também é preciso alterar o valor da variável online quando uma das condições for atendida (if...else). Em nenhum momento isso é feito, logo o valor da variável é sempre o mesmo.
Minha sugestão que que você defina no CSS a cor inicial do link, bem como o espaçamento do círculo ao texto, usando um margin-right, assim você não precisa colocar um caractere de espaço entre o círculo e o texto.
Para alterar o texto, pode usar os métodos nextSibling.textContent. O nextSibling irá selecionar o próximo nó após o círculo (no caso, o texto). E o textContent irá alterar o texto.
Para alterar a cor do link (logo, do círculo e do texto juntos), pode usar o método .parentNode. Como na função o seletor usado é o círculo, o .parentNode irá selecionar a tag  que é o pai.
Com essas correções, seu código poderia ser desta forma:

var online = 1;

function myFunction(){
   var onOff = document.getElementById("foo");

   if(online == 1){
      online = 0;
      onOff.parentNode.style.color = "darkred";
      onOff.nextSibling.textContent = "Offline";
   }else{
      online = 1;
      onOff.parentNode.style.color = "darkgreen";
      onOff.nextSibling.textContent = "Online";
   }
}
/* seleciona a tag  onde o atributo onclick começa com myFunction*/
a[onclick^='myFunction']{
   color: darkgreen;
}

#foo{
   margin-right: 5px;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">

   Online

Comment: O AP nada disse a respeito de mudar a cor do texto. To com dedo em cima do down  :)
Answer: Utilizando de short-if:
Online

Demonstração:
https://jsfiddle.net/leonardomsnt/mvc082n5/

Aplicação

Copie e cole o código
Crie duas classes, MINHA_CLASSE_VERDE e MINHA_CLASSE_VERMELHA
.MINHA_CLASSE_VERDE { background: darkgreen}
.MINHA_CLASSE_VERMELHA { background: darkred}

Recomendo:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator


Java Script - cloneNode(true), clone too much items

Question: I'll get to the point
What am I trying?:
I try to clone items so that every item, when clicked, clones itself. Even those that were cloned.
Problem:
The problem is that when I have e.g 10 items cloned, after clicking the first (original) item, it clones the next 10 items. Only the last (newest) clone, clones one element, no matter how many elements I already have.
Info:
Without app() at the end of the "clone" function, only the original element adds more clones.
It is problem with clondeNode() or maybe with wrong misaligned addEventListener?
Thanks for the help in advance, Matt
JS:
app = () => {
    const divs = document.querySelectorAll('.div');

    divs.forEach((div) => {
        div.addEventListener('click', () => clone(event))
    })

}

clone = (event) => {
    const div = event.target;
    const clone = div.cloneNode(true);

    document.body.appendChild(clone)

    app()
}

app()

HTML:

DIV FOR CLONING

Comment: every time you call app() you add more listeners!! `addEventListener` does not replace what is there.
Comment: Where do you declare the `event` variable being used in `() => clone(event)`?
Comment: It should be `(event) => clone(event)`
Answer: Inside the clone function you are calling the app() again
app = () => {
    const divs = document.querySelectorAll('.div');

    divs.forEach((div) => {
        div.addEventListener('click', () => clone(event))
    })

}

clone = (event) => {
    const div = event.target;
    const clone = div.cloneNode(true);

    document.body.appendChild(clone)

    app() // <<<<<<-------HERE
}

that ends in a recursion, because each time you click it will add a new listener.
https://codesandbox.io/s/agitated-cohen-0j6dm
  const clone = event => {
    const div = event.target;
    const cloned = div.cloneNode(true);
    document.body.appendChild(cloned);
    cloned.addEventListener("click", clone);
  };

Comment: Without app(), in the end of clone function, only the original element adds more clones.I want after clicking a cloned item, it also cloned itself.
Comment: Could you check

 const clone = event => {
    const div = event.target;
    const cloned = div.cloneNode(true);
    document.body.appendChild(cloned);
    cl
Answer: When calling app() after a click, you add a new event listener to all existing elements, which is in addition to the handler they already had attached to them.
Instead of calling app there, just add the listener to the newly created clone.
Secondly, you use the same name for a function and a variable. That is confusing.
So name that variable differently:
const clonedDiv = div.cloneNode(true);
document.body.appendChild(clonedDiv);
clonedDiv.addEventListener('click', clone);

As you see, you also don't need that arrow function. Just pass clone as a function argument.
Comment: Great, I understand and it work as it should
Thank You very much :)


Current tag synonym candidates

Question: I suggest adopting the following system for handling tags that could be made synonyms. The system has worked very well on Cross Validated: see here.

Please post your tag synonym suggestions as new answers in this thread, one answer per suggestion. Upvote answers where you believe that the suggested tags should be made synonyms, and downvote answers where you believe the tags should remain separate. Well upvoted suggestions will be eventually implemented by the moderators (and then the corresponding answers will be deleted).
Answer: asset-pricing (137) $\leftarrow$ asset-prices (11) (2 overlapping)

I wonder if there is any difference between these tags.
Comment: I set them as synonyms
Comment: @1muflon1, great, thank you!

Current tag synonym candidates


How to capture a complete view of an Activity Screen in Android

Question: I am using a scroll View in my activity.I want to share the whole activity screen but not able to do that.Am able to share the visible part of the screen but not the full screen of the activity.Is it possible to take the screenshot of the full activity.I have tried like this but its sharing only the visible part of the activity.Plz help me out of this.Thank You
<code>   ShareImageView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

             //View v1 = getWindow().getDecorView();

              View v1 = findViewById(android.R.id.content);

             v1.setDrawingCacheEnabled(true);
             myBitmap = v1.getDrawingCache();
             saveBitmap(myBitmap);

        }

    });
</code>
Saving the Screenshot taken ::
<code>  public void saveBitmap(Bitmap bitmap) {
     String filePath = Environment.getExternalStorageDirectory()
     + File.separator + "Pictures/screencapture.png";
     File imagePath = new File(filePath);
     FileOutputStream fos;
     try {
     fos = new FileOutputStream(imagePath);
     bitmap.compress(CompressFormat.PNG, 100, fos);
     fos.flush();
     fos.close();
     share(filePath);
     } catch (FileNotFoundException e) {
     Log.e("exception1", e.getMessage(), e);
     } catch (IOException e) {
     Log.e("exception2", e.getMessage(), e);
     }
     }
</code>
Answer: <code> try this:

     public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width , height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return b;
</code>
}
Comment: Am confused with the height and width which is used in the method.depending upon the screen size of the screen we need to pass the height and width of the screen.@Anantham
Comment: view.getWidth() and view.getHeight  @Gauravsingh
Comment: its working but still its taking the snapshot of the visible area not the whole activity screen shot.Any other way to capture the whole screen @Anantham


Andy Timmons Carpe Diem fast vibration

Question: This is a tough one :)
When I listen to this amazing track (track 14 from "That was then, This is now" album) I notice at 0:36 and 0:42 a very fast vibration on the G string (5th fret) which I doubt is possible using your fingers. I was wondering how exactly does he achieve this sound (its like a very fast and short vibration/trilling sound).
When I pull/release the tremolo bar (fast) it sounds like it but I was wondering how exactly he does it.
thx
Answer: Of all that sounds exceptional on that track (and there is much that's great on the track; thanks for bringing it to my attention), the vibrato isn't. It sounds good, but it sounds like finger vibrato. There might be some points where he uses the whammy bar, but most of it sounds like finger vibrato to me.
This video show Tom Hess giving a phrasing lesson, and it includes a wide and fast finger vibrato.
Comment: Thanks for the answer. I watched the video and it is definitely a standard finger vibrato (also in speed). If you listen very carefully to time 0:36 and 0:42 you will hear what I meant. (its very short but audible)
Comment: I watched three different Andy Timmons videos while he is playing "Carpe Diem" and there is nothing at 0:36 or 0:42 that he is not already doing with his hands. It's all in his hands.
Comment: Do  not watch the videos. listen to the studio track. I 100% positive the vibrato I mean is not the one you heard.
Comment: @VarLogRant, I heard today another track and the sound I talk about can be clearly heard at track : "That Was Then, This is Now" (From the same album) 1:26-1:28. And I really doubt it is done with by fingers
Comment: I don't know what that is, but I have an idea.

Consider the gap between the second and third strings. Here you go from G to B, which is a major third. One common lick is to bend the G string up to a note, not necessarily hitting it, with your middle and ring finger, then play that note on the B string, fretting it with your index finger. It is a canonical Chuck Berry move.

Now, hold the notes and kick up the gain, and you'll get the difference between those two notes acting up. I think that's what he's doing, but I could be wrong.
Comment: @VarLogRant I know about this one but its way to long to acomplish in the time interval you hear it. The best I tried was hitting the tremolo bar upwards (it releases immediately and produces this springy sound).

Andy Timmons Carpe Diem fast vibration


Division in the Ring of Integral Quaternions

Question: Consider the ring of integral quaternions, $\mathbb{I}$, with norm-like function $N(a+bi+cj+dk) = a^2+b^2+c^2+d^2$.
Let $z,w \in \mathbb{I}$, with $w \neq 0$. Prove that $\exists q, r \in \mathbb{I}$ such that $z = qw + r$, with $N(r) < N(w)$.
We already know such things like: $N$ is multiplicative, there are precisely 24 units in $\mathbb{I}$ every element in $\mathbb{I}$ is associate to an element with all coefficients integers.
Comment: I tried extending the proof that division works in $\mathbb{Z}[i]$ by looking at the "pretend" $z/w$ and finding two integers $e, f$ which are within 1/2 of each component of $z/w$, and using $q = e+fi$. However, in the quaternion case this means we get the remainder has norm at most 2, and there are plenty of integral quaternions with that small of a norm...
Answer: Your comment is basically correct; I think you just made a calculation error.  If each component of $x = z/w$ (of course, we have to pick a side for the division here), is rounded to the nearest integer to produce a quaternion $x_0$ with integer coefficients, then the norm between $x$ and $x_0$ will be no more than $(1/2)^2 * 4 = 1$ (not 2 as you said in the comment).  We are done, unless the distance is exactly 1, but I think you can figure out what happens in that case.
Comment: +1 It seems to me that the covering radius of the Hurwitz order $\mathbb{I}$ is $1/\sqrt2$, i.e. the same as with the lattice of the Gaussian integers in the complex plane.


Riemann-Lebesgue Lemma proof.

Question:
Assume that $f(x)$ is $2π$-periodic and square integrable on $(−π, π)$.

Can someone help me show how following statements are true
using Bessel's Inequality?
$$\lim_{n\rightarrow \infty}\int_{-\pi}^{\pi}f(x)\cos(nx)dx=0$$
$$\lim_{n\rightarrow \infty}\int_{-\pi}^{\pi}f(x)\sin(nx)dx=0~.$$
Comment: Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Answer: For each $n\in \mathbb{N}$, let $e_n(x)=\cos(nx)$. Then $\{e_n : n\in \mathbb{N}\}$ is an orthonormal family of functions in $L^2[-\pi, \pi]$. Hence, for any $f\in L^2[-\pi, \pi]$: $\sum\limits_{n=1}^\infty |\langle f, e_n\rangle|^2 \leq ||f||_2$. In particular we must hvae $|\langle f, e_n\rangle| \rightarrow 0$ which is exactly what you want. The proof is the same for the $\sin$ functions.
Comment: Perhaps you meant $e_n(x) = \frac{1}{\sqrt{\pi}}\cos(nx)$? (the remaining argument still follows since the normalization constant doesn't depend on $n$)
Comment: You are right, thanks

Riemann-Lebesgue Lemma proof.


Why would a query that returns 835 records in Access, return an empty recordset in VBA code?

Question: The following code is slightly modified from some boilerplate I use for almost every project I work on (in Access).  All the other versions of this code work perfectly in this db.  The tables are all actually in SQL Server but they are linked in this Access db.
Here's the weird part...When I run the code and get down into the "With rs" and do the ".Open", the next step "Do While Not .EOF" skips to the bottom of the "Do"...I am at .EOF!  But if I get a copy of the ".Source" SQL Statement and paste it into a blank SQL query on the non-code Access main window, I get 835 records from that query.  How could I be getting back an empty recordset when this query should return 835 records?
I've tried changing my .CursorType and .LockType, to no avail.
Anyone have any thoughts about what I could try in troubleshooting this?
<code>Public Sub test()
Dim db As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sFromDate As String
Dim sToDate As String
Dim sSubUnit As String

sFromDate = "1/1/2013"
sToDate = "1/31/2013"
sSubUnit = "2???"

' Make a connection to the db
Set db = CurrentProject.Connection

With rs
    .ActiveConnection = db
    .CursorType = adOpenForwardOnly
    .LockType = adLockReadOnly

    .Source = "SELECT SCEVENT.CLIENT_ID, SCATTEND.EMP_ID, SCATTEND.STARTDATE, SCATTEND.SVC_ID " & _
                "FROM SCATTEND LEFT JOIN SCEVENT ON SCATTEND.SCEVENT_ID = SCEVENT.ID " & _
                "WHERE (SCATTEND.STARTDATE Between #" & sFromDate & "# And #" & sToDate & "#) " & _
                    "AND (SCATTEND.SUBUNIT_ID Like '" & sSubUnit & "') " & _
                    "AND ((APPTYP_ID IS NULL) OR (APPTYP_ID IN (1,2))) " & _
                "ORDER BY SCEVENT.CLIENT_ID, SCATTEND.EMP_ID, SCATTEND.STARTDATE, SCATTEND.SVC_ID;"
    .Open
    Do While Not .EOF
        MsgBox "there are records!"
        .MoveNext
    Loop
    .Close
End With

Set rs = Nothing
Set db = Nothing
</code>
End Sub
Answer: It might have something to do with the difference between ADO and DAO
Difference between ADO and DAO
Comment: That was exactly it!  I changed the single character wildcards I was using in the sSubUnit string (from "2???" to "2%") and Voila'!  It works.  Thank you SO much for the article.


Intuition on the definition of the covariance

Question: I was trying to understand the Covariance of two random variables better and understand how the first person that thought of it, arrived at the definition that is routinely used in statistics.
I went to wikipedia to understand it better.
From the article, it seems that good candidate measure or quantity for $Cov(X,Y)$ should have the following properties:

It shoukd have a positive sign when two random variables are similar (i.e. when one increases the other one does to and when one decreases the other one does too).
We also want it to have a negative sign when two random variables are oppositely similar (i.e. when one increases the other random variable tends to decrease)
Lastly, we want the this covariance quantity to be zero (or extremely small probably?) when the two variables are independent of each other (i.e. they don't co-vary with respect to each other).

From the above properties, we want to define $Cov(X,Y)$. My first question is, it is not entirely obvious to me why $Cov(X,Y) = E[(X-E[X])(Y-E[Y])]$ satisfies those properties. From the properties we have, I would have expected more of a "derivative"-like equation to be the ideal candidate. For example, something more like, "if the change in X positive, then the change in Y should also be positive". Also, why is taking the difference from the mean the "correct" thing to do?
A more tangential, but still interesting question, is there a different definition that could have satisfied those properties and still would have been meaningful and useful? I am asking this because it seems no one is questioning why we are using this definition in the first place (it kind of feels like, its "always been this way", which in my opinion, is a terrible reason and it hinders scientific and mathematical curiosity and thinking). Is the accepted definition the "best" definition that we could have?

These are my thoughts on why the accepted definition makes sense (its only going to be an intuitive argument):
Let $\Delta_X$ be some difference of for variable X (i.e. it changed from some value to some other value at some time). Similarly for define $\Delta_Y$.
For one instance in time, we can calculate if they are related or not by doing:
$$sign(\Delta_X \cdot \Delta_Y)$$
This is somewhat nice! For one instance in time, it satisfies the properties we want. If they both increase together, then most of the time, the above quantity should be be positive (and similarly when they are oppositely similar, it will be negative, because the $Delta$'s will have opposite signs).
But that only gives us the quantity we want for one instance in time, and since they are r.v. we might overfit if we decide to base the relationship of two variables based on only 1 observation. Then why not take the expectation of this to see the "average" product of differences.
$$sign(E[\Delta_X \cdot \Delta_Y])$$
Which should capture on average what the average relationship is as defined above!
But the only problem this explanation has is, what do we measure this difference from? Which seems to be addressed by measuring this difference from the mean (which for some reason is the correct thing to do).
I guess the main issue I have with the definition is taking the difference form the mean. I can't seem to justify that to myself yet.

The interpretation for the sign can be left for a different question, since it seems to be a more complicated topic.
Comment: The very starting point may be the concept or intuition of cross-product (covariance is only the extension of it). If we have two series of numbers X and Y of the same length, and we define the summed cross-product as Sum(Xi*Yi), then it is maximized if both series were sorted in the same order, and is minimized if one series were sorted ascendingly and the other descendingly.
Comment: [This answer](http://stats.stackexchange.com/a/18200/805) provides a very nice piece of intuition relating to covariance.
Comment: The difference from the mean is not the fundamental issue. It is just the magnitude which matters, the difference from the origin; for some reasons it is naturally and convenient to put the origin into the mean.
Comment: @ttnphns are you saying that if they covary together then then the covariance should be "maximized" and if they covary opposite it should be as negative as it can? (i.e. minimized) Why isn't it defined then as the expectation of the cross-product?
Comment: Covariance is natural for variables without inherent origin. We then compute mean as the origin (mean have nice properties not relating to the theme of association, so it is typically chosen). If the origin is inherent and is meaningful, it is reasonable to stick to it, then "covariance" (co-outburst) won't be symmetric, but who cares?
Comment: @ttnphns I think I do agree that the starting point is the cross-product, but what about it? Do you have reference to read more/learn more on cross-product (summations)?
Comment: @ttnphns: you probably meant dot product (aka inner product)?
Comment: I think what @ttnphns is suggesting is considering the formula for covaraince, if we get a higher positive value of covaraince, then $X-\mathbb{E}[X]$ and $Y-\mathbb{E}[Y]$  are probably both sorted in a reletaviely same order, be it ascending or descending.
Answer: Imagine we begin with an empty stack of numbers. Then we start drawing pairs $(X,Y)$ from their joint distribution. One of four things can happen:

If both X and Y are bigger then their respective averages we say the pair are similar and so we put a positive number onto the stack.
If both X and Y are smaller then their respective averages we say the pair are similar and put a positive number onto the stack.
If X is bigger than its average and Y is smaller than its average we say the pair are dissimilar and put a negative number onto the stack.
If X is smaller than its average and Y is bigger than its average we say the pair are dissimilar and put a negative number onto the stack.

Then, to get an overall measure of the (dis-)similarity of X and Y we add up all the values of the numbers on the stack. A positive sum suggests the variables move in the same direction at the same time. A negative sum suggests the variables move in opposite directions more often than not. A zero sum suggests knowing the direction of one variable doesn't tell you much about the direction of the other.
It's important to think about 'bigger than average' rather than just 'big' (or 'positive') because any two non-negative variables would then be judged to be similar (e.g. the size of the next car crash on the M42 and the number of tickets bought at Paddington train station tomorrow).
The covariance formula is a formalisation of this process:
$\text{Cov}(X,Y)=\mathbb E[(X−E[X])(Y−E[Y])]$
Using the probability distribution rather than monte carlo simulation and specifying the size of the number we put on the stack.
Comment: Wow, this a very good answer. Just one last thing, do you mind adding more details on the justification on why it **has** to be the difference form the *mean*? Why not some other value? Why does it make sense? I think thats the main thing that is getting me stuck about fully internalizing this definition. Thanks btw!
Comment: Thanks. Suppose there are two big trucks in two different countries. Now big trucks tend to carry big loads. If we added a positive number to the stack every time each truck carried a big load we'd end up having to say that the behaviour of the two trucks was very similar. But actually the size of the load carried by one truck isn't related to the size of the load carried by the other at any particular time. They just happen to both be big trucks. So our measure of similarity wouldn't be useful. That's why we have to think about 'bigger than average'.
Comment: Sorry this is a little late, but I decided to review this topic and I still have a question about why its the difference from the mean. Is the difference from their respective means important because each random variable X and Y might come from different scales? i.e. To have a sense of what "big" is, its different depending on what base scale they are. So to overcome this issue of scale we compare it to their respective means?
Answer: Here is my intuitive way at looking at it without any equations.

Its a generalization of the variance to higher dimensions.
The motivation probably came from trying to describe how data behaves. To the first order, we have its location - the mean. To the second order, we have the scatter - the covariance.

I guess the main issue I have with the definition is taking the difference form the mean. I can't seem to justify that to myself yet.

the scatter is evaluated relative to the center of the distribution. The most basic definition of the variance is the 'mean deviation from the mean'. hence, you have to substract the mean also in the case of the Covariance.
Another prime motivation that comes to mind is the need to define a way to measure distance between random variables. The Mahalanobis distance and the Covariance come hand in hand: Given a Gaussian distribution and two other samples that have an equal Euclidean distance to the distribution mean.
If I would ask you which of the samples is more likely to be an outlier that was not drawn from the gaussian distribution, the Euclidean distance will not do. The Mahalanobis distance has a single notable difference from Euclidean distance: it takes into account the scatter (Covariance) of the distribution. This allows you to generalize distance to random variables.
Answer:

Lastly, we want the this covariance quantity to be zero (or extremely small probably?) when the two variables are independent of each other (i.e. they don't co-vary with respect to each other).

OK, let us consider two independent Bernoulli$\left(\frac 12\right)$
random variables $X$ and $Y$. If you are agreeable to allowing $E[XY]$ to mean covariance but are gagging on the subtraction of the mean, then we
can readily compute that $E[XY] = \frac 14$ which is pretty small. But
what about independent random variables $\hat{X}=1000X$ and
$\hat Y = 1000Y$ for which $E[\hat X \hat Y] = 250,000$? So the
covariance is not zero (or perhaps just small) as you want it to be for independent random variables.  On the other hand, the standard
definition cov$(X,Y) = E[(X-E[X])(Y-E[Y])]$ suffers from no such
defects, giving zero as the covariance value in both pf the simple
cases described above.

We also want it to have a negative sign when two random variables are oppositely similar (i.e. when one increases the other random variable tends to decrease)

So now, consider $X$ as before but define $Y = 1-X$. It is very clear
that as one variable increases, the other decreases. But, $E[XY]=0$
whereas the standard
definition cov$(X,Y) = E[(X-E[X])(Y-E[Y])]$ gives a negative value
just as you want it to.

It should (sic) have a positive sign when two random variables are similar (i.e. when one increases the other one does to and when one decreases the other one does too).

Once again, let $X$ be as before but now define $Y = X-1$. It is very clear
that as one variable increases, so does the other increase. But, $E[XY]$
is negative instead of being positive the way you want it to,
whereas the standard
definition cov$(X,Y) = E[(X-E[X])(Y-E[Y])]$ gives a positive value
just as you want it to.
Finally, the standard definition of covariance simplifies to the
definition of variance when $X = Y$.
Answer: I was wondering about the same question, and the intuition given by conjectures helped me. To visualise the intuition, I took two random normal vectors, x and y, plotted the scatterplot and coloured each point by the product of their deviations from their respective means (blue for positive values, red for negative).
As is clear from the plot, the product is most positive in the upper-right and bottom-left quadrants, while it is most negative in the bottom-right and upper-left quadrants. The effect of summing the products would result in 0, as the blue points cancel out the red ones.
But you can see that if we removed the red points, the remaining data exhibit a positive relationship with each other, which is validated by the positive sum of products (i.e. sum of the blue points).
Answer: in the vector space of random variables it is reasonable to define the square of  distance between two random variable x and y with E{(x-y)^2} now with respect to this   definition of distance dot product or relation of random variables will be E{x.y}
which is so similar to the definition of covariance except the terms -E{x} and -E{y} which are for kind of normalization.


Find possible values

Question: I want to verify a formula of the form:
Exists p . ForAll x != 0 . f(x, p) > 0 and g(x, p) < 0

All variables are reals.
As suggested here, I add this list to the solver:
[ForAll([x0, x1],
    Implies(Or(x0 != 0, x1 != 0),
        And(P0*x0*x0 + P1*x0*x1 + P2*x0*x1 + P3*x1*x1 > 0,
            -2*P0*x0*x1 + P1*x0*x0 - P1*x0*x1 - P1*x1*x1 + P2*x0*x0 - P2*x0*x1 - P2*x1*x1 + 2*P3*x0*x1 - 2*P3*x1*x1 < 0
            )
        )
    )
]

The solver with the above formula returns unsat. A possible solution is for P to be [[1.5, -0.5], [-0.5, 1]] and in fact, by substituting those values, the formula is satisfied:
And(3/2*x0*x0 - 1*x0*x1 + x1*x1 > 0,
    -1*x0*x0 - 1*x1*x1 < 0)

Is there a way to actually compute such a p? If it's hard for z3, is there any alternative for this problem?
Answer: When you say 'Exists' followed by 'Forall', then you are saying that the formula should be true for every such x0, x1. And Z3 is telling you that is simply not the case.
If you are interested in finding one such P, and corresponding x values, simply drop the quantification and make everything a top-level variable:
from z3 import *

def f(x0, x1, P0, P1, P2, P3):
    return P0*x0*x0 + P1*x0*x1 + P2*x0*x1 + P3*x1*x1

def g(x0, x1, P0, P1, P2, P3):
    return -2*P0*x0*x1 + P1*x0*x0 - P1*x0*x1 - P1*x1*x1 + P2*x0*x0 - P2*x0*x1 - P2*x1*x1 + 2*P3*x0*x1 - 2*P3*x1*x1

p0, p1, p2, p3  = Reals('p0 p1 p2 p3')

x0, x1 = Reals('x0 x1')
fmls = [Implies(Or(x0 != 0, x1 != 0), And(f(x0, x1, p0, p1, p2, p3) > 0, g(x0, x1, p0, p1, p2, p3) < 0))]

while True:
    s = Solver()
    s.add(fmls)
    res = s.check()
    print res
    if res == sat:
        m = s.model()
        print m
        fmls += [Or(p0 != m[p0], p1 != m[p1])]
    else:
       print "giving up"
       break

When I run this, I get:
sat
[x0 = 1/8, p0 = -1/2, p1 = -1/2, x1 = 1/2, p2 = 1, p3 = 1]

and many others; which is I believe what you're after.
Note that you can also do some programming to get rid of the existential quantification depending on where you are; i.e., start with the quantified version, if you get an unsat, then switch to a new solver and use the unquantified version to automate this process. Of course, this is just programming and doesn't really have anything to do with z3 at this point.
Comment: I'm really interested in finding a `P` for which all nonzero reals satisfy the formula; that `P` exists, because the one in the first post satisfy the formula for all nonzero reals
Comment: Also, when you say: "And Z3 is telling you that is simply not the case", then Z3 is wrong, because of that example. And introducing the values makes Z3's result be `sat`
Comment: @nyuw I didn't study the expression, but if you do believe Z3 is wrong, then that would be a rather serious bug that should be reported. (This is a soundness issue, and developers should know about it!) I'd encourage you to report it at their issue tracker: https://github.com/Z3Prover/z3/issues
Comment: @nyuw I've since looked at the expressions in more detail, and I think you're right that Z3 seems to be saying `unsat` for no good reason. Unless there's some other gotcha, this might very well be a bug. Please report this at their issues page. (Or I can do the same, let me know.)
Comment: I've created an issue; please let me know if you think it's properly written. I also wasn't exactly sure why I had to drop the `Exists` quantifier at the beginning (ref. my previous question); but even by adding it again, some of the values for `P` are wrong (?) or they don't work if hard coded (as I said in the issue). Let me know
Comment: @nyuw The bug is now fixed: https://github.com/Z3Prover/z3/issues/1637 If you do a build off of github (or wait for the nightly builds to come out), I think you'll find it now works as expected.
Comment: @nyuw It would be good to close the bug (https://github.com/Z3Prover/z3/issues/1637) if this is all working as expected now.
Comment: I just wanted to test it a bit more. Thank you so much :)

Find possible values


How to add internal path in *.links.menu.yml

Question: I am trying to add an internal link to admin toolbar but I am not able to achieve it.
According to documentation we add an internal link in *.links.menu.yml in the below manner but the link is not being appeared in the toolbar.
hello_world.admin2:
  title: 'Hello module settings'
  description: 'example of how to make an admin settings page link'
  parent: system.admin_config_development
  url: internal:/node/123

I tried the following variants as well but none works. url: 'internal:/node/123' or uri: internal:/node/123 or uri: 'internal:/node/123' .
But the following works url: http://localhost/node/123 .
Can anyone suggest me a way to create a menu link in *.links.menu.yml file.
Use case : I want to provide easily accessible link to user to access one particular page. It is not a route. I am aware of other way to create menu link by using MenuLinkContent::create method. But trying to figure out why above method is not working.
Comment: Related https://drupal.stackexchange.com/questions/253789
Answer: I don't know thy this doesn't work (it is a valid input for Drupal\Core\Url::fromUri), but /node/123 actually has a route:
hello_world.admin2:
  route_name: entity.node.canonical
  route_parameters:
    node: 123

Even though they are valid inputs, it is generally a good idea to avoid internal: URLs if you can use something better. "Something better" is either a route name (in the context of links.yml files) or an entity scheme entity:node/123 (in the context of storing links in the DB). AFAIK internal: was meant for local unrouted URLs like e.g. internal:/robots.txt
Comment: Thank you very much for the hint. It works. Bit i am still wondering why the method in question is not working. I will wait couple of days to check if anyone can provide any additional information on why it is not working. Or else I will mark your answer as accepted answer.
Answer: @miststudent2011 I think the idea you're missing is that a menu link offers either a route or a url.
From the Drupal 10.1 Menu API intro page:

links point to routes or URLs.

From the Drupal 10.1 documentation for function hook_menu_links_discovered_alter:

route_name: (optional) The route name to be used to build the path. Either the route_name or url element must be provided.
route_parameters: (optional) The route parameters to build the path.
url: (optional) If you have an external link use this element instead of providing route_name.

Put simply, use route_name for internal links.  Use url for external links.
Not both!


MongoKit "ImportError: No module named objectid " error

Question: I get some very strange error using MongoKit:
>>> from mongokit import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/mongokit/__init__.py", line 35, in <module>
    from document import Document, ObjectId
  File "/usr/local/lib/python2.7/dist-packages/mongokit/document.py", line 48, in <module>
    from pymongo.objectid import ObjectId
ImportError: No module named objectid

I tried everything to find the reason but nothing helps.
Actually I googled "ImportError: No module named objectid" error and it has no results at all. I tried to use MongoKit following the simple tutorial http://namlook.github.com/mongokit/introduction.html#a-quick-example and the first line of the tutorial produces this strange error. Below is the log of MongoKit installation.
What I'm doing wrong?
user@server:~$ sudo pip install mongokit
Downloading/unpacking mongokit
  Downloading mongokit-0.7.2.tar.gz (69Kb): 69Kb downloaded
  Running setup.py egg_info for package mongokit

Downloading/unpacking pymongo>=2.0.1 (from mongokit)
  Downloading pymongo-2.2.tar.gz (228Kb): 228Kb downloaded
  Running setup.py egg_info for package pymongo

Downloading/unpacking anyjson>=0.2.2 (from mongokit)
  Downloading anyjson-0.3.1.tar.gz
  Running setup.py egg_info for package anyjson

Installing collected packages: mongokit, pymongo, anyjson
  Running setup.py install for mongokit

  Running setup.py install for pymongo
    building 'bson._cbson' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.7 -c bson/_cbsonmodule.c -o build/temp.linux-i686-2.7/bson/_cbsonmodule.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.7 -c bson/time64.c -o build/temp.linux-i686-2.7/bson/time64.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.7 -c bson/buffer.c -o build/temp.linux-i686-2.7/bson/buffer.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.7 -c bson/encoding_helpers.c -o build/temp.linux-i686-2.7/bson/encoding_helpers.o
    gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-i686-2.7/bson/_cbsonmodule.o build/temp.linux-i686-2.7/bson/time64.o build/temp.linux-i686-2.7/bson/buffer.o build/temp.linux-i686-2.7/bson/encoding_helpers.o -o build/lib.linux-i686-2.7/bson/_cbson.so
    building 'pymongo._cmessage' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.7 -c pymongo/_cmessagemodule.c -o build/temp.linux-i686-2.7/pymongo/_cmessagemodule.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.7 -c bson/buffer.c -o build/temp.linux-i686-2.7/bson/buffer.o
    gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-i686-2.7/pymongo/_cmessagemodule.o build/temp.linux-i686-2.7/bson/buffer.o -o build/lib.linux-i686-2.7/pymongo/_cmessage.so

  Running setup.py install for anyjson

Successfully installed mongokit pymongo anyjson
Cleaning up...

Answer: It's an error in the dependencies. As of PyMongo 1.11 objectid lives in the bson module, not pymongo.
Comment: Is there any way to solve it? Or should I re-write 3rd party source code? It's a very basic thing, actually the first line of the tutorial and doesn't work. 'coz all I'm doing - just importing "from mongokit import *"
Comment: Keep in mind it's not yet pulled in. Alternatively, you could try downgrading to 2.1.1, that should be the last version with the fallback.
Answer: As Electro said, it's a Bug.
I used the following dirty little hack to keep my site running until it is fixed:
import sys
import pymongo
import bson.objectid
pymongo.objectid = bson.objectid
sys.modules["pymongo.objectid"] = bson.objectid


Would cache in files be an alternative?

Question: Once I worked in a company that had its own CMS and we used to cache data in files so basically the system would check if the cache file existed, if not it would go to the database, get the data, save it in a file and then show it to the users (basic cache thing). This resulted in less connections to the database.
I would like to know if this is a good option to Drupal or if there is any problems with this way of caching things.
Answer: As anschauung mentioned you can use Boost to create a static page cache. Boost will copy the entire HTML of a page and store that HTML as a static file on the disk in a specific directory. A set of rewrite rules will cause the webserver to first look for a static HTML file for each request and serve that file if it's found. If it isn't, a normal Drupal request occurs via PHP. Requests served through the static file will be really fast, but PHP and the database are completely bypassed.
Boost is not a replacement for the cache backend and that Drupal will still use the cache tables in the database when a miss occurs on the static HTML files created by Boost. If you want to completely replace the cache backend, you could look into memcache, which stores serialized objects in memory. Memcached runs as a daemon on the server and can be connected to via TCP. This can be both a good and bad thing, depending on number of servers in the environment and
Note that it is possible to have the database keep the cache tables in memory as well (at least with MySQL), although I'm not sure about the specifics of doing so.
You could all use the APC module if you're running Drupal 7. The APC modules integrates with the APC opcode cache and uses it as Drupal's cache backend. APC can be faster than memcached in certain scenarios because there is no TCP connection overhead. Each APC cache is tied to a specific server, while memcached and the database can be shared by multiple front end servers (again, this can be good or bad).
Comment: To follow on from this, cache behaviour more like memcache/APC, but with files as the storage medium (so no 3rd party software) is possible with Drupal 6 via the CacheRouter module. This is being continued in to Drupal 7 via the FileCache module, which died during Drupal 6 but is being resurrected by a new maintainer right now - both of these options *are* file caching but are not the model Boost uses (though I understand the Boost maintainer wants to move that way in Drupal 7, ultimately).
Comment: Thanks Greg, that's good info. Didn't know what other cache backends there were.
Comment: In reply to Greg's answer about Boost's future (yeah I don't have enough juice to comment yet) here is the comment about a potential merge with the [filecache](http://drupal.org/project/filecache) module: http://groups.drupal.org/node/131639#comment-427114. Main point of something like this is to use more Drupal APIs, allow custom logic that can't be done in htaccess rules, lower the bar for adoption, & eventual option for core inclusion. A simple html file cache should be apart of core IMHO as it offers huge gains on cheap hosting.
Answer: In fact, the Boost module does exactly what you're describing -- it creates file caches of pages and re-checks the database if a particular file doesn't exist.
Give it a look :)
Answer: While the Boost module accomplishes the same method, there are many alternatives that may perform even better, such as the Drupal page cache (which caches the whole page into a single database record), memcache, or even Varnish.

Would cache in files be an alternative?


Can I select hierarchy based on it's name in hiera.yaml file in puppet?

Question: I am using hiera5 and I want to read hierarchies from one of the groups based on their names.
For e.g. Currently I have:
version: 5
defaults:
  datadir: "/"
  data_hash: yaml_data
hierarchy:
  - name: "ABC"
    paths:
      - "env/env-data1.yaml"
      - "env/env-data2.yaml"
      - "env/env-data3.yaml"

I want to add multiple hierarchies like this:
hierarchy:
  - name: "ABC"
    paths:
      - "env/env-data1.yaml"
      - "env/env-data2.yaml"
      - "env/env-data3.yaml"
  - name: "DEF"
    paths:
      - "env/env-data4.yaml"
      - "env/env-data5.yaml"
      - "env/env-data6.yaml"
  - name: "GHI"
    paths:
      - "env/env-data7.yaml"
      - "env/env-data8.yaml"
      - "env/env-data9.yaml"

And read files from just one of the groups at a time lets say just 'ABC'.
Is there a way I can pass hierarchy name as parameter while calling puppet script ?
Additional Info:
I am running a shell script from jenkins which triggers the puppet script.
puppet apply --hiera_config=${WORKSPACE}/hiera.yaml ${WORKSPACE}/puppet-script.pp

Thanks in advance!
Answer:
I want to add multiple hierarchies like this: [...]

The syntax is fine, but it does not describe multiple hierarchies.  It describes one multi-level hierarchy (which is in fact the usual case).  Having multiple levels is what makes it hierarchical -- it is the distinguishing characteristic of Hiera relative to other external-data mechanisms that Puppet has had.

And read files from just one of the groups at a time lets say just 'ABC'.

Nope, not happening.  Hiera does not work that way.

Is there a way I can pass hierarchy name as parameter while calling puppet script ?

No, but you can specify a different hiera.yaml configuration file, as you already demonstrate.  If you want different hierarchies for different runs then define each in its own (full) configuration file, and choose the appriate config file for each use.
Comment: Thank you John for your reply.
Having multiple hiera.yaml is what my approach currently.


A continuos map preserves (path-)connectedness, compactness

Question: It is clear that continuous maps preserve those properties. What about the reverse?
If a map maps every path-connected space to path connected then it is continuous? Also for connectedness, compactness And so on, what property are strong enough to indicate continuity?
Answer:
(path) connected: No, take any discontinuous function $\mathbb{Q}\to\mathbb{Q}$. Note that $\mathbb{Q}$ is totally disconnected, i.e. a subset of $\mathbb{Q}$ is (path) connected if and only if it is a singleton.
compact: Again no, take any discontinuous function $X\to C$ where $C$ is finite discrete. Obviously image of every subset is compact.

what property are strong enough to indicate continuity?

It is unlikely you will find any such property for general topological spaces. In some specialized context it may be possible, e.g. being differentiable.


Slider Range do jQuery

Question: Olá, tudo bem?
Tenho um código que filtra os dados de um JSON com jQuey, eu consigo filtrar com valores pre-definidos em uma variável. Mas queria utilizar os valores de um slide range do jquery ui para filtrar o json, só que quando tento fazer isso não consigo ele fica retornando vazio.
Alguém sabe como posso utilizar o slide range para tal operação? Obrigado
Estou fazendo um filtro em JavaScript com Jquery onde ele filtra um resultado que está em Json, mas não estou consguindo fazer com que ele filtre utilizando um slider range do Jquery UI.
JSON

var json = {
       "tpAmbiente":null,
       "hotelPesquisa":[
          {
             "dtEntrada":"20170510",
             "dtSaida":"20170511",
             "hotel":{
                "id":94,
                "nome":"Itamarati"
             },
             "quarto":[
                {
                   "quartoUh":[
                      {
                        "nQUarto": 1,
                         "tarifa":{
                            "vlDiariaTotal":157.21,
                            "desconto":null
                         },
                         "qtDisponivel":null,
                         "desconto":null
                      },
                      {
                        "nQUarto": 2,
                         "tarifa":{
                            "vlDiariaTotal":157.21,
                            "desconto":null
                         },
                         "qtDisponivel":null,
                         "desconto":null
                      },
                   ]
                }
             ]
          },
          {
             "dtEntrada":"20170510",
             "dtSaida":"20170511",
             "hotel":{
                "id":95,
                "nome":"copacabana"
             },
             "quarto":[
                {
                   "quartoUh":[
                      {
                        "nQUarto": 1,
                         "tarifa":{
                            "vlDiariaTotal":102.1,
                            "desconto":null
                         },
                         "qtDisponivel":null,
                         "desconto":null
                      },
                      {
                        "nQUarto": 2,
                         "tarifa":{
                            "vlDiariaTotal":102.1,
                            "desconto":null
                         },
                         "qtDisponivel":null,
                         "desconto":null
                      },
                   ]
                }
             ]
          },
          {
             "dtEntrada":"20170510",
             "dtSaida":"20170511",
             "hotel":{
                "id":96,
                "nome":"Itamarati"
             },
             "quarto":[
                {
                   "quartoUh":[
                      {
                        "nQUarto": 1,
                         "tarifa":{
                            "vlDiariaTotal":157.21,
                            "desconto":null
                         },
                         "qtDisponivel":null,
                         "desconto":null
                      },
                      {
                        "nQUarto": 2,
                         "tarifa":{
                            "vlDiariaTotal":157.21,
                            "desconto":null
                         },
                         "qtDisponivel":null,
                         "desconto":null
                      },
                   ]
                }
             ]
          },
          {
             "dtEntrada":"20170510",
             "dtSaida":"20170511",
             "hotel":{
                "id":96,
                "nome":"Litoral Hotel"
             },
             "quarto":[
                {
                   "quartoUh":[
                      {
                        "nQUarto": 1,
                         "tarifa":{
                            "vlDiariaTotal":1001.00,
                            "desconto":null
                         },
                         "qtDisponivel":null,
                         "desconto":null
                      },
                      {
                        "nQUarto": 2,
                         "tarifa":{
                            "vlDiariaTotal":1001.00,
                            "desconto":null
                         },
                         "qtDisponivel":null,
                         "desconto":null
                      },
                   ]
                }
             ]
          }
       ]
    };

Função

function filtro(min, max){
    var pesquisa = {
      min: min,
      max: max
    };
    var filtrados = json.hotelPesquisa.filter(function(hotel) {
        hotel.quarto[0].quartoUh = hotel.quarto[0].quartoUh.filter(function(quarto) {
            return quarto.tarifa.vlDiariaTotal  dados.min;
        });
        return hotel.quarto[0].quartoUh.length > 0;
    });
    console.log(filtrados);
}

Eu utilizo o Jquery UI o slider range que o código e:

$("#price-range").slider({
    range: true,
    min: 0,
    max: 1000,
    values: [ 0, 1000 ],
    slide: function( event, ui ) {
        tjq(".min-price-label").html(ui.values[ 0 ]);
        tjq(".max-price-label").html(ui.values[ 1 ]);
        filtro(ui.values[ 0 ], ui.values[ 1 ]);
    }
});

Quando eu arrasto o slider ele chama a função filtro passando os parametros min e max para poder filtrar o json com os valores minimos e maximos do slider.
no começo ele ate filtra mas depois que arrasto o slider varias vezes ele retorna vazio:
[]
Alguém sabe como posso resolver isso? Obrigado!
Comment: Que tal você [edit] sua pergunta e adicionar o seu código? Ficará muito mais fácil entendermos o que você está querendo. Busque também fazer um [mcve] para que possamos verificar as soluções.
Comment: @AndersonCarlosWoss Espero que assim fique melhor de entender.
Answer: Sempre que possível, coloque o seu código completo no JSFiddle ou outra ferramenta semelhante. Assim podemos ver o problema ocorrendo e fica mais fácil avaliar.
Fiz um exemplo com base no seu código. Se necessário, edite o código, clique em Update e me mande o link.
Os valores filtrados estão aparecendo no log do console.
Exemplo - JSFiddle.
Comment: Obrigado. O meu problema e o seguinte. Preciso que o filtro me retorne o um json com todos os hoteis onde os preços dos quartos sejam maior que 0 e menor que 1010 com valores definidos manualmente em um array ele filtra normal mas quando utilizo o slide range ele não filtra. ele começa a filtrar quando deslide o slide range mas depois começa a retornar so [] como mostra ** [NESTA IMAGEAM](https://uploaddeimagens.com.br/imagens/sssssssssssssss-png--3) ** o link do JSFiddle olha no console https://jsfiddle.net/newtech/xrkuoqhq/2/
Comment: Percebi que no seu código, caso não haja hotel que se enquadre no filtro (ex.: Min=200 Max=900), a variável **filtrados** não volta a pegar os valores. Por conta da falta de experiência, não posso dizer porque isso ocorre. Contudo, veja que no meu exemplo, usando o loop `for (i = 0; i < filtrados.length; i++)` esse problema não ocorre.
Comment: No seu exemplo tem como ele retornar o json ao invés de retornar o preço?
Comment: Sim. Em console.log troque **valorQuarto** por **filtrados** `if (valorQuarto >= min && valorQuarto <= max) {
      console.log(filtrados);
    }`
Comment: Repare que ele sempre retorna 4 objetos e neles tem quartos onde o preço não enta dentro dos valores do slide: https://uploaddeimagens.com.br/imagens/sssssssssssssss-png--5

Slider Range do jQuery


Will hooking the output on a monitoring loudspeaker to a bass amp instead of a subwoofer damage anything?

Question: I bought a Thump15a and plan to use a focusrite scarlett solo with it. My brother plays bass and has a bass amp, and so I was wondering if I could take the output of the thump15a and plug into the input of the bass amp, while setting the mode of the thump15a to sub (this takes out the low end from the loudspeaker and lets the bass amp handle it instead). The only danger I see is that the output is line level whereas the input to the amp is instrument level. What do you guys think?
I am not using a stereo setup (as I only have one loudspeaker), so I could also hook up the scarlett solo directly to the bass amp (but again I believe the output on the scarlett solo is line level). What is the difference between these two setups?
Answer: The usual way to connect a line output to an instrument input is using a DI (typically passive) with an attenuation switch and a ground lift switch.  That's comparatively advisable since instrument inputs tend to be rather sensitive to ground loop hum.
The Thump15A already has a 15" bass speaker.  The typical bass amp will not really offer to move much more air.  Its specified range starts at 32Hz and in the images and instructions I see nothing that would point towards a ported design (that uses a resonance port for lowering the specified bass response while giving higher rolloff below it at the cost of a more sluggish phase response).
A compact subwoofer tends to give more "oomph" at the cost of an even more sluggish phase response.  A typical bass amp, however, is supposed to deliver a very precise onset at the cost of considerably coloring the signal and partly adding its own characteristics.  That makes it an instrument amplifier and implies, among other things, that it will become locatable as the source of sound due to the characteristics of its nonharmonic distortions.  Good for an instrument amp, bad for a PA component.
Mackie's dedicated subwoofer uses an 18" speaker.  That can move more air than a 15" speaker without overly relying on resonance trickery.  If you want to project a really big bass drum (like when working with electronic drums) or a church organ, this can make a difference compared to the unadorned Thump15A.  For most other purposes, I am skeptical that using this functionality with a separate bass speaker cabinet is going to buy you much of an improvement.  And I am particularly skeptical that using a bass guitar amp will make any reasonable sense as part of a setup in connection with a Thump15A.
Answer: This may work. If there is any level mismatch you should be able to adjust it with the gain knob on the bass amp (make sure the amp doesn't clip at large volumes). But...

Thump15a manual says sub mode rolls off low frequencies on the speaker, but it doesn't roll off high frequencies on the output (you want to connect to an amp), so you'll need to do it by yourself. A proper way is to use a crossover. Maybe turning high and mid knobs on the amp all way down will suffice, maybe not. You risk having the bass amp sound interfering with Mackie's sound.
Why do you want to add a subwoofer in the first place? For stage monitoring you perhaps don't want a subwoofer at all. For PA you may have trouble to get good sound without a proper crossover.
Bass amp and cab might not be as good in reproducing very low frequencies as you may naively think. And very likely it is not reproducing the input sound neutrally.


guitar beginner level - chord voicings

Question: I have been playing guitar for a few years and lately I have been studying some music theory. So what is the difference between playing the bmaj chord with the root note in the fifth string (A string) second fret, with root note in the sixth string (Low E string) 7th fret and with the root note in the fifth string 14th position (octave higher than first version). The notes for each chord are

b3, f4#, b4, d5#, f5#
b3, f4#, b4, d5#, f5# and b5
b4, f5#, b5, d6#, f6#

they all have the b note but the second one has a b5 note extra and the third one has the notes one octave higher.  Soooo for example if I play the chords in a unspecified c scale (the c scale stars on the middle c which corresponds to the c4 note on piano) - which version of the b chord should I play?  There must be a logical answer for this.  It can not just be like its the same if you play it in the 5th fret and in the 14th fret...
The same question would apply to the other chords too.  I hope I'm not to confusing.
Comment: I edited your question because your string numbering is the opposite of what most guitarist have been taught.  The first string is the skinniest string and is the 6th string if you count starting with the one closest to your head when you play but it's commonly known as the FIRST string.  The Sixth String is the fattest string (looks like it should be called the first string because it's the first one you hit if you do a down strum on all 6 strings).  Also, I assume when you refer to middle c and c4 and b4 you mean the corresponding pitch on piano.  But it's still not clear what you are asking
Comment: What do you mean by "if I play the chords in a unspecified c scale"?  There are several places on the guitar fretboard where you can play a C major scale (although some start on C3).  And by unspecified do you mean either C minor, C major, C melodic minor, C harmonic minor?  Specify what you mean by unspecified.  Also, there are no chords in a scale.  A scale is individual notes.  So I don't know what you mean by "the chords in a c scale".  Do you mean chords in the key of c?  Or do you mean you want to play a scale based on a chord formation?
Comment: Consider editing for grammar and capitalisation. That should make your question easier to read.
Comment: Difficult to understand, this, maybe you number the strings from the wrong end, too?
Comment: What's the difference? They sound different, right? Well, that's the difference.
Comment: @ToddWilcox If the OP ever logs back in to the site and clarifies the tru nature of the question it might be worth answering - but I can't figure out what the real question is.  Surprised there are no close votes for "not clear what you are asking".
Comment: hello. thank you for being understandive.i have just learned some music theory and im trying to fit it into my guitar playing.the problem is that i find it very hard to formulate my question.someone commented "Overall when learning music theory you should keep in mind that there is no "correct" way. Music theory is not a set of rules that you must follow and obey, it is simply a set of tools to help you create your own music and to better understand other people's music. You can choose to use these tools or not as you see fit. :)"..i think that would be the most apropriate answer.still thanks.
Answer: There is no correct answer as to which chord you "should" play because you can use whichever chord you think sounds best in a given situation.
What you're describing is essentially changing the voicing or the way the chord sounds without changing the chord. There are many, many ways to play the same chord but each one has its own unique sound. Here are just a few different ways of playing the B major on guitar:
http://www.guitar-chords.org.uk/b-major-chord.html
And that's not even close to all of them as you can omit notes, skip strings, you can play with a capo or use an alternate tuning on the guitar which provides even more options for different chord voicings, etc. and all of these things change the way the chord sounds and none of them are "wrong" or "correct", they are just different.
To give an analogy, asking which version of a B major chord to play is like asking what color of blue to paint the sky in your painting. In the same way, there is no correct or wrong answer and it's up to you to figure out what color blue you want your sky to be.
I'd say that the only exception here is if you are trying to learn a song written/played by someone else and you want to know the specific voicing of B major they used in their song so that you can sound exactly like the original when you play it. But when you are writing your own material, there is no right answer and it's simply a matter of which version of B major you like.
You should experiment with different versions of the same chord and train your ear to hear the subtle (or not so subtle) changes that they make. You might find that you like the 2nd fret B major for one song but like the 14th fret B major in a different song. Or maybe even just 3 strings instead of playing 5 or 6 strings. Etc.
Overall when learning music theory you should keep in mind that there is no "correct" way. Music theory is not a set of rules that you must follow and obey, it is simply a set of tools to help you create your own music and to better understand other people's music. You can choose to use these tools or not as you see fit. :)
Answer: As a supplement to Tekkerue's excellent answer, there are situations where it's very useful to know multiple voicings, specifically different inversions of the same chord for creating moving basslines.
Being able to change shape without changing the chord makes more of the fretboard usable for extending the range of the bassline as a separate voice.

guitar beginner level - chord voicings


codeigniter - custom validation

Question: This is my extended class for form_validation:
<?php
class MY_Form_validation extends CI_Form_validation
{
    function __construct($config = array()) {
         parent::__construct($config);
    }
    function count_errors(){
        if (count($this->_error_array) === 0){
            return 0;
        }
        else
            return count($this->_error_array);
    }

    public function max_number($num, $val) {
        if($num > $val){
            $this->set_message("max_number", "The %s can not be greater then "  . $val);
            return false;
        }
    }

    public function min_number($num, $val) {
        if($num < $val){
            $this->set_message("min_number", "The %s can not be smaller then "  . $num);
            return false;
        }
    }

    public function error_array(){
        return $this->_error_array;
    }
}

And then in controller I set up rule like this for example "num" field:
$this->form_validation->set_rules('num', "Number", 'required|numeric|min_number[1]|max_number[99]');

For example 56 passes but also 1903.
But if num field is 0 it works.
So, this is working only for min_num but does not work for max_num.
What I am doing wrong here?
Answer: Codeigniter already has a built-in function for this, greater_than[1] and less_than[99]
However, to get your functions working you need to return true (well, !== FALSE) i.e.
 public function max_number($num, $val) {
    if($num > $val){
        $this->set_message("max_number", "The %s can not be greater then "  . $val);
        return false;
    }

    return true;
}

public function min_number($num, $val) {
    if($num < $val){
        $this->set_message("min_number", "The %s can not be smaller then "  . $num);
        return false;
    }

    return true;
}

Hope this helps!

codeigniter - custom validation