Nested Grouping using XSLT 1.0

Question: I'm having some difficulties with nested grouping in XSLT 1.0. The problem is a few documents have multiple products in their metadata. First, I need to group the results by the products. Finally, grouping by types is expected as well. Actually, I gained the goals using for-each-group instruction from XSLT 2.0. But the thing is, I`m not able to change the version of XSLT in my project.
I would greatly appreciate it if someone could help me to implement this requirements in XSLT 1.0. I`m wondering if it is possible to use the Muenchian method there and what the named keys are look like.
Here is an example of input xml:
<result>
    <document>
        <metadata>
            <title>Academic Program Directors</title>
            <type>typeA</type>
            <product>Product1</product>
            <product>Product2</product>
            <product>Product3</product>
        </metadata>
    </document>
    <document>
        <metadata>
            <title>Administrative Directors</title>
            <type>typeA</type>
            <product>Product2</product>
        </metadata>
    </document>
    <document>
        <metadata>
            <title>Program Managers</title>
            <type>typeB</type>
            <product>Product1</product>
            <product>Product3</product>
        </metadata>
    </document>
</result>

The expect output would be the following:
Product1
    typeA
        Academic Program Directors
    typeB
        Program Managers

Product2
    typeA
        Academic Program Directors
        Administrative Directors

Product3
    typeA
        Academic Program Directors
    typeB
        Program Managers

Here's the XSLT 2.0 solution
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="html" indent="yes"/>

    <xsl:template match="/result">
        <xsl:for-each-group select="document/metadata" group-by="product">
            <xsl:sort select="current-grouping-key()"/>

                <xsl:value-of select="current-grouping-key()"/>

            <xsl:for-each-group select="current-group()" group-by="type">
                <xsl:sort select="current-grouping-key()"/>

                    <xsl:value-of select="current-grouping-key()"/>

                <xsl:for-each select="current-group()">

                        <xsl:value-of select="title"/>

                </xsl:for-each>
            </xsl:for-each-group>
        </xsl:for-each-group>
    </xsl:template>
</xsl:stylesheet>

Comment: So which XSLT 1 processor do you use, any support for e.g. http://exslt.org/set/functions/distinct/index.html?
Comment: @MartinHonnen we use Apache Xalan processor and it seems as set:distinct function is supported there. Thank you for your help and guidance!
Answer: A lot of XSLT 1 processors implement set:distinct (http://exslt.org/set/functions/distinct/index.html) so with that you can use the approach in http://xsltransform.net/bEzjRKX which does
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
  xmlns:set="http://exslt.org/sets" exclude-result-prefixes="set">

    <xsl:output method="html" indent="yes"/>

    <xsl:template match="/result">
        <xsl:variable name="metas" select="document/metadata"/>
        <xsl:for-each select="set:distinct($metas/product)">
            <xsl:sort select="."/>

                <xsl:value-of select="."/>

            <xsl:variable name="current-group" select="$metas[product = current()]"/>
            <xsl:variable name="types" select="set:distinct($current-group/type)"/>
            <xsl:for-each select="$types">
                <xsl:sort select="."/>

                    <xsl:value-of select="."/>

                <xsl:for-each select="$current-group[type = current()]">

                        <xsl:value-of select="title"/>

                </xsl:for-each>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:template>

</xsl:transform>

Using keys and Muenchian grouping I think the problem can be solved with
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
  xmlns:set="http://exslt.org/sets" exclude-result-prefixes="set">

    <xsl:output method="html" indent="yes"/>

    <xsl:template match="/result">
        <xsl:variable name="metas" select="document/metadata"/>
        <xsl:for-each select="set:distinct($metas/product)">
            <xsl:sort select="."/>

                <xsl:value-of select="."/>

            <xsl:variable name="current-group" select="$metas[product = current()]"/>
            <xsl:variable name="types" select="set:distinct($current-group/type)"/>
            <xsl:for-each select="$types">
                <xsl:sort select="."/>

                    <xsl:value-of select="."/>

                <xsl:for-each select="$current-group[type = current()]">

                        <xsl:value-of select="title"/>

                </xsl:for-each>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:template>

</xsl:transform>

Online at http://xsltransform.net/ehVYZNZ
Comment: thank you a lot for the help! Both solutions are elegant and work fine for me. Especially thanks for the new function set:distinct I found because I`ve never seen it in the templates. Will try to adopt the first solution in my project.

Nested Grouping using XSLT 1.0


Geometrical interpretation of modulus of a cross product

Question: Context: this question is set as an A-level question.
When we want to interpret modulus of a cross product, there are usually two scenarios:

For the case where $\mathbf{a}$ and $\mathbf{b}$ are position vectors, $|\mathbf{a}\times\mathbf{b}|$ is area of a parallelogram with $\mathbf{a}$ and $\mathbf{b}$ as adjacent sides;
For the case where $\mathbf{a}$ is a unit vector, we can also see $|\mathbf{a}\times\mathbf{b}|$ as shortest distance from $B$ to $OA$.

However I saw this one today: $\left|\vec{OA}\times \dfrac{\vec{AN}}{|\vec{AN}|}\right|$. I believe context of $A$ and $N$ does not matter, and $O$ is the origin. I certainly cannot see this is perpendicular distance from $A$ to $AN$, since we have to show that this is equal to some nonzero value.
Sorry for the bad formatting; apart from the \vv command I am not sure how to represent a vector here.
Comment: You can use \vec to draw the vector arrows.
Comment: Does it help to note that $\frac{\vec{AN}}{|\vec{AN}|}$ is a unit vector?
Comment: @Spencer thanks for the heads up and edit.
Comment: @StinkingBishop that i noticed, but as i said i dont think it should mean perpendicular distance from A to AN.
Comment: In physics, the modulus of the cross product might represent torque.
Answer: $$|\vec a \times \vec b|= ab \sin \theta$$
1-$|\vec a \times \vec b|$ is the area of parallelogram whose adjacent  sides are represented
by $\vec a$ and $\vec b$.
2-$|\vec a \times \vec b|$ is twice the area of whose adjacent sides are represented
by $\vec a$ and $\vec b$.
3- $|\vec a \times \vec b|$ area of parallelogram whose adjacent  sides are represented
by $\vec a$ and $\vec b$ is twice the area of infinitely many quadrilaterals whose diagonals are $\vec a$ and $\vec b$.
Here, $\vec a, \vec b$ are not position vectors the are absolute vectors.
Edit:
To OP:
$$\left |\vec OA \times \frac{\vec ON}{|\vec ON |}\right|$$ is the length  of perpendicular projection of $\vec OA$ perpendicular to $\vec ON$ wgich is the length of $\vec AN$
Comment: yeah i understand all these, but the issue here is that $\vec{AN}$ here is not a position vector.
Comment: @Kenny Wong  Thanks, you may like my edit.
Answer: I have found the solution after some searching. apparently it will be like (1) as posted, but using $A$ as point of reference here, so the answer is perpendicular distance from $O$ to $AN$.


Load test for Registration page in jmeter

Question: I have a thread group with register page.
Iam try to do concurrent unique users registrations as much as my website can handle.
Till now I have recoded script for single user for registering and parameterizing with different unique users data manually in csv file and replacing in recorded script. But it is difficult to modify for huge no of users while registering.
Is there any simple way to do this?
Answer: If you are testing registration process you don't need a pre-defined data set as you are creating users "on-the-fly". Therefore you can use random data instead of pre-defined, for example

if you need an email you can generate one using __RandomString() function like:
<code>${__RandomString(15,abcdefghijklmnopqrstuvwxyz)}@example.com
</code>
if you need a random date (for example of birth) you can use __RandomDate() function like:
<code>${__RandomDate(,1950-01-01,2018-01-01,,)}
</code>
if you need a random number - go for __Random() function
<code>${__Random(0,9999999,)}
</code>
if you need a totally unique identifier - use __UUID() function
<code>${__UUID}
</code>
you can get current timestamp in different formats with __time() function
<code>${__time(EEEE\, dd MMMM yyyy hh:mm:ss a,)}
</code>

Demo of above functions:

More information on JMeter Functions: Apache JMeter Functions - An Introduction
Comment: I simply know how much of users can handle my application.Is there any chance to repeat the same data if I use random function , for easier convenient me?


Get bandwidth value eth0, ifconfig on python script

Question: Get bandwidth value ifconfig on python script : How to manipulate value from ifconfig eth0 and get bandwidth value in python script, like this:
<code>$python foo.py eth0
UP: 7 KB/sec
DOWN: 31 KB/sec
</code>
where output script can change, use Kb/s
?
Comment: You should parse `/proc/net/dev` instead of the output of `ifconfig`.
Comment: Please refer http://stackoverflow.com/questions/24196932/how-can-i-get-the-ip-address-of-eth0-in-python. I hope so it will help you.
Answer: You can alternatively parse the /proc/net/dev file. See this code on link
It shows the same process.


why "repeat" function is cancelable in kotlin

Question: fun main(args: Array<String>) = runBlocking<Unit> {
val job = launch {
    repeat(1000) { i ->
        println("I'm sleeping $i ...")
        delay(500L)
    }
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancel() // cancels the job
job.join() // waits for job's completion
println("main: Now I can quit.")

}
this code not check isActive or use suspend function but can canceled
Answer: Here's the analogy with Java threads:
1) Checking the interrupted flag explicitly:
while (!Thread.interrupted()) {
    // loop code
}

2) Calling interruptible operations:
while (true) {
    Thread.sleep(1);
    // loop code
}

In both cases the thread will respond to a raised interrupt flag.
In coroutines, delay() is the counterpart of Thread.sleep() and the isActive flag is the counterpart of the Thread.interrupted flag.
Therefore, when you write
delay(1)

the coroutine will be scheduled off the thread and, when its time to resume comes, inside the continuation.resume() call it will first check the isActive flag. If it's raised, it will throw a CancellationException instead.
Answer: Because delay() is a suspend function.
Thread.sleep() is not a suspend function.
If you replace delay(500L) with Thread.sleep(500), then it will not be cancellable on time.


Sequence of matrices and convergence

Question: There is question in Matrix analysis by Horn (p. 300) that:
Let $f(x) = \sum_{k=0}^{\infty} a_{k} x^{k}$ with radius of convergence $R>0$. Then, $f(A)$ converges for all $A \in M_{n}$ such that $\rho(A)<R$, where $\rho(A)$ is the spectral radius of $A$.
I would like to prove it. Would you give me a hint?
Comment: Use Jordan form of $A$
Comment: This follows easily from spectral radius formula: $\rho (A)=\lim (||A^{n}||)^{1/n}$
Comment: Have you heard of Dunford-Schwartz functional calculus? It seems to solve the problem all too easily. And for all rigorous proofs matrix, there's always the Jordan normal form.
Answer: There exists $R_1 \in (0,R)$ such that $\rho (A) <R_1$. By spectral radius formula $||A^{n}|| <R_1^{n}$ for $n$ sufficiently large. Hence $\sum ||a_n A^{n}||$ is dominated by the series $\sum a_n R_1^{n}$ which is convergent since $R_1$ is less than the radius of convergence.
Answer: A useful result is that for any $\epsilon>0$ there is a submultiplicative matrix norm $\|\cdot\|_*$ such that $\|A\|_* < \rho(A)+\epsilon$.
All norms are equivalent on finite dimensional normed spaces, so it is sufficient to prove convergence with $\|\cdot\|_*$.
Let $\epsilon>0$ be such that $\rho(A)+\epsilon < R$, and $\|\cdot\|_*$  the
corresponding norm.
Then $\sum_k |a_k| \|A\|_*^k \le \sum_k |a_k| (\rho(A)+\epsilon)^k < \infty$.
In particular, the series $\sum_k a_k A^k$ is Cauchy and hence converges.
Aside:
To prove the result stated above, suppose $J= V^{-1} AV$ is the Jordan form of $A$ and let $R = \operatorname{diag} (r_1,...,r_n)$. Then
$[RJR^{-1}]_{ij} = {r_i \over r_j} [J]_{ij}$. Note that the diagonal elements of $RJR^{-1}$ are the same as those of $J$ and the off diagonal elements are of the form ${r_{j-1} \over r_j}$, for $j=2,...,n$.
In particular, we can choose $r_n=1$ and the subsequent $r_k$ so that the
numbers ${r_{n-1} \over r_n}, ..., {r_1 \over r_2}$are arbitrarily close to zero.
Note that if $\Lambda$ is the diagonal part of $J$, then $\|\Lambda\|_2 = \rho(A)$. By noting that the norm is a continuous function, then for any $\epsilon>0$ we can choose the $r_k$ such that $\| R J R^{-1}\|_2 < \rho(A)+\epsilon$
In particular, for any $\epsilon>0$ we can choose $R$ such that
$\|A\|_* = \| R V^{-1} A V R^{-1}\|_2 < \rho(A)+\epsilon$.
Now check that $\|B\|_* = \| R V^{-1} B V R^{-1}\|_2$ is indeed a submultiplicative norm.

Sequence of matrices and convergence


How to pass arguments to class methods and return values to the main method?

Question: I found a random assignment online and am using it as practice to try and improve as a coder, but I am having a lot of difficulty with this one area of the assignment. It wants me to "do the calculations and conversions inside separate methods. Pass the needed information into the method from the main method. After calculation is done, return the result into the main method for printing." I have been working on this for a long time now, and if I don't complete this it's really going to bug me, so any help is greatly appreciated. I apologize if this is a stupid question, I am very new to coding.
Here is my code:
import java.util.Scanner; // Allows for use of scanner in class

public class MeasurementConversion // Start of class
{
    public static void main(String[]args) // Start of main
    {
        Scanner readConsole = new Scanner(System.in); // This is the scanner
        String convert;
        double poundAmount; // These are the doubles that store the measurements
        double kilogAmount;
        double ounceAmount;
        double gramAmount;
        double feetAmount;
        double meterAmount;
        double mileAmount;
        double kilomAmount;

        System.out.println("Hello, I am a conversion calculator. I can convert pounds to kilograms, ounces to grams,"); // This is where the scanner begins prompting the user for input
        System.out.println("feet to meters, miles to kilometers, and vice versa.");
        System.out.println("What would you like to convert?");
        convert = readConsole.nextLine();
        if (convert.equalsIgnoreCase("pounds to kilograms")) // This converts from pounds to kilograms
        {
            System.out.println("Ok, what is the amount of pounds you know?");
            poundAmount = readConsole.nextDouble();
            kilogAmount = poundAmount * .4536;
            System.out.println("That is " + kilogAmount + " kilograms.");
        } // End of if statement
        if (convert.equalsIgnoreCase("kilograms to pounds")) // This converts from kilograms to pounds
        {
            System.out.println("Ok, what is the amount of kilograms you know?");
            kilogAmount = readConsole.nextDouble();
            poundAmount = kilogAmount * 2.20462;
            System.out.println("That is " + poundAmount + " pounds.");
        } // End of if statement
        if (convert.equalsIgnoreCase("ounces to grams")) // This converts from ounces to grams
        {
            System.out.println("Ok, what is the amount of ounces you know?");
            ounceAmount = readConsole.nextDouble();
            gramAmount = ounceAmount * 28.5;
            System.out.println("That is " + gramAmount + " grams.");
        } // End of if statement
        if (convert.equalsIgnoreCase("grams to ounces")) // This converts from grams to ounces
        {
            System.out.println("Ok, what is the amount of grams you know?");
            gramAmount = readConsole.nextDouble();
            ounceAmount = gramAmount * .035274;
            System.out.println("That is " + ounceAmount + " ounces.");
        } // End of if statement
        if (convert.equalsIgnoreCase("feet to meters")) // This converts from feet to meters
        {
            System.out.println("Ok, what is the amount of feet you know?");
            feetAmount = readConsole.nextDouble();
            meterAmount = feetAmount * .3048;
            System.out.println("That is " + meterAmount + " meters.");
        } // End of if statement
        if (convert.equalsIgnoreCase("meters to feet")) // This converts from meters to feet
        {
            System.out.println("Ok, what is the amount of meters you know?");
            meterAmount = readConsole.nextDouble();
            feetAmount = meterAmount * 3.28084;
            System.out.println("That is " + feetAmount + " feet.");
        } // End of if statement
        if (convert.equalsIgnoreCase("miles to kilometers")) // This converts from miles to kilometers
        {
            System.out.println("Ok, what is the amount of miles you know?");
            mileAmount = readConsole.nextDouble();
            kilomAmount = mileAmount * 1.61;
            System.out.println("That is " + kilomAmount + " kilometers.");
        } // End of if statement
        if (convert.equalsIgnoreCase("kilometers to miles")) // This converts from kilometers to miles
        {
            System.out.println("Ok, what is the amount of kilometers you know?");
            kilomAmount = readConsole.nextDouble();
            mileAmount = kilomAmount * .621371;
            System.out.println("That is " + mileAmount + " miles.");
        } // End of if statement
    } // End of main
} // End of class

Comment: If your assignment is to create other methods, then you should do that. You only have a single method already, main.
Comment: https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Comment: While you're at it you might want to consider how much of that code is repeated with little differences and how you might be able to refactor it.
Comment: You oass arguemntsa s parameters. You return values as return values. Unclear what you're asking, or else meaningless title.
Answer: As an example, replace the following code in your main method:
if (convert.equalsIgnoreCase("pounds to kilograms")) // This converts from pounds to kilograms
    {
        System.out.println("Ok, what is the amount of pounds you know?");
        poundAmount = readConsole.nextDouble();
        kilogAmount = poundAmount * .4536;
        System.out.println("That is " + kilogAmount + " kilograms.");
    } // End of if statement

with:
if (convert.equalsIgnoreCase("pounds to kilograms")) // This converts from pounds to kilograms
    {
        System.out.println("Ok, what is the amount of pounds you know?");
        poundAmount = readConsole.nextDouble();
        kilogAmount = convertPoundToKilogram(poundAmount); // call method to do the calculation
        System.out.println("That is " + kilogAmount + " kilograms.");
    } // End of if statement

and create a new method in your class like this:
private static double convertPoundToKilogram(double poundAmount) {
    return poundAmount * .4536;
}

You can then add more methods, or even do more work in these methods if you want (like taking the required input from the user etc).
Comment: The program still works after I replaced all of the methods and added the new class so I assume that it now works like it should. Your help is very much appreciated. Thanks


$d(f,g)= \sup _{x \in [a,b]} |f'(x)-g'(x)|$ show it is a metric

Question: Let $ C^1([a,b])$ be the set of real valued continous functions define on $[a,b]$, differentiable with continous derivatives on $[a,b]$
define the function
  $$ \forall f,g \in  C^1([a,b]) , d(f,g)= \sup _{x \in [a,b]} |f'(x)-g'(x)|$$
where $f'$ denotes the derivative on $f$. Is $d$ a metric on  $C^1([a,b])$

The properties of metrics are $\forall f,g,h \in C^1([a,b])$
$$ \begin{aligned}
&(i) && d(f,g) \geq 0
\\&(ii) && d(f,g) =0 \iff f=g
\\&(iii) && d(f,g)=d(g,f)
\\&(iv) && d(f,g) \leq d(f,h)+d(h,g)
\end{aligned}$$

**is there something said that is wrong? **

Attempt to show that it is a metric
Showing $d(f,g) \geq 0$.
$f'(x)-g'(x)$ where $x \in [a,b]$ is a real number so the absolute value of it is greater or equal to $0$.
[showing ii]
$(d(f,g)=0 \Rightarrow f=g)$
assuming that $$d(f,g)=\sup |f'(x)-g'(x)|=0$$
so $\forall x \in [a,b]$
       $$ f'(x)-g'(x)=0  \equiv f'(x)=g'(x)$$
integrating we have that
$$\int f'(x)dx =\int g'(x)dx \Rightarrow f(x)=g(x)$$
($\Leftarrow ] $ $f=g \Rightarrow d(f,g)=0$ )
So $\forall x\in [a,b]$ $f(x)=g(x)$ so differentiating we have that $$f'(x)=g'(x) \Rightarrow f'(x)-g'(x)=0$$ so $\forall x \in [a,b]$
$$\sup_{x\in [a,b]}|f'(x)-g'(x)|=0 $$
Showing $d(f,g)=d(g,f)$
$$\begin{aligned}
d(f,g)&=\sup _{x \in[a,b]} |f'(x)-g'(x)|
  \\ & =   \sup _{x \in[a,b]} |g'(x)-f'(x)|
\\ &=d(g,f)
\end{aligned} $$
Showing Triangular inequality ($d(f,g)\leq d(f,h)+d(h,f)$)
$$\begin{aligned}
d(f,g)&=\sup_{x\in[a,b]} |f'(x)-g'(x)|
\\&=\sup_{x\in[a,b]}|f'(x)-h'(x)+h'(x)-g'(x)|
\end{aligned} $$
call sup to be $x_1$ so
$$ |f'(x_1)-h'(x_1)+h'(x_1)-g'(x_1)| \leq  |f'(x_1)-h'(x_1)|+|h'(x_1)-g'(x_1)|$$
Now $x_1$ may not be the sup of each absolute diff of 2 functions  so
$$  |f'(x_1)-h'(x_1)|+|h'(x_1)-g'(x_1)|
  \leq \sup_{x \in [a,b]} |f'(x_1)-h'(x_1)|+  \sup_{x \in [a,b]}|h'(x_1)-g'(x_1)|=d(f,h)+ d(h,g)$$
$\therefore d(f,g) \geq d(f,h)+d(h,g)$
We have that the 4 prop of metrics do hold $\therefore$ $d$ is a metric
Comment: It's not a metric. Let $f(x) = 1, g(x) = 2$.
Comment: $d(f,g)=0\implies f-g=\text{constant}$
Comment: If $f$ and &g$ differ by a constant, $d(f,g) =0$ but $f \neq g$
Comment: Some "cheaty" to prove that it is a metric: Let $D:C^1[a,b]\to C^0[a,b]$ be given by $D(f)=f'$. Then $d(f,g)=d_\infty(Df,Dg)$, where $d_\infty(f,g)=\sup_{x\in[a,b]}|f(x)-g(x)|$ is the usual uniform metric. It is a general fact that a metric defined such as $d$ (in terms of some function and a metric on the range) is a pseudometric, and a metric iff the function $D$ is injective, which is not the case.
Answer: False.  Try the constant functions $f(x) = 0, g(x) = 1$.


Slickgrid Copy Paste issues

Question: We are thinking about using SlickGrid in our application. I have run into a few issues with the copy paste functionality.  We are using the ExternalCopyManager plugin.

Copy and paste on an editable grid doesn't paste multiple cells. It looks like it only pastes the current selected cell.
When you have leaveSpaceForNewRows =true and enableAddRow and you paste multiple rows at the end of the grid it only creates 1 row.

Any help or suggestions?
Answer: SlickGrid doesn't have copy'n'paste.  It has a plugin Slick.CellCopyManager, but it doesn't copy the cells for you.  It fires the copy/paste events and tells you which ranges need to be copied from where and where to.  You still have to implement the actual logic for copying.  It's done in that way because the rules for the actual copying are very application-specific.
Comment: We are using the ExternalCopyManager plugin I was wondering if anyone using the plugin have suggestions using it in the way we are implementing it.
Comment: You should contact the author of that plugin.
Answer: Check this example out: you can copy/paste multiple cells.

First, double click a cell to edit its contents.  Do that with multiple cells.
Then, right click a cell and WITHOUT RELEASING (mouse left still down), drag the mouse to cover a range of cells (their backgrounds will turn yellowish).  Release the left click.
CTRL+C will copy this range.  These cells are now blueish.
Select the range that you will paste to and CTRL+V.  If your paste range is smaller than your copy range, only the selected paste range will receive new cell calues.

Slickgrid Copy Paste issues


DocFx does not generate documentation

Question: I'm trying to use DocFx to generate API documentation. I was under the impression that if I added docfx.console as a nuget package to my .NET project and built it, the documentation would be generated automatically. But that does not seem to be happening. It does generate some html files inside the _sites folder, but it doesn't convert my XML comments to a friendly doc format. What am I doing wrong? My project is ASP.NET MVC with C# (.NET 4.6.1).
Comment: docfx requires you to have Visual Studio (or at least the Build Tools) installed on that machine. Otherwise, it cannot generate any files. Such dependencies are not quite well documented, in case you missed. You'd better run its command line tool and learn its log files. Only when you are familiar with it, you can switch to the NuGet package.
Comment: @LexLi I do have Visual Studio installed. I have tried it on different computers with VS 2015 and VS 2017, but I got the same result in either case.
Comment: Check existing issues, or report yours as a new one https://github.com/dotnet/docfx/issues
Answer: I have the same problem. I solved by using command docfx build [your project folder] then docfx serve [your project folder again] on Developer Command.

DocFx does not generate documentation


How can I use bootstrap in css file?

Question: I want to use bootsrap in my asp.net 4 project.
I installed bootstrap in visual studio using nuget:

I have global css file:
    /*Global styles*/
body, form
{
    direction: rtl;
    font-family: Arial;
    font-size: 16px;
    color: #333333;
    margin: 0px;
    padding: 0px;
    background-position: bottom;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-color: #f8f8f8;
}
input[Type=text], input[Type=password], input[Type=button], input[Type=submit], input[Type=reset], input[Type=file], select, textarea
{
    margin: .2em .05em;
    border: 1px solid #333333;
    color: #333333;
}
input[Type=text], input[Type=password], input[Type=file], select, textarea
{
    max-width: 225px;
    width: 98%;
}
input[Type=text]:disabled, input[Type=password]:disabled, input[Type=file]:disabled, select:disabled, textarea:disabled
{
    background-color: #E6F6FA;
}
input[Type=button], input[Type=submit], input[Type=reset]
{
    background-color: #EEEEEE;
    cursor: pointer;
}
input[Type=button]:hover, input[Type=submit]:hover, input[Type=reset]:hover
{
    background-color: #DCDCDC;
}

I need to define style of the buttons and other elements using bootstrap, I want to it in global css file.
So my question how can I use bootstrap in css file?
Answer: @import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");
Comment: where do I write it in ccs file?and how I add it to button style defenition?
Answer: You can import the CSS file like stara_wiedzma said.
However you can't import bootstrap's .btn class for input[Type=button], input[Type=submit], input[Type=reset] globally with CSS
I think you are looking for something like LESS of SASS.
With LESS and SASS you can do things like:
input[type=button]{
    .btn;
    .btn-success;

    // your own styles...
}

Google: "bootstrap less workflow" for some setup and examples.
Comment: Does  LESS or SASS gives me option to import bootstrap style to css page?
Comment: Yes! You can inherrit bootstrap's classes on your own elements. The example I gave will make all buttons look like bootstrap's success button.
Comment: Can please you give some example?Or write reference to example in google??
Comment: I think this: https://scotch.io/tutorials/getting-started-with-less will explain a lot

How can I use bootstrap in css file?


Can't make it work Ajax with MVC 3

Question: This is my Controller method
    [HttpPost]
    public ActionResult RemoveValue()
    {

        return View();

    }

And this is how i am trying to access to method
@Ajax.ActionLink("Asenkron process", "RemoveValue")

But if i remove HttpPost attribute then it works.
I have tested this on MVC 3 RC 2
Comment: Anyone has no idea ? works on you ?
Comment: I am also having this problem when I try to do the MvcMusicStore tutorial.
Answer: The [HttpPost] attribute means that that method can only be reached via a POST request. If you were to look at the request in Firebug or something similar, you would see the request being made, and get a 500 error in response.
If you want the link to perform a POST, change it to:
@Ajax.ActionLink("Asenkron process", "RemoveValue", new AjaxOptions {HttpMethod="POST"})

EDIT
Upon further reading of the docs, Ajax.ActionLink does nothing with the result it gets unless you specify something for it to do. It also does a POST by default it seems, so the AjaxOptions isn't needed. If you want to display the contents of whatever is in the RemoveValue view, you need to do something like the following:
@Ajax.ActionLink("Text","RemoveValue", new AjaxOptions {UpdateTargetId="resultDiv" })

The contents of resultDiv will be whatever is returned from the Action.
If you are looking for just some sort of confirmation:

@Ajax.ActionLink("Text","RemoveValue", new AjaxOptions {OnSuccess="onSuccess", OnFailure="onFailure" })

This is, of course, assuming you want an asynchronous request. If you want a normal synchronous POST, where the browser goes to a new page, do something like this:
using(Html.BeginForm("ActionName","ControllerName",FormMethod.Post))
{
  <input type="submit" value="Delete" />
}

If you do this, the Action you POST to should end with return RedirectToAction("AnotherAction");. The browser will then make a GET request to AnotherAction. This prevents duplicate actions when the user clicks the back button and the "Data must be resubmitted to the page" popup in browsers.
Hopefully this is slightly more helpful.
Comment: I have also tried this but didn't work. Does it works on you? have you tested ?
Comment: Looking further at the docs, I think a more appropriate question is what are you expecting to happen? I'm going to update my answer with more details.
Comment: I am expecting that method will be invoked but it doesn't happen.
Comment: Still no luck. Ajax.ActionLink use Get method even if i change it's HttpMethod property. I will gone mad. But i am able to make ajax with pure javascript codes.
Answer: Maybe a Ajax.BeginForm around it?
@using (Ajax.BeginForm(new AjaxOptions{ UpdateTargetId="resultDiv", HttpMethod="Get"})) {
}

Can't make it work Ajax with MVC 3


Solution of Differential equation

Question: Question:
Find solution of differential equation
$$ 3e^{4x} \frac{dy}{dx} = -16\frac{x}{y^2} $$
which satisfies the initial condition y(0)=1
Solution:
I know that I have to bring it in the general form of :
$$ \frac{dy}{dx} + P(x) y = Q(x)$$
However in the equation there is no P(x)y component so how do i do it ?
Answer: You can solve this ODE by separation of variables:
$\frac{dy}{dx}=-16\frac{x}{y^{2}}\frac{1}{3}e^{-4x}$
$y^{2}dy=-\frac{16}{3}xe^{-4x}dx$
$\int y^{2}dy=-\frac{16}{3}\int xe^{-4x}dx$
Now you can integrate both sides using standard techniques (the integral on the right hand side using partial integration).We get
$\frac{y^{3}}{3}=\frac{4}{3}xe^{-4x}+\frac{1}{3}e^{-4x}+C$
$y(x)=\left(4xe^{-4x}+e^{-4x}+\tilde{C}\right)^{1/3}$, with $\tilde{C}:=3C$
Using your initial data we find that $\tilde{C}=0$.
Answer: $3e^{4x} \frac{dy}{dx} = -16\frac{x}{y^2}$ write it as
$\int y^2 dy = -16/3\int \frac{x}{e^{4x} }dx$ now apply by parts in R.H.S
Answer: An interesting aspect:
The differential equation has the form
\begin{align}
3 \, e^{a x} \, y' = - 16 \cdot \frac{x}{y^{2}}
\end{align}
for which
\begin{align}
3 \, y^{2} \, y' = - 16 \, x \, e^{-a x}
\end{align}
where $a$ is a constant, here $a = 4$. This last equation can be seen to have the form
\begin{align}
\frac{d (y^{3})}{dx} &= \frac{d}{da} \left(16 \, e^{-a x} \right) = \frac{d}{dx} \left[ \frac{d}{da} \left( - \frac{16}{a} \, e^{-ax} \right) \right].
\end{align}
Integration with respect to $x$ provides:
\begin{align}
y^{3} = \frac{d}{da} \left( - \frac{16}{a} \, e^{-ax} \right) + c_{1}
\end{align}
or
\begin{align}
y(x) &= \left.\left[ \frac{d}{da} \left( - \frac{16}{a} \, e^{-ax} \right) + c_{1} \right]^{1/3}\right|_{a=4} \\
&= \left.\left[ \frac{16}{a} \, \left(1 + \frac{1}{a}\right) \, e^{-ax} + c_{1} \right]^{1/3} \right|_{a=4} \\
&= \left[ (4 x + 1) \, e^{-4x} + c_{1} \right]^{1/3}.
\end{align}

Solution of Differential equation


Reinforcement Learning, how can I sample action from Gaussian distribution with action dimension space larger than one?

Question: In the code of Actor-Critic with Gaussian,
class PolicyEstimator():
    """
    Policy Function approximator.
    """

    def __init__(self, learning_rate=0.01, scope="policy_estimator"):
        with tf.variable_scope(scope):
            self.state = tf.placeholder(tf.float32, [400], "state")
            self.target = tf.placeholder(dtype=tf.float32, name="target")

            # This is just linear classifier
            self.mu = tf.contrib.layers.fully_connected(
                inputs=tf.expand_dims(self.state, 0),
                num_outputs=1,
                activation_fn=None,
                weights_initializer=tf.zeros_initializer)
            self.mu = tf.squeeze(self.mu)

            self.sigma = tf.contrib.layers.fully_connected(
                inputs=tf.expand_dims(self.state, 0),
                num_outputs=1,
                activation_fn=None,
                weights_initializer=tf.zeros_initializer)

            self.sigma = tf.squeeze(self.sigma)
            self.sigma = tf.nn.softplus(self.sigma) + 1e-5
            self.normal_dist = tf.contrib.distributions.Normal(self.mu, self.sigma)
            self.action = self.normal_dist._sample_n(1)

Initializing an instance of Normal distribution
self.normal_dist = tf.contrib.distributions.Normal(self.mu, self.sigma)

Sampling
self.action = self.normal_dist._sample_n(1)

the code samples only one action since the dimension of the env is 1. However, if the action space is 40 or more, how can I sample the action?
self.action = self.normal_dist._sample_n(40)

I think it means sampling 40 actions of which dimension space is 1 not sampling an action with 40 dimension value.
How can I sample one action of which dimension value is 40 or more?
Answer: To create an action vector with shape (40), you need the last layer of your network to output a vector with a shape of 40. So change:
self.mu = tf.contrib.layers.fully_connected(
                inputs=tf.expand_dims(self.state, 0),
                num_outputs=1,
                activation_fn=None,
                weights_initializer=tf.zeros_initializer)

To:
self.mu = tf.contrib.layers.fully_connected(
                inputs=tf.expand_dims(self.state, 0),
                num_outputs=40,
                activation_fn=None,
                weights_initializer=tf.zeros_initializer)

This means that self.mu (which is fed to tf.distributions.Normal) will be a vector with shape (40).
You can do the same for sigma, but in my experience, it is better to treat this as a trainable parameter rather than an output from a network, for example:
import numpy as np
import tensorflow as tf

state_dim = 3  # 3 dimentional state
action_dim = 40  # 40 dimentional action
action_bound = 2  # Actions are scaled between -2 & +2

# Define ops for actor/policy
state = tf.placeholder(tf.float32, [None, state_dim])

# Dense layer which takes an imput of shape 3, and output shape 40
mu = tf.layers.dense(state, action_dim, tf.nn.tanh, name='pi_mu')

# Use log sigma to prevent NaNs (initialised to 0)
log_sigma = tf.get_variable(name="log_sigma", shape=action_dim, initializer=tf.zeros_initializer())

# Create a 40D Gaussian distribution (sigma = exp(0) = 1)
dist = tf.distributions.Normal(loc=mu * action_bound, scale=tf.exp(log_sigma))

# This sample_op returns a single vector of shape 40 sampled from dist
sample_op = tf.squeeze(dist.sample(1), axis=0)

# Start session
sess = tf.Session()
sess.run(tf.global_variables_initializer())

# Sample a 40D action using an input state
sess.run(sample_op, feed_dict={state: np.array([[1, 0, -1]])})

Output:
array([[-0.12732446, -1.0969237 ,  0.19172549, -0.53541076, -1.7409694 ,
        -1.9716561 , -0.4621313 ,  1.1770394 , -0.89807725, -0.428378  ,
         0.43714064,  0.5723815 , -2.4273002 , -1.1083983 , -0.67126757,
         1.4471897 , -1.9418054 , -0.3857537 ,  0.3149717 , -0.5094094 ,
        -0.9856905 ,  1.1567912 ,  0.37608355, -1.1339413 ,  0.13634366,
        -0.22886413,  1.2220807 , -0.9807693 ,  1.5443543 , -0.01700211,
        -0.30074215,  0.77911556,  1.0790621 ,  1.4446486 ,  0.11510286,
         0.13127172,  0.9332013 , -0.22423705,  0.27746603,  0.03245509]],
      dtype=float32)

Comment: Sorry to reply to your answer so late. Could you please offer a working code so that I can try it and get an intuitive understanding of the process.
Comment: Thank you, some people say that if the action dimension is large than one, multivariate normal is preferred than unimodal normal.


Using Googlemaps in Yii2?

Question: How do I use Googlemaps in Yii2 ?
I am not able to follow the Usage placed in http://www.yiiframework.com/extension/yii2-google-maps-library
Installation has been done, but I am getting error
Class 'dosamigos\google\maps\LatLng' not found

Could anyone provide a tutorial/examples where Yii uses Google Maps ?
Answer: Normally the use directive for third party extensione start with vendor
could be you must add the vendor to the use  where you use these class.
try using
use vendor\dosamigos\google\maps\LatLng;
use vendor\dosamigos\google\maps\services\DirectionsWayPoint;
use vendor\dosamigos\google\maps\services\TravelMode;
use vendor\dosamigos\google\maps\overlays\PolylineOptions;
use vendor\dosamigos\google\maps\services\DirectionsRenderer;
use vendor\dosamigos\google\maps\services\DirectionsService;
use vendor\dosamigos\google\maps\overlays\InfoWindow;
use vendor\dosamigos\google\maps\overlays\Marker;
use vendor\dosamigos\google\maps\Map;
use vendor\dosamigos\google\maps\services\DirectionsRequest;
use vendor\dosamigos\google\maps\overlays\Polygon;
use vendor\dosamigos\google\maps\layers\BicyclingLayer;

Using Googlemaps in Yii2?


Find number of leaves of a tree (Proof)

Question: Problem:
Let $T$ be a tree that has $i\ge1$ branch nodes, all of which have the same degree[1] $d$. Show that the number of leaves $(l)$ of the tree can be calculated via the following formula:
$$l=(d-2)i+2$$
[1] The degree of a node is defined as the number of all edges connected to it $(d_{leaf}=1)$.

What I've tried:
I've tried to solve this problem using induction to the number of leaves (I'm open to a better way).
Initial Notes:

For a node to be a branch node: $d\ge2 \implies d_{min}=2$.
As a result, the minimum possible number of leaves $l_0=2$.
Also, let $s=d-d_{min}\ge0$.

So, the formula becomes:
$$
l=(d-d_{min})i+d_{min}
$$
Base Case:
Show that the formula holds for the minimum number of branch nodes $(i=1)$:
$$
l_1=(d-d_{min})\cdot 1+d_{min}=d
$$
The above holds, because the only branch node will be connected to all leaves. $l_1$ can also be written in the following form:
$$
\begin{align}
l_1
&=(d-d_{min})\cdot 1+d_{min}\\
&=l_0+(d-d_{min})\\
&=l_0+s
\end{align}
$$
Inductive Step:
Assume that the formula works for $(i=k)$:
$$
l_k=(d-d_{min})k+d_{min}
$$
Then prove that it works for $(i=k+1)$:
$$
\begin{align}
l_{k+1}
&=(d-d_{min})(k+1)+d_{min}\\
&=(d-d_{min})k+(d-d_{min})\cdot1+d_{min}\\
&=l_k+(d-d_{min})\\
&=l_k+s
\end{align}
$$
Therefore, the formula holds $\forall\ i\ge1$.

Question:
Is my approach correct? If not, what is the best approach to solving this problem?
Answer: There is a slick proof using the Euler characteristic formula: if a tree has finitely many nodes then the number of nodes minus the number of edges equals $1$.
You've used $i$ for the number of nodes of degree $d$; to improve visuals, I'll use a capital $I$. I'll also use $L$ for the number of leaves, so the total number of vertices of the tree is $V = I+L$. And let me use $E$ for the number of edges. The Euler characteristic equation becomes
$$V-E=1
$$
$$I+L-E=1
$$
which we can solve for
$$E = I+L-1
$$
Next we count in an another way. Each edge has two endpoints. Each leaf is counted exactly once in this manner, and each branch node is counted exactly $d$ times. Therefore
$$2E = L + d I
$$
Now we eliminate $E$:
$$2(I+L-1)=L+dI
$$
and simplify
$$L = (d-2)I+2
$$
Regarding the Euler characteristic formula, the simplest proof I know is an induction proof that is kind of like what you have written.
Answer: I'd say the simplest way is to recall that the sum of degrees of all vertices is twice the number of edges, which is $n-1=i+l-1$ for the tree in question. Thus,$$2(i+l-1)=l+di\\\implies l=2+(d-2)i$$

Find number of leaves of a tree (Proof)


Which one is a resource efficient approach : CSS3 Stylesheet or Canvas API for a HTML5 app to be ported as Blackberry Webworks

Question: I'm developing a Math-based game/app using HTML5 technologies (HTML5 + CSS3 + javascript) for the upcoming Blackberry 10 Devices, to be ported using Blackberry WebWorks.
The game requires generation of lots of random numbers. I'm currently generating them in "p" tag and styling them. But some guy suggested me not to use Stylesheet so much and rather use Canvas API.
Is there any effective/performance-improving reason to listen to the suggestion or it is just any suggestion ?
Answer: I look it at this way:
HTML tags have pre-defined properties and behaviour such as padding, floating, relative positions, etc. Making use of these tags ensures that the developer does not have to write tons of code to mimic this trivial behaviour. Think of building a list: using
 and
 will take care of the positioning for you. In canvas you need to create this from scratch or look for a library. HTML/CSS IMO is perfect for Web Apps. In terms of performance, make sure your animations are done in the GPU (using 3d transforms) and the performance is great. It is easy to respond to different screen sizes when using HTML/CSS too.
Games tend to use absolute positioned elements that are manipulated directly (example, move player from 100px to 150px) and are therefore easier to work with in Canvas. Performance-wise, canvas2d operations are hardware accelerated, so it should be as smooth as using HTML/CSS.
Comment: I got a similar reply in my local area.
What does "IMO" mean in "HTML/CSS IMO" ?
Thanks for detailing :)


Valor oculto da variável

Question: Quando coloco para mostrar os números que foram trocados o programa apenas não mostra nada, não entendi o porquê disso.

Ler dois números, armazenando-os nas variáveis num1 e num2. Verificar
  se o valor de num1 é maior que o valor de num2 e, em caso positivo,
  trocar os conteúdos das variáveis

<code>#include <stdio.h>

int main(){
/*Ler dois números, armazenando-os nas variáveis num1 e num2. Verificar se o valor de
num1 é maior que o valor de num2 e, em caso positivo, trocar os conteúdos das variáveis*/

int num1, num2, x;
printf("Digite o valor do primeiro numero\n");
scanf("%d", &num1);
printf("Digite o valor do segundo numero\n");
scanf("%d", &num2);
x=num1;
if (num1<num2){
    num1=num2;
    num2=x;
    printf("O valor do primeiro numero é:\n", num2);
    printf("O valor do segundo numero é:\n", x);
}

return 0;

}
</code>
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver pontuação suficiente).
Answer: Se eu entendi bem tem que imprimir os dois valores originais de forma trocada, então não faz sentido não imprimir um deles e imprimir um valor temporário que é igual ao outro. O fato de não usar um nome de variável adequado ajuda cometer o erro. Além disto não está mandando imprimir o número, está só mandando um texto, para imprimir o número tem que dizer onde ele será colocado e usa-se neste caso o placeholder <code>%d</code> para um número inteiro. Tem mais erros de interpretação, assim fica melhor:
<code>#include <stdio.h>

int main() {
    int num1, num2;
    printf("Digite o valor do primeiro numero\n");
    scanf("%d", &num1);
    printf("Digite o valor do segundo numero\n");
    scanf("%d", &num2);
    if (num1 > num2) {
        int temp = num1;
        num1 = num2;
        num2 = temp;
    }
    printf("O valor do primeiro numero é: %d\n", num1);
    printf("O valor do segundo numero é: %d\n", num2);
}
</code>
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Answer: Se num1 for maior que num2 vai imprimir eles trocados, caso contrário não acontecerá nada.
<code>#include <stdio.h>

int main(){
/*Ler dois números, armazenando-os nas variáveis num1 e num2. Verificar se o valor de
num1 é maior que o valor de num2 e, em caso positivo, trocar os conteúdos das variáveis*/

int num1, num2, x;
printf("Digite o valor do primeiro numero\n");
scanf("%d", &num1);
printf("Digite o valor do segundo numero\n");
scanf("%d", &num2);
x=num1;
if (num1>num2){
    num1=num2;
    num2=x;
    printf("O valor do primeiro numero é: %d\n", num1);
    printf("O valor do segundo numero é: %d\n", num2);
}

return 0;

}
</code>

Valor oculto da variável


Derivative with integral inequality proof

Question: let $f(x)$ be second derivative on $[0,1]$,and $$f''(x)\ge 0,f'(x)<0,\forall x\in[0,1], f(0)=0,f(1)=-1$$
show that
$$\int_{0}^{1}\sqrt{\dfrac{f'^2(x)+1}{|f(x)|}}dx\le 2\sqrt{2}$$
Comment: Well, at least I don't think your hint works. Obviously, when $f=-x$, the functional gets its maximum, but $\int_0 ^1 1/|x| dx = \infty$.  The point is to show, why the minimizer is a linear function.
Comment: Sorry, I should say, the maximizer.
Answer: This question is not well-posed.
Let $f(x)=x^{10}-2x$,satisfying $$f''(x) \ge 0, \forall x \in [0,1],f(0)=0,f(1)=-1$$but$$\int_{0}^{1}\sqrt{\dfrac{f'^2(x)+1}{|f(x)|}}dx=\int_{0}^{1}\sqrt{\dfrac{(10x^9-2)^2+1}{|x^{10}-2|}}dx=3.28097>2\sqrt2$$
Actually the supremum of the functional is $\infty$.
Comment: Hello,you have somewrong, I think $f(x)=x^{10}-2x$,but then you have true,if $f(x)$ add monotone decreasing,maybe is true
Comment: Sorry, it's a typo. The calculation is actually done by taking $f(x)=x^{10}-2x$, so it works.


Hook for csv export view - flag exported items

Question: I am using Views data export to export view with exposed filter, is there any hook or another way to run an action over these filtered items?
My goal: set "flag" (boolean field) for these exported items so I will know, they have been exported.
Answer: Views Data Export isn't transactional and so if you're looking for something, you'd likely need to wrap up Views Data export with your own code that loops over the results and sets the flag then.
Comment: Could you please point me to the right section of module's code, where I can get these results?


Flash CS5, make the image scaling smoother

Question: I have a problem where the images look a little pixelated because they have been scaled down alot, just need a way to make everything appear smoother.
I need the game I'm making to look high quality and also work at different resolutions so when I made all the graphics I made them massive and same for the stage size in flash.
The stage size is 2000*1500 and it's being scaled down to 800*600 which is an exact ratio, I didn't expect to see pixelization when scaling the images DOWN, that's why I made them so large.
If there's no options for smoothing things out, then does anyone know the best option for swapping images at run-time? This way I can have pre-made images for all the most popular resolutions.
Answer: If you are using bitmaps, try smoothing and pixelsnapping:
<code>image.smoothing = true;
image.pixelSnapping = "never";
</code>
If you have library images (bitmaps), try changing "Allow Smoothing" and "Compression"

If you want to automate this you can use JSFL:
http://mrsteel.wordpress.com/2007/06/12/flash-jsfl-script-allow-smoothing-on-all-bitmaps-in-library/
Comment: Thanks, is there a way that I can do this for the whole stage. Because the images are all being used in buttons, and they are all loaded into the stage automatically by the IDE
Comment: I just found that I can set the smoothing from the IDE by going to the properties of an image. But I can't see anything to set pixel snapping.
Comment: Use this JSFL to apply smoothing on all bitmaps in the library. http://mrsteel.wordpress.com/2007/06/12/flash-jsfl-script-allow-smoothing-on-all-bitmaps-in-library/
Comment: Be careful with the loseless images though, you will get bigger files because they are not compressed.
Comment: Yeah nice One :). I used lossless on a few of the images but not most. Thanks for your help
Comment: another tip to help scaling issues is to make your image sizes the power of 2, i.e.: 8x8, 16x16, 32x32, 64x64, etc


How to stop a loop in rules?

Question: I'm using Conditional Rules module, there some conditions inside the loop I need to break out of. However, there's no action in rules for stopping/terminating the loop.
I tried a custom rules where I tried the following but it does not work:
<code>function my_module_break_rules_loop() {
  return FALSE;
}
function my_module_break_rules_loop() {
  return 0;
}
function my_module_break_rules_loop() {
  break;
}
</code>
The break works but display with this error message:

PHP Fatal error:  Cannot break/continue 1 level in

Any one know how to stop/terminate the loop?
Comment: Found any solutions for this?
Comment: take a look here , (possible duplicate) http://stackoverflow.com/questions/11988281/why-does-cannot-break-continue-1-level-comes-in-php
Comment: Could you perhaps change it to a while instead?
Answer: Install Conditional Rules so that you can add "conditions" between " rule actions". After that you can create a variable which iterates and use that to stop after the third elements.
Comment: can you include a sample rule (in export format) that demonstrates your answer?
Answer: You ought to filter the array before handling it over to the foreach. You could do this by implementing a rule component that takes two parameters:

The new (filtered) list.
The item you are considering.

Put this component within a foreach loop. That would likely be another component.
If the parameter meets your criteria, then append it to the list. If not, do nothing. The result is that you then have your filtered list.
Now you can do your foreach.
Another possibility is to put a rule component within your loop that only runs if some passed in function works. Basically, a while loop.

How to stop a loop in rules?


What happens if I use a classical guitar capo on an acoustic or electric guitar, or an acoustic and electric guitar capo on a classical guitar?

Question: I've noticed that the capos for electric/acoustic guitars and classical guitars are different. For example, classical guitar capos are flat, while electric/acoustic guitar capos are curved.
Is there any risk of damaging the instrument if I use a capo designed for the other type of guitar? Classical capos on electric/acoustic guitars, or electric/acoustic capos on classical guitars? If there's no risk, will it work correctly?
Answer: Using a curved capo on a flat fretboard or a flat capo on a curved fretboard may not damage the instrument, but it definitely will not work correctly as previous answers have detailed.
For others who may read this post seeking the answer to the same question who are like me (visual learners), I have provided some pictures below to illustrate the problem that will result from using the wrong capo.

A capo designed for use on a curved fretboard would conform to the fretboard and apply equal pressure against all frets as shown in the image above (exaggerated for effect).

A curved capo applied to a flat fretboard would apply pressure only to the frets closest to the edge of the fretboard and fail to adequately make contact with the center strings resulting in muting of these strings.  Diagram is exaggerated to better illustrate the concept.

Conversely (no pun intended), a flat capo on a curved fretboard would fail to properly contact the outer strings causing them to be muted.
The other problem you might encounter is - a typical classical guitar fretboard is significantly wider than an electric guitar or steel string acoustic guitar fretboard.  So the length of the capo for acoustic steel string guitar may be too short for a classical guitar.
Just as a classical guitar requires different strings than a steel string acoustic or electric guitar, it also requires a different capo.
Answer: I suppose you might scratch the back of the neck if using a clamp-on that is too small (i.e. meant for thin neck, used on thick neck). But that might happen anyway if you are not careful.
As you say, the curvature of capos is different for different applications. So when using a capo meant for a curved fretboard (e.g. electric) on a flat fretboard (e.g. classical/spanish) the capo won't clamp down properly on all strings and vice versa.
Answer: It's going to depend on what sort of capo. There are several different designs on the market, some of which rely purely on a spring to work. On a classical guitar with a beefier neck, they may be too tight. This isn't going to be a problem for the neck, but the tuning will suffer.
The bigger problem is the shape of the fingerboard. A capo meant for a cambered fingerboard
wil hold the outer strings on a classiccal tighter than the middle ones. Not so good. And a flat capo on a cambered 'board will do the opposite. Again, not so good.
As far as damage, no big deal, but looking at cost, isn't it worth just getting one for each?


Qual a diferença entre forms.Form e forms.ModelForm?

Question: Olá, prezados.
Com a ajuda de um tutorial, consegui criar um template com formulário e utilizar o forms.ModelForm para salvar no banco, porém, vi na documentação do Django que existe também o forms.Form. Qual a diferença?
framework Django1.9
Python3.4
Answer: A diferença é simples, o ModelForm serve para criar o formulário de um Model.
<code># Formulário que salva artigos no seu banco de dados.
class ArticleForm(ModelForm):
    class Meta:
        model = Artigo
        fields = ['pub_date', 'headline', 'content', 'reporter']
</code>
Já o Form é um formulário comum que não tem relação com seu banco de dados (model).
<code># formulário de contato para enviar via e-mail
class ContatoForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)
</code>
Answer: Exatamente como foi dito acima p ModelForm liga o seu Model ao Banco de Dados, já o Form realiza a conexão do Model com a Interface, as Views e Templates.


ProFTP DefaultRoot setting on different ports

Question: I have had ProFTP 1.3.2 and configured it to run for the same user on different ports with different root directories. Basically, the configuration was:
<VirtualHost ftp.domain.tld>
Port 1
AuthAliasOnly on
UserAlias xxx yyy
DefaultRoot /var/ftp/subdir
</VirtualHost>

<VirtualHost ftp.domain.tld>
Port 2
AuthAliasOnly on
UserAlias xxx yyy
DefaultRoot /var/ftp/subdir/uploads_weather/
</VirtualHost>

I did this because of a limitation of my weather station, which cannot save data into a subdirectory.
I have now installed a new server (Debian Stretch) and it has ProFTP 1.3.5b, but the above configuration does not seem to work any longer. When I log in on port 2, I see the same contents as I do on port 1.
I'd like to avoid having too many different user names. Is it still possible to have a per-port configuration?
Comment: Yes, it is still possible to have per-port `` configurations.  I'd recommend starting ProFTPD with debug logging enabled, _i.e._ `proftpd -nd10`, and see what it reports about possible IP address/port collisions.  After that, use the [debug logging](http://www.proftpd.org/docs/howto/Debugging.html) when your FTP clients connect, and see if that provides more clues.
Answer: Thanks to a comment of Castaglia I could figure out the issue.
I started ProFTPD at a higher log level (proftps -nd10) and I saw the error message

no matching vhost found for ::ffff:192.168.178.36#2, using DefaultServer 'Debian'

This reminded me of the fact that ProFTPd performs an nslookup operation for its virtual hosts. This could not work on my test environment, because it's just a VM, not a reachable machine in the Internet.
I fixed the test environment by adding the IP address and name to /etc/hosts:
192.168.178.36    ftp.domain.tld


Can a long /etc/hosts file slow DNS lookup?

Question: I'm facing a little question here. I have a long /etc/hosts file. (working in the web, so I'm hosting a lot of sites locally for developping). Let's says it is about 40, 50 lines long.
All redirecting to 127.0.0.1.
Now when checking Chrome's inspector, it seems my local web pages are loading slowly because of the DNS Lookup part. On a mygreatwebsite.local url also defined in the /etc/hosts file.
After a quick check, it would seem that reducing the hosts file to a couple of lines, drastically speeds up the DNS lookup part. So my question, is it possible to be confronted with differences of about 5 seconds for 50 lines, and insignificant times for a couple of lines? Or am I completely missing  something?
Comment: How long? I have used > 20000 line hosts files (no DNS involved though). Looks didn't take noticeably long...
Answer: Your tld .local could be the problem, zeroconf uses this. There is no real standard, but the suggested tld for an internal tld is .site or .internal. See http://en.wikipedia.org/wiki/Top-level_domain#Pseudo-domains for this.
Comment: Indeed, I have noticed great performance boost when using .site extension. After a little research, it seems to be the apple's Bonjour protocol that uses .local tld.
Comment: I joined StackExchange just to say THANK YOU for this excellent tip. My app was taking 10-15 seconds just to load assets and making my dev experience a nightmare. Using .site TLD has the pages loading all snappy again. Awesome.

Sidenote: Someone needs to mention this tidbit to all the bloggers/screencasters that use .local!
Answer:
Can a long /etc/hosts file slow DNS lookup?

The answer is yes, in a Windows (XP/Vista/7) machine.
It is a known problem that a long hosts file does not work well with "DNS Client" service.
http://winhelp2002.mvps.org/hosts.htm:

in most cases a large HOSTS file (over 135 kb) tends to slow down the machine.
[Solution: Set "DNS Client" service to manual or disabled]

http://vlaurie.com/computers2/Articles/hosts.htm:

Note that a hosts file that is much over 100 KB can actually slow up
  browsing unless the service "DNS Client" is set to manual start.

www.ericphelps.com/scripting/samples/Hosts/:

The most important thing to do before using large HOSTS files is to
  disable the Domain Name Service client ("DNS Client" or "DnsCache")
  service on your machine. It sounds bizarre, but the DNS client isn't
  needed to do DNS. Worse, if you have a large HOSTS file (which is
  what I suggest), the DNS client chokes your entire PC.

... and I have personally witnessed this on three different Windows machines: XP Pro, Vista, and 7 Starter.
Comment: Interesting point of view. I didn't knew that. But this questions concerns Mac Os environments. ;)
Comment: This is still relevant with Windows 11; adding a 20MB hosts file (to block every known malicious IP) makes a 24-core i7 /w nvme take 4+ hours to boot.  Worse, DNS cache is now system-controlled and cannot be stopped.  Do not attempt!
Comment: Issues with Windows continue.  With Windows 11 23H2, I tried a hosts with 1.6M entries.  It did not go well.
Answer: I would suggest using tcpdump to see whats actually going on. Without it you will be only guessing.
Basic syntax would be
tcpdump -n -i eth0 port 80 or port 53

(if you are interested in seeing ports 80 and 53, -n to prevent DNS lookups, supposing all comunication is taking place on eth0).
If this is too fast or too much information, redirect it to dumpfile with adding:
 -s 0 -w /tmp/dump

and use i.e. wireshark for looking into the dumpfile. You can see precise timing information in the file and much more...
Answer: When i used Spybot it would insert around 50,000 hosts file entries that redirect known malicious sites to 127.0.0.1. I never noticed any issues from having a long hosts file of this nature. Likely has more to do with your dev setup or the code itself. How many sites are you serving locally (50?) Does everyone one of them take this long to respond when 50 entries are present?
Comment: Yes, I'm sure it has nothing to do with the sites itself, they ran perfectly on my other mac (Snow Leopard). Now on Lion, only the server configuration and hosts file have changed. And yes, they all take the same time to load. And always on DNS Lookup part.
Answer: Based on my testing, a 34 MB hosts file with a few million entries slows down browsing in Windows a bit even when the "DNS Client" service is disabled. So, there is a maximum size beyond which you probably don't want to go.
Answer: For various reasons I have hosts files on some machines with hundreds of entries. This has no impact on DNS lookups simply because once the machine has found an entry in the hosts file it will not do a lookup for the same information. If everything else is configured correctly educing the size of the hosts file won't affect performance because even with a thousand entries that file can still be parsed faster than performing a DNS lookup. Check the order in which your machine is resolving addresses. The hosts file should be first.
Comment: Thanks, for the answer. How do I check the order?
Comment: @Zenklys, I'll have to leave it up to someone far more expert in Linux to answer that for you.
Answer: This is a slightly tangential answer to your question.
While not in the order of magnitude of seconds, I've observed a measurable difference comparing ping times against hosts when using their IP directly vs. a hostname entered in /etc/hosts mapping to the same IP:

Command
Mean [ms]
Min [ms]
Max [ms]
Relative

ping -c 1 XX.XX.XX.XX
13.6 ± 1.3
12.1
32.0
1.00

ping -c 1 <hostname>
14.2 ± 1.0
9.9
26.3
1.05 ± 0.13

ping -c 1 XX.XX.XX.XX
21.2 ± 0.4
18.0
21.9
1.00

ping -c 1 <hostname>
21.8 ± 0.5
20.1
22.9
1.03 ± 0.03

ping -c 1 XX.XX.XX.XX
11.4 ± 0.2
10.0
12.1
1.00

ping -c 1 <hostname>
12.0 ± 0.6
7.2
12.8
1.05 ± 0.06

ping -c 1 XX.XX.XX.XX
7.7 ± 0.3
6.8
9.3
1.00

ping -c 1 <hostname>
8.2 ± 0.4
7.0
9.2
1.06 ± 0.07

ping -c 1 XX.XX.XX.XX
30.6 ± 0.8
25.9
31.4
1.00

ping -c 1 <hostname>
31.2 ± 0.6
26.6
32.0
1.02 ± 0.03

ping -c 1 XX.XX.XX.XX
7.3 ± 0.3
6.1
9.5
1.00

ping -c 1 <hostname>
7.9 ± 0.4
6.8
9.9
1.09 ± 0.08

ping -c 1 XX.XX.XX.XX
8.0 ± 0.3
7.0
9.0
1.00

ping -c 1 <hostname>
8.4 ± 0.4
7.1
9.3
1.06 ± 0.06

ping -c 1 XX.XX.XX.XX
7.3 ± 0.4
6.0
9.1
1.00

ping -c 1 <hostname>
7.7 ± 0.5
6.6
8.6
1.06 ± 0.08

The difference for those hosts is between 2–9% depending on the original ping time.
This is on a mostly out of the box Debian system without any further special configuration related to DNS.
So yes, the lookup takes time, but should not take seconds.


Correlation bounds in terms of spectral radius

Question: My application requires that the following is true for random variables $X$, $Y$ in $\mathbb{R}^d$ with $E[X]=0, E[Y]=0$ and spectral radius $\rho$
$$\rho(E[XX]^{-1}E[XY]E[YY]^{-1}E[YX])<0.5$$
Can something be said about the strength of correlation between $X$ and $Y$ for this to be true?
Clarifying notation above:
$$\begin{array}{ccc}
E[XX]_{ij}&=&E[X_i X_j]\\
E[XY]_{ij}&=&E[X_i Y_j]\\
E[YX]_{ij}&=&E[Y_i X_j]\\
E[YY]_{ij}&=&E[Y_i Y_j]\\
\end{array}
$$
Comment: I cannot find any consistent way to make sense of this expression.  I understand that by "multivariate" you mean $X$ is some $n$ vector and $Y$ is some $m$ vector, but no matter whether I require $m=n$ or not and no matter whether I consider either or both to be column vectors or row vectors, the sequence of matrices implied by these four expectations cannot be multiplied except for special values of $m$ and $n.$  Please, then, clarify the meaning of your notation. Did you perhaps forget to indicate transposes in some places?
Comment: It's matrix multiplication (so they don't need to have same number of components). This is the same form as generalized version of "variance/covariance inequality", we know that that $<1$ is true by Schur's complement, tightening to 0.5 is more strict
Comment: clarified notation above
Comment: Thanks.  Evidently $X$ and $Y$ have the same number of components.  By "spectral radius" do you therefore mean the largest absolute eigenvalue of the matrix formed componentwise by these four products?  Or are you forming the product of four matrices?
Comment: BTW, offering a simple example might help.  It strikes me that when all four expectations exist and the variables are in one dimension, the spectral radius can be made as close to $1$ as one would like, with no additional assumptions on $X$ and $Y.$  Would that be correct, or am I missing something in your notation or assumptions?
Comment: Okay -- but consider what happens to your inequality when you add the same large constant to all components of $X$ and $Y.$ Notice that this won't change any of the correlation coefficients between components of $X$ and components of $Y.$  Indeed, in light of the fact there are $mn$ such pairs of components, could you be more specific about what you mean by "strength of correlation"?
Comment: You are right, I needed another assumption about variables being centered at 0
Comment: I don't know what is "the strength of correlation", that's basically the question. I have a requirement on spectral radius, which is opaque, and I'm looking to translate it into something easier to interpret. Maybe a bound on mutual information between two variables, or bound on largest correlation between any pair of components
Answer: This quantity seems to have an interpretation in terms of top canonical correlation, from 19.7 of Matrix Tricks for Linear Statistical Models: Our Personal Top Twenty 2011th edition,


how to run a vmdk image on another 64 bit machine which does not have vt support

Question: I have a CentOS 64 as Guest OS installation (basically the vmdk file) which was created on a machine which had Virtualization Support enabled in BIOS.
How ever I have another machine where I do not have virtualization support (even in BIOS) both these machines are 64 bit.
When ever I try to boot the vmd image which was created on machine with Virtualization support on the other machine which does not have virt support
after going through a series of messages as
You have configured this virtual  machine to use a 64 bit guest Operating System.How ever 64 bit operation is not possible. This host does not support VT.For more detailed information see http://vmware.com/info?id=152
Continue without 64 bit support.

Where I select yes and then some boot sequence starts but then I see a message
Your CPU does not support long  mode.Use a 32 bit distribution.

Is there a way to get past it.Given this another machine is a 64 bit machine.
Answer: Seems like it is possible to import VMDK images into VirtualBox, which can run without VT albeit a little slower.
Comment: Ok after your suggestion I downloaded virtualbox from here  http://www.virtualbox.org/wiki/Linux_Downloads for Ubuntu the version  I have is 4.0 and following page says some instructions as how vmdk images can run
http://www.ubuntugeek.com/howto-convert-vmware-image-to-virtualbox-image.html how ever I do not have any such option to import the vmx file or vmdk image in Virtualbox.So any other suggestion.
Comment: You don't really "import" it. You need to create a new VM in VirtualBox, and when you get to the part where you configure the virtual disk, you can choose an existing disk file. VMDK is one of the supported formats.
Answer: If you either have a very early 64bit chip or are (un)lucky enough (like me) to have a more recent non-VT Intel chip, there's one course of action remaining: EMULATION.
Bochs & Qemu will emulate the 64bit chip hardware, and there are a couple of decent GUI's for managing it. Finding a stable Qemu environment in your preferred distro might entail turning off some chipset features, or backing through some qemu versions or bios binaries.
Bochs is slower than Qemu. Qemu has the fast driver-mode KQemu, but consider it still like running a modern OS on a 200Mhz 1-core processor.


Question about rotate bitmap with Canvas.rotate

Question: As we know, we can rotate a bitmap through 2 ways.
The 1st way is:
Matrix mt = new Matrix();
mt.postRotate(degree);
Bitmap bitmap = CreateBitmap(src, 0, 0, w, h, mt, true);
canvs.drawBitmap(bitmap, 0, 0, paint);

In this way, we always need create new bitmap for every rotation, it is not good way for high performance game or app.
The 2nd way is:
canvas.save();
canvas.rotate(degree);
canvas.drawBitmap(bitmap, 0, 0, paint);
canvas.restore();

In this way, we avoid creating new bitmap frequently, but the rotation bitmap is distortion, the bitmap quality is worse than first way.
So, Is there 3rd way to rotate bitmap with high performance and good quality?
Your any comments are really appreciated!
Answer: Make sure that you providing Paint to canvas.drawBitmap(bitmap, 0, 0, paint).
And don't forget to use anti-alias and bitmap filtering:
paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);

Answer: If you really want high speed graphical applications (even 2D) you should use OpenGL on Android.
I believe Replica Island uses OpenGL and VBO's (where available) for rendering it's 2D scene. But I can't find a reference.
Comment: Thanks a lot! I've think about GL before but I don't want to use it since my app is not a game just a application.
Answer: this method should use the GPU to rotate the bitmap
Canvas.drawBitmap(android.graphics.Bitmap, android.graphics.Matrix, android.graphics.Paint)


JQuery - Add regular HTML along with escaped HTML

Question: I store some data in firebase (which can be retrieved in the client), and then, I add it to the HTML using JQuery. This is easy - I just prepend the data to the DOM element. However, the issue is, this raw code will be vulnerable to attacks, so I need to properly escape the data taken from the database before adding it to the HTML. I thought the following code would do the job:
function escapeHTML(text) {
  var map = {
    '&': '&',
    '<': '<',
    '>': '>',
    '"': '"',
    "'": '''
  };
  return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

$('#element').prepend('
Heading

' + escapeHTML(data) + '
');

When I test this code, by making the value of data something like , I thought that it would just add this text to the

 tags, without executing the JS, but it actually ran the code.
I understand that using $('#element').text() will escape the text for me, but I don't want everything to get escaped - I still want to add the

 and

 tags, I just need the variable "data" to be escaped. I saw a couple of StackOverflow posts on similar topics, but none of them seem to address this issue - post 1, post 2, post 3.
Comment: XSS is more than just
Comment: @epascarello what do you mean? Isn't that the only way to run inserted JS code?
Comment: no, there are more ways to do it.
Comment: @epascarello ook. Could you please give me an example or some links?
Comment: https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)
Comment: Why don't you just ban inline javascript for the page?
Comment: Here's the link to get started https://glebbahmutov.com/blog/disable-inline-javascript-for-security/
Comment: You should never trust data coming from the client, you should generate or validate it on the server.
Comment: @Barmar I also tried that - I actually tried escaping the HTML in the server itself, but weirdly enough, it had no effect - when I added the escaped HTML to the DOM, it still ran.
Answer: The reason the code in your question didn't work is because all the entities like & in the Javascript are parsed as the characters they represent when the JS in the HTML is parsed. It would work if you put the code in an external .js file, since that's not parsed as HTML. Or you could double-encode them:
  var map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };

But a better way is to create the
 and
 elements separately, and put the escaped text in the paragraph using a jQuery method.

const data = '<scr' + 'ipt>alert("foo");</scr' + 'ipt>';

$("#element").prepend("
Heading
", $("
", {text: data}));

If you want to fill in data attributes, you can do it similarly:
$("#element").prepend($("
", {
    data: {
        attr: data,
        another: someMoreData
    },
    text: "hello world"
}));

Comment: doubt this would meet the OPs needs if the content contains tags like bold and such. Maybe it is plain text and would be fine....
Comment: Why do you say that?
Comment: @Barmar I am actually adding the data from firebase like this: `$('#element').prepend('hello world')`. So, I don't know how to use your JQuery method... Also, this is already in an external JS file, and even if it wasn't, I don't think it would get parsed as HTML - it's in a string. But this is probably not the cause of my issue. However, your double escaping method worked like a charm! Thanks a lot! I can't upvote you yet though, as my rep is too low
Comment: I've added code that shows how to fill in the data attributes using the object method.


$\sum_{n=0}^\infty \frac{(1+\frac{1}{n})^n\cdot n!}{n^n}x^n$ prove if it converge or diverge for $x=-e$

Question: $$\sum_{n=0}^\infty \frac{(1+\frac{1}{n})^n\cdot n!}{n^n}x^n$$
Hello, this power series has a radius of $e$, but I cannot conclude if it diverges or converges in $x = -e$, I didn't succeed writing it formally. I would to receive hints or a valid solution, thanks.
Comment: Use Stirling's approximation.
Comment: Leibniz alternate series test.
Comment: i am not familiar with Stirling's approximation is there any other way?
Comment: Try proving that $\frac{n!e^n}{n^n}\to \infty$, or just that it doesn't converge to $0$. Stirling's approximation is just to help you with that.
Answer: You can prove that $a_n=\frac{(1+\frac{1}{n})^n\cdot n!}{n^n}e^n$ is a strict increasing sequence. So its limit is not zero and this implies your series is divergent!
$$\frac{a_{n+1}}{a_n}=\frac{(1+\frac{1}{n+1})^{n+1}\cdot (n+1)!}{{(n+1)}^{n+1}}e^{n+1}\frac{n^n}{e^n(1+\frac{1}{n})^n\cdot n!}
=\frac{(1+\frac{1}{n+1})^{n+1}}{(1+\frac{1}{n})^n}\frac{e}{(1+\frac{1}{n})^n}>1.$$
Here the sequence $\{(1+\frac{1}{n})^n\}$ is strict increasing tending to $e$.
Comment: i did exactly that for x=e but i don't see how the fact that the series diverge for x=e since $  \lim_{n\to \infty} != 0 $ is a sufficient claim for x=-e?
Comment: In both case $x=e$ and $x=-e$, you have the same conclusion  that $\frac{(1+\frac{1}{n})^n\cdot n!}{n^n}x^n$ does not tend to $0$, it is enough to prove the divergence.
Answer: Note that
$$\tag 1\ln \left (\frac{n!e^n}{n^n}\right ) = \sum_{k=1}^{n} \ln k  + n - n\ln n.$$
Now $\ln x$ is increasing, and this implies $\sum_{k=1}^{n} \ln k \ge \int_1^n \ln x\, dx.$ That integral equals $n\ln n -n +1.$ Thus the expression in $(1) $ is at least $1.$ Therefore $\dfrac{n!e^n}{n^n}$ is at least $e,$ which implies your series diverges.
Answer: Use Stirling's approximation as noted by @Robert Z
$$n! \sim \sqrt{2 \pi n} \frac{n^n}{e^n}$$
So
$$ \sum_{n=0}^\infty \frac{(1+\frac{1}{n})^n\cdot n!}{n^n}x^n \sim \sqrt{2 \pi}\sum_{n=0}^\infty f(n)$$
where $$f(n) = (1+\frac{1}{n})^n\cdot \sqrt{ n} \frac{1}{e^n}x^n$$
For $x = -e$, we have
$$f(n) = (-1)^n(1+\frac{1}{n})^n\cdot \sqrt{ n} $$
Consider
Let's work with $\vert f(n) \vert$
$$g(n) = \log \vert f(n) \vert = \underbrace{n \log(1+\frac{1}{n})}_{\rightarrow 1} + \underbrace{\frac{1}{2} \log n}_{\rightarrow \infty} \rightarrow +\infty$$
So $$\vert f(n) \vert \rightarrow + \infty \neq 0$$
Hence, the series diverges.
Comment: Approximating the sum is not at all formal in this case, as the sum is oscillating.
Comment: Use the absolute value of $x$. State that explicitly.
Comment: @RumpelstiltskinI thought the OP meant for $x = e$. Let me edit as Szeto suggests.
Comment: thanks @Szeto .
Comment: Still, the second line is bothering me. We want to approximate the argument, not the sum itself. Approximating sums like that seems like a bad habit that others might repeat
Comment: @Rumpelstiltskin all i'm saying is $\sum a_n$ diverges because $a_n \rightarrow k \neq 0$
Comment: @Rumpelstiltskin unless you prove what you say is concrete, i can't follow what you're saying
Comment: $\sum a_n \sim \sum b_n$ should mean that the one converges if and only if the other one does. In general that's not the case. It's the case with sums of positive coefficients. $a_n \sim b_n$ on the other hand means that $a_n/b_n\to 1$. While using the Stirling approximation is a fine approach, one should not compare those sums so recklessly!
Comment: Is there a mathematical definition of "recklessly"..

What you're saying doesn't make any sense to me. All the terms are positive here in $\vert f(n) \vert$.
Comment: Coefficients of those two sums aren't positive though i. e. $f(n)$ and $\frac{(1+\frac{1}{n})^n\cdot n!}{n^n} x^n$
Answer: $f_m(x)
=\sum_{n=1}^{m} \frac{(1+\frac{1}{n})^n\cdot n!}{n^n}x^n
$
(The usual)
$\begin{array}\\
(1+1/n)^n
&=\exp(n\ln(1+1/n))\\
&=\exp(n(1/n-1/(2n^2)+O(1/n^3)))\\
&=\exp(1-1/(2n)+O(1/n^2))\\
&=e\exp(-1/(2n)+O(1/n^2))\\
&=e(1-1/(2n)+O(1/n^2))\\
\end{array}
$
so,
since
$n! \approx cn^{n+1/2}e^{-n}
$,
$\begin{array}\\
f_m(x)
&=\sum_{n=1}^{m} \dfrac{(1+\frac{1}{n})^n\cdot n!}{n^n}x^n\\
&=\sum_{n=1}^{m} \dfrac{(e(1-1/(2n)+O(1/n^2)))\cdot n!}{n^n}x^n\\
&=\sum_{n=1}^{m} \dfrac{e n!}{n^n}x^n
-\sum_{n=1}^{m} \dfrac{e\cdot n!}{2n\cdot n^n}x^n
+O(\sum_{n=1}^{m} \dfrac{ n!}{n^2n^n}x^n)\\
&=\sum_{n=1}^{m} \dfrac{e cn^{n+1/2}e^{-n}}{n^n}x^n
-\sum_{n=1}^{m} \dfrac{e\cdot cn^{n+1/2}e^{-n}}{2n\cdot n^n}x^n
+O(\sum_{n=1}^{m} \dfrac{ cn^{n+1/2}e^{-n}}{n^2n^n}x^n)\\
&=ec\sum_{n=1}^{m} \sqrt{n}(x/e)^n
-(ec/2)\sum_{n=1}^{m} n^{-1/2}(x/e)^n
+O(\sum_{n=1}^{m} n^{-3/2}(x/e)^n)\\
\end{array}
$
At $x=e$,
the third series converges,
the second series diverges slowly
like $\sqrt{m}$,
and the first series diverges
like $m^{3/2}$.
So the overall sum diverges.
This holds even if
we take more terms
in the Stirling approximation,
since the first sum remains the same
and only the second sum is changed.
Answer: A necessary condition for a series $\sum _{k=0} ^{\infty} a_k $ to converge is that $\lim _{k \rightarrow \infty} a_k =0 $. You can prove this condition does not hold for $x=-e$, hence the power series diverges at $x=-e$. In fact, using Stirling approximation $a_k \approx e\sqrt{2\pi k} \left( \frac{x} {e} \right) ^k$ for $k \rightarrow \infty$.


MatFormFieldControl that implements ControlValueAccessor and Validator creates cyclic dependency

Question: I'm trying to create custom form control by implementing MatFormFieldControl, ControlValueAccessor and Validator interfaces.
However, when I provide NG_VALUE_ACCESSOR or NG_VALIDATORS..
@Component({
  selector: 'fe-phone-number-input',
  templateUrl: './phone-number-input.component.html',
  styleUrls: ['./phone-number-input.component.scss'],
  providers: [
    {
      provide: MatFormFieldControl,
      useExisting: forwardRef(() => PhoneNumberInputComponent)
    },
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => PhoneNumberInputComponent),
      multi: true,
    },
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(() => PhoneNumberInputComponent),
      multi: true
    }
  ]
})
export class PhoneNumberInputComponent implements MatFormFieldControl<string>,
  ControlValueAccessor, Validator, OnDestroy {
  ...
}

cyclic dependencies are created:

Uncaught Error: Template parse errors:
  Cannot instantiate cyclic dependency! NgControl

This works:
@Component({
  selector: 'fe-phone-number-input',
  templateUrl: './phone-number-input.component.html',
  styleUrls: ['./phone-number-input.component.scss'],
  providers: [
    {
      provide: MatFormFieldControl,
      useExisting: forwardRef(() => PhoneNumberInputComponent)
    }
  ]
})
export class PhoneNumberInputComponent implements MatFormFieldControl<string>,
  ControlValueAccessor, Validator, OnDestroy {
  ...
  constructor(@Optional() @Self() public ngControl: NgControl) {
    if (this.ngControl) {
      this.ngControl.valueAccessor = this;
    }
  }
}

But I still cannot figure out how to make validation work. Providing NG_VALIDATORS creates cyclical dependency. Without providing it, validate method is simply not called.
I'm using @angular/material 5.0.4.
Answer: To get rid of cyclical dependency, I removed the Validator interface from  the component and instead provided the validator function directly.
export function phoneNumberValidator(control: AbstractControl) {
  ...
}

@Component({
  selector: 'fe-phone-number-input',
  templateUrl: './phone-number-input.component.html',
  styleUrls: ['./phone-number-input.component.scss'],
  providers: [
    {
      provide: MatFormFieldControl,
      useExisting: forwardRef(() => PhoneNumberInputComponent)
    },
    {
      provide: NG_VALIDATORS,
      useValue: phoneNumberValidator,
      multi: true
    }
  ]
})
export class PhoneNumberInputComponent implements MatFormFieldControl<string>,
  ControlValueAccessor, OnDestroy {
  ...
  constructor(@Optional() @Self() public ngControl: NgControl) {
    if (this.ngControl) {
      this.ngControl.valueAccessor = this;
    }
  }
}

Comment: How would you go about accessing the input component instance from the validator function? Is it even possible?
Comment: @DmitryEfimenko How does your answer help in this case as one cannot use dependency injection to get the injector because the validator function is defined outside of a class so it has no constructor?
Comment: @MaxMumford see my answer below
Answer: My solution takes the idea from @blid, but rather duplicating the same @Inputs as the component that's being validated has, I inject the component via dependency injection like so:
@Directive({
  selector: 'fe-phone-number-input, [fePhoneNumber]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: PhoneNumberInputValidatorDirective,
      multi: true
    }
  ]
})
export class PhoneNumberInputValidatorDirective implements Validator {
  constructor(private injector: Injector) {}

  validate(control: FormControl) {
    // use @Self to get the only instance of component that this validator is directly attached to
    // use @Optional so that this validator can be used separately as a directive via attribute `fePhoneNumber`
    const phoneNumberInputComponent = this.injector.get(PhoneNumberInputComponent, undefined, InjectFlags.Self | InjectFlags.Optional);

    if (phoneNumberInputComponent?.myInput) {
      // some custom logic
    }
    return null;
  }
}

Comment: checking for basics: did you declare the new Directive in the `declarations` of your module? Does the constructor execute? Put a console.log statement there to check
Comment: I tried this but in my case the `validate` function is simply never being called and validation does not work. Any idea, why?
Comment: I created the Directive automatically via VS Code so I don't know if it was automatically added to the `declarations` or not. I cannot check this anymore because I was already able to solve the problem with @Martin's suggestion in the meanwhile. Nevertheless, thanks for the help!
Answer: A clean of doing this is to create a @Directive with the same selector as the @Component. This way enables the @Directive to mirror any @Input the @Component has and account for it when validating.
@Directive({
  selector: 'fe-phone-number-input',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: PhoneNumberInputValidatorDirective,
      multi: true
    }
  ]
})
export class PhoneNumberInputValidatorDirective implements Validator { ... }

Answer: I'm not sure you need to implement the validator interface. For my custom controls I use the injected ngControl for any validation.
@Component({
  selector: 'fe-phone-number-input',
  templateUrl: './phone-number-input.component.html',
  styleUrls: ['./phone-number-input.component.scss'],
  providers: [
    {
      provide: MatFormFieldControl,
      useExisting: forwardRef(() => PhoneNumberInputComponent),
    },
  ],
})
export class PhoneNumberInputComponent
  implements MatFormFieldControl<string>, ControlValueAccessor
{

  constructor(@Optional() @Self() public ngControl: NgControl) {
    if (this.ngControl != null) {
      this.ngControl.valueAccessor = this;
    }
  }

  updatePhone(phone: string) {
    this.value = phone;
    this.ngControl.control?.updateValueAndValidity();
  }
}

<input
  class="phone-number-input mat-input-element"
  type="text"
  (blur)="updateValue(phoneInput.value)"
  [required]="required"
  #phoneInput
/>


Why are regression problems called "regression" problems?

Question: I was just wondering why regression problems are called "regression" problems. What is the story behind the name?

One definition for regression:
  "Relapse to a less perfect or
  developed state."
Comment: See second paragraph of "History" section https://en.m.wikipedia.org/wiki/Regression_analysis
Answer: The term "regression" was used by Francis Galton in his 1886 paper "Regression towards mediocrity in hereditary stature". To my knowledge he only used the term in the context of regression toward the mean. The term was then adopted by others to get more or less the meaning it has today as a general statistical method.
Comment: Galton derived a linear approximation to estimate a son's height from the father's height in that paper. His equation was fitted so an average height father would have an average height son, but a taller than average father would have a son that is taller than average by 2/3 the amount his father is. Same with shorter than average. This could be argued to be a simple linear regression (today's meaning). And of course today regression has an even broader meaning: it's any model that makes continuous predictions. It is interesting how much his original usage of that word has changed.
Comment: Answer by NRH is correct. The following link gives lot more details on Francis Galton's paper "Regression towards mediocrity in hereditary stature" http://blog.minitab.com/blog/statistics-and-quality-data-analysis/so-why-is-it-called-regression-anyway
Comment: Galton used data from both parents. Resist paraphrases and mangled memes: the original paper is at http://galton.org/essays/1880-1889/galton-1886-jaigi-regression-stature.pdf
Comment: is it time for the statistics community to replace the word 'regression' with a more straightforward and clear term, maybe 'formulaic predictor' ?
Answer: @Mark White mentioned the link already but for those of you who do not have much time to check the link, here's the exact properly referenced answer:
Origin of 'regression'
The term "regression" was coined by Francis Galton in the 19th century to describe a biological phenomenon. The phenomenon was that the heights of descendants of tall ancestors tend to regress down towards a normal average (a phenomenon also known as regression toward the mean)(Galton, reprinted 1989). For Galton, regression had only this biological meaning (Galton, 1887), but his work was later extended by Udny Yule and Karl Pearson to a more general statistical context (Pearson, 1903).
References
https://en.wikipedia.org/wiki/Regression_analysis#History
Galton, F. (1877). Typical laws of heredity. III. Nature, 15(389), 512-514.
Galton, F. (reprinted 1989). Kinship and Correlation. Statistical Science, 4(2), 80–86.
Pearson, K. (1903). The law of ancestral heredity. Biometrika, 2(2), 211-228.
Comment: Galton's regression as in 'regression to the mean' makes sense.
however I don't understand use of the word 'regression' to mean 'learn a formula from independant variables to an outcome variable'
Comment: It more generally means that, but machine learning uses regression but regression is not a machine learning technique, despite popular, incorrect opinion. Statistical learning is separate from machine learning but in general, ML proponents take statistical methods and incorrectly label them as ML so the apparent incongruities pop up. Galton's regression is regression; it has to do with modeling/predicting a tendency.
Answer: As opposed to progressing, we are falling back to the mean, i.e. regressing. Hence the term regression ! I think its something that got picked up and stuck.
Answer: I arrived here via a search for how a regression got its name. Here are the interesting parts of what I found (mostly from wikipedia.)

The term "regression" was coined by Francis Galton in the nineteenth century to describe a biological phenomenon. The phenomenon was that the heights of descendants of tall ancestors tend to regress down towards a normal average (a phenomenon also known as regression toward the mean).7,8 For Galton, regression had only this biological meaning,9,10 but his work was later extended by Udny Yule and Karl Pearson to a more general statistical context.11,12 In the work of Yule and Pearson, the joint distribution of the response and explanatory variables is assumed to be Gaussian. This assumption was weakened by R.A. Fisher in his works of 1922 and 1925.13,14,15 Fisher assumed that the conditional distribution of the response variable is Gaussian, but the joint distribution need not be. In this respect, Fisher's assumption is closer to Gauss's formulation of 1821.

Also very interesting:

In the 1950s and 1960s, economists used electromechanical desk "calculators" to calculate regressions. Before 1970, it sometimes took up to 24 hours to receive the result from one regression.16

Sources

Mogull, Robert G. (2004). Second-Semester Applied Statistics. Kendall/Hunt Publishing Company. p. 59. ISBN 978-0-7575-1181-3.

Galton, Francis (1989). "Kinship and Correlation (reprinted 1989)". Statistical Science. 4 (2): 80–86. doi:10.1214/ss/1177012581. JSTOR 2245330.

Francis Galton. "Typical laws of heredity", Nature 15 (1877), 492–495, 512–514, 532–533. (Galton uses the term "reversion" in this paper, which discusses the size of peas.)

Francis Galton. Presidential address, Section H, Anthropology. (1885) (Galton uses the term "regression" in this paper, which discusses the height of humans.)

Yule, G. Udny (1897). "On the Theory of Correlation". Journal of the Royal Statistical Society. 60 (4): 812–54. doi:10.2307/2979746. JSTOR 2979746.

Pearson, Karl; Yule, G.U.; Blanchard, Norman; Lee,Alice (1903). "The Law of Ancestral Heredity". Biometrika. 2 (2): 211–236. doi:10.1093/biomet/2.2.211. JSTOR 2331683.

Fisher, R.A. (1922). "The goodness of fit of regression formulae, and the distribution of regression coefficients". Journal of the Royal Statistical Society. 85 (4): 597–612. doi:10.2307/2341124. JSTOR 2341124. PMC 1084801.

Ronald A. Fisher (1954). Statistical Methods for Research Workers (Twelfth ed.). Edinburgh: Oliver and Boyd. ISBN 978-0-05-002170-5.

Aldrich, John (2005). "Fisher and Regression". Statistical Science. 20 (4): 401–417. doi:10.1214/088342305000000331. JSTOR 20061201.

Rodney Ramcharan. Regressions: Why Are Economists Obessessed with Them? March 2006. Accessed 2011-12-03.
Answer: "Regression" comes from "regress" which in turn comes from latin "regressus" - to go back (to something).
In that sense, regression is the technique that allows "to go back" from messy, hard to interpret data, to a clearer and more meaningful model. As a physicist, I like the idea, as physicists see natural phenomena as the multiple possible outcomes of a relatively simple natural law.
In other words, the word regression seems to suggest that data is just the visible, tangible effect of a "statistical model". In other words, the model comes first, and your desire is use the data "to go back" to what originated them.
Comment: Sorry, but I can't endorse your personal gloss on the word _regression_ as fit for wider use. The origin of the word in Galton's (not Dalton's) work is clear and well documented. It is unfortunate that its original biological meaning has nothing to do with most applications since, but the solution -- if that is seen as a problem -- is to avoid the term, not to attempt unilateral definition.
Comment: This isn't how the term arose, as other threads explain.
Comment: Full disclosure: I confess I did not know the origins of the word in a statistical context when I wrote this. However (the latin meaning is unambiguous and) the somehow flowery "definition" above of why it is used in the context of what we mean by regression, seems equivalent to the one intended by Dalton?


Unity3D PlayableDirector play timeline animation backwards

Question: I have made a zooming animation to get a close view of a GameObject. I am triggering this animation by using the PlayableDirector. I can just call the Play() method on this.
But if the user is zoomed in, I want to make it possible to zoom out as well. This should be able, but I do not know how. Is there something like a reverse method available on the PlayableDirector?
I would appreciate any insight / advice.
Thanks in forward.
Answer: At the moment, this is not possible in a simple way. The tricky way is to invert the clips in a semi-automatic way, as described here: https://forum.unity.com/threads/how-can-i-play-an-animation-backwards.498287/#post-5004851
Answer: you can use a while loop to evaluate the time
<code>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;

public class TimelineManager : MonoBehaviour
{
    private PlayableDirector timeline;
    private bool _isPlaying;

    private void Awake()
    {
        timeline = GetComponent<PlayableDirector>();
    }

    public void PlayAnimation()
    {
        if(_isPlaying) return;
        StartCoroutine(Play());

    }

    public void ReverseAnimation()
    {
        if(_isPlaying) return;
        StartCoroutine(Reverse());
    }

    IEnumerator Play()
    {
        _isPlaying = true;

        float dt = 0;
        while (dt < timeline.duration)
        {
            dt += Time.deltaTime / (float) timeline.duration;

            timeline.time = Mathf.Max(dt, 0);
            timeline.Evaluate();
            yield return null;
        }

        _isPlaying = false;
    }

    private IEnumerator Reverse()
    {
        _isPlaying = true;

        float dt = (float) timeline.duration;

        while (dt > 0)
        {
            dt -= Time.deltaTime / (float) timeline.duration;

            timeline.time = Mathf.Max(dt, 0);
            timeline.Evaluate();
            yield return null;
        }

        _isPlaying = false;
    }
}
</code>