AngularJs native slide toggle for nested submenues doesn't update height correctly

Question: I'm implementing the a slide toggle for a nested menu in AngularJS. I've been using the code from the following page: https://blog.assaf.co/native-slide-toggle-for-angularjs-1-4-x/
I'm having only one problem with it though. I'm trying to implement this on a sidenav menu with nested submenues, built with
 and
 elements. After having toggled a menu item that has submenu, and I later toggle the submenu of that same menu button, the
 element of that menu button doesn't slide in. The height remains the same.
Also, if I keep the submenu closed, and open only the top menu item, the height of the
 element remains the same when I toggle the submenu, meaning that the submenu doesn't show until I toggle it open (though remaining invisible), then close the top menu button, then open it again.
Please see it in action here:
https://codepen.io/marcus-edensky/pen/MBoWZJ
Here's my JavaScript code:
app.controller('myCtrl', function($scope, $mdSidenav) {
});

app.animation('.slide-toggle', ['$animateCss', function($animateCss) {
    var lastId = 0;
    var _cache = {};

    function getId(el) {
        var id = el[0].getAttribute("data-slide-toggle");
        if (!id) {
            id = ++lastId;
            el[0].setAttribute("data-slide-toggle", id);
        }
        return id;
    }
    function getState(id) {
        var state = _cache[id];
        if (!state) {
            state = {};
            _cache[id] = state;
        }
        return state;
    }

    function generateRunner(closing, state, animator, element, doneFn) {
        return function() {
            state.animating = true;
            state.animator = animator;
            state.doneFn = doneFn;
            animator.start().finally(function() {
                if (closing && state.doneFn === doneFn) {
                    element[0].style.height = '';
                }
                state.animating = false;
                state.animator = undefined;
                state.doneFn();
            });
        }
    }

    return {
        addClass: function(element, className, doneFn) {
            if (className == 'ng-hide') {
                var state = getState(getId(element));
                var height = (state.animating && state.height) ?
                    state.height : element[0].offsetHeight;

                var animator = $animateCss(element, {
                    from: {height: height + 'px'},
                    to: {height: '0px'}
                });
                if (animator) {
                    if (state.animating) {
                        state.doneFn =
                          generateRunner(true,
                                         state,
                                         animator,
                                         element,
                                         doneFn);
                        return state.animator.end();
                    }
                    else {
                        state.height = height;
                        return generateRunner(true,
                                              state,
                                              animator,
                                              element,
                                              doneFn)();
                    }
                }
            }
            doneFn();
        },
        removeClass: function(element, className, doneFn) {
            if (className == 'ng-hide') {
                var state = getState(getId(element));
                var height = (state.animating && state.height) ?
                    state.height : element[0].offsetHeight;

                var animator = $animateCss(element, {
                    from: {height: '0px'},
                    to: {height: height + 'px'}
                });

                if (animator) {
                    if (state.animating) {
                        state.doneFn = generateRunner(false,
                                                      state,
                                                      animator,
                                                      element,
                                                      doneFn);
                        return state.animator.end();
                    }
                    else {
                        state.height = height;
                        return generateRunner(false,
                                              state,
                                              animator,
                                              element,
                                              doneFn)();
                    }
                }
            }
            doneFn();
        }
    };
}]);

(function() {
    var app = angular.module('app', ['ngAnimate']);

    app.animation('.slide-toggle', ['$animateCss', function($animateCss) {
        return {
            addClass: function(element, className, doneFn) {
                if (className == 'ng-hide') {
                    var animator = $animateCss(element, {
                        to: {height: '0px'}
                    });
                    if (animator) {
                        return animator.start().finally(function() {
                            element[0].style.height = '';
                            doneFn();
                        });
                    }
                }
                doneFn();
            },
            removeClass: function(element, className, doneFn) {
                if (className == 'ng-hide') {
                    var height = element[0].offsetHeight;
                    var animator = $animateCss(element, {
                        from: {height: '0px'},
                        to: {height: height + 'px'}
                    });
                    if (animator) {
                     return animator.start().finally(doneFn);
                    }
                }
                doneFn();
            }
        };
    }]);
})();

Here's the HTML - a simple :

Tours

Group tours

Planning

Types

Users

Staff

Clients

Here's the CSS:
.slide-toggle {
  overflow: hidden;
  transition: all 0.25s;
}

Answer: The parent still holds the height after the animation. You have to remove it.
Add element[0].style.height = 'auto' after animation is done.In the generateRunner function at line 36 after the if
function generateRunner(closing, state, animator, element, doneFn) {
  return function () {
    state.animating = true;
    state.animator = animator;
    state.doneFn = doneFn;
    animator.start().finally(function () {
      if (closing && state.doneFn === doneFn) {
        element[0].style.height = '';
      }
      element[0].style.height = 'auto'; // <----- HERE
      state.animating = false;
      state.animator = undefined;
      state.doneFn();
    });
  }
}

Hope this helps. Good luck!


Arquivo em Formato MSG - Assinatura Outlook

Question: Tenho um arquivo em formato msg, se eu clico nele duas vezes ele abre no outlook com uma assinatura configurada.
Porém ele contém imagens, alguém sabe como faço para editar o local que carrega as imagens neste arquivo? pois tenho que colocá-las online no servidor para todos poderem visualizar.
Não sei como edito ele ou como altero para formato html por exemplo.
Answer: Descobri como, basta abrir o arquivo que está em formato msg, então ele será exibido em formato de mensagem no Outlook, após vai em arquivo/salvar e escolhe formato html. Após edita o arquivo que está em formato html, e altera o local das imagens, inserindo o endereço delas online. Após acessa a pasta de assinaturas do Outlook, <code>%appdata%\Microsoft\Assinaturas</code> e substitui alguma assinatura que contem neste local em formato html pelo novo arquivo.


Rank of matrix with parameters

Question: i need a little help with an exercise on my class. We have to do this exercise
for a = 2, b = 4, c = 0
How can i determine λ if a know that the rank of the matrix is 2 ?
Comment: also please indicate symbols correctly,i can't see $c$ in your determinant
Comment: Find the determinant and see for which $\lambda$ it is 0 (there are at most four such values for $\lambda$). Then put those values in the matrix and see when you get a matrix whose rank is 2 (by using Gauss row operations); or use row reduction since the beginning
Answer: if rank of matrix is $2$,it means for  matrices for sizes more then  $2$,all minor determinants and also  whole determinant is just zero,so you need to compute determinants seperately with size more then   $2$ and set to zero,also dont forget there must be  at least one matrix with size  $2$ by $2$ with non zero determinant
Comment: my matrix is

{{3+l,  6,  3,  l+3},{6, 7,  3,  7},{3,    3,  7,  6},{l+3,  7,  6,  11}}

can you help me with that. So i can understand how i have to resolve exerises like this ?

Rank of matrix with parameters


How to find an element which its two childs match with two different values?

Question: I want to use Python selenium to find the specific server on Speedtest website. For example, I want to find the server which its host-location is Dagupan City and host-sponsor is USATV One Inc.
Below is how the html code looks like. There will be lots of the same classname inside. What should I do to match with two different values from this?
Thanks!

        Dagupan City

        USATV One Inc

        Park City, Utah

        Utah Broadband

        Nagaoka

        CanopusAzusa

        Jakarta

        PT. Aplikanusa Lintasarta

Answer: Something like:
//a[span[@class='host-location' and contains(text(),'Dagupan City')] and span[@class='host-sponsor' and contains(text(),'USATV One Inc')]]

Demo:

References:

XPath Tutorial
XPath Axes
XPath Operators & Functions
XPath Element that contains 2 children that each match a specific text
Comment: I use "find_elements_by_xpath" to implement you code and it works! However, it will get a list includes two elements. Is that normal? I can't find another element on my website.
Comment: Wouldn't `a[contains(., 'Dagupan City') and contains(., 'USATV One Inc')]` work just as well?
Answer: you can also try like
//span[@class='host-sponsor'][contains(text(),'USATV One Inc')]/parent::a/span[contains(text(),'Dagupan City')]/parent::a

Answer: To find the server with respect to its children class attribute host-location e.g. Dagupan City and host-sponsor e.g. USATV One Inc as the elements are dynamic elements, you need to induce WebDriverWait for the desired elements and you can use the following  Locator Strategy:

XPath:
element = WebDriverWait(driver,15).until(lambda driver: driver.find_element_by_xpath("//a[span[@class='host-location' and contains(.,'Dagupan City')]]") and driver.find_element_by_xpath("//a[span[@class='host-sponsor' and contains(.,'USATV One Inc')]]"))


Virtual server freeze (apache ?)

Question: I rent a small virtual server at 1und1.de. (Link, but German only) (2GB RAM dynamic, 512MB at least, 20 GB HDD) I choose to run a Ubuntu 8.04 LTS as operating system (64 Bit). I installed apache2 + php5 + mysql via the Ubuntu repositories and later eAccelerator.
I running some development stuff and a production site. This site is a kind of directory and has a few visitors (250 each day) and a lot of pages (about 7,5k). Every few days the servers freezes. This means, it's up, could be pinged, but any other action will result in "server refused connection". Looking into the admin panel it says that my kmemsize is to high and also there a lot of apache processes that were spawned.
For me it seems that my apache consumes all my ressources (and it also seems, that these freezes seems to start if Google or another crawler start to crawl the page).
Then I tried to avoid this freezes:

I lowered MaxKeepAliveRequests and KeepAliveTimeout in the Apache config
I set MaxRequestsPerChild in the setting of the prefork settings, to keep Apache workers cleaned more often.

This seems to improve the situation, but still freezes are happening.
Anyone any idea what could / should be changed?
Solution.
Answer: Figure out what the problem Actually Is:
Don't start tuning until you have used something like top or the ps command to see what is actually using the memory.  It could be anywhere in the stack ( Mysql, PHP, Apache ).  If it is Apache...
Switch to lighter HTTP Daemon:
Have you considered lighter HTTP daemon such as:

lighttpd
Nginx

Consider a different MPM with Apache:
I would test this a lot before pushing this into production, but you might consider switching the the worker (instead of perfork) Multi-Processing Module (MPM).  This article says this was used at dealnews.com and it helped with memory usage.  I haven't done this with Ubuntu, but I think it is just:
sudo apt-get remove apache2-mpm-prefork
sudo apt-get install apache2-mpm-worker

But you might want to consider building Apache from source so you only have the modules you need, that can be kind of a big project though. Also, from the article keep in mind:

This is an important part. You can't
  use radical extensions in PHP when you
  are using worker.

Tune PHP as Well:
This IBM Developerworks article has some php tuning options that might help reduce memory as well.
Tune MySQL as Well:
The third article in the above IBM Lamp tuning article talks about MySQL tuning.  This can end up using quite a bit of memory.
Comment: I have to stick to Apache because some of my testing stuff needs some mods that are only availabe for apache. Mysql is fine, 95% of all http-requests could be handled from a harddisk cache. I thought of switching to worker, but this needs a lot of work, but I will try.
Comment: i install mpm_worker and used fastcgid (big mess), tweaked my eaccelerator and now its nearly perfect...
Comment: Hippo: So are you saying you ended up going with the worker?
Comment: yes, installation was a mess (not that easy as you wrote) but it works really nice. thanks you answer and the interessting links.

Virtual server freeze (apache ?)


How to properly parse a PDF and read if checkboxes are checked

Question: I'm trying to parse PDF forms on server side. I tried many node.js modules like pdf2json, hummus and node-pdftk and I'm able to get all the text fields but not if checkboxes are checked.
I've been testing with different files (like this one) and pdf2json always returns an empty string as every checkbox value while hummus gives true. With pdftk I get FieldValue and FieldStateOption fields and compare them as I read in this answer but neither the result seems to be correct.
Can anybody give me some advice, please?
Answer: See if using the pdffiller package works. The generateFDFTemplate method should do the trick. As per the README:
var pdfFiller = require('pdffiller');

var sourcePDF = "test/test.pdf";

// Override the default field name regex. Default: /FieldName: ([^\n]*)/
var nameRegex = null;

var FDF_data = pdfFiller.generateFDFTemplate( sourcePDF, nameRegex, function(err, fdfData) {
    if (err) throw err;
    console.log(fdfData);
});

will print out:
{
    "last_name" : "",
    "first_name" : "",
    "date" : "",
    "football" : "",
    "baseball" : "",
    "basketball" : "",
    "hockey" : "",
    "nascar" : ""
};

Hope this helps :)


Understanding why $\det(A) = \det(A^T)$ via the 3D Paralleliped

Question: I am trying to understand why, geometrically, we have that
$$
\det(A) = \det(A^T).
$$
To build intuition, I am thinking in 3 dimensions. So let $A$ be a $3 \times 3$ matrix of real numbers.
First, I know that if
$$
\det(A) = \left|
\begin{array}
xx_1 & y_1 & z_1 \\
x_2 & y_2 & z_2 \\
x_3 & y_3 & z_3
\end{array}
\right|
$$
then $|\det(A)|$ can be thought of as the area of a parallelepiped formed by $(x_1, x_2, x_3)$, $(y_1, y_2, y_3)$, and $(z_1, z_2, z_3)$.
Moreover, the fact that $\det(A) = \det(A^T)$ implies that $|\det(A)|$ can also be thought of as the area of the parallelepiped formed by
$(x_1, y_1, z_1)$, $(x_2, y_2, z_2)$, and $(x_3, y_3, z_3)$.
Question: Does this also mean that the area of a parallelepiped formed by any permutation of the $x_i$, $y_i$, and $z_i$ is equal to $|\det(A)|$? For example, does the area of a parallelepiped formed by the coordinates $(x_1, y_2, z_3)$, $(x_2, y_1, z_2)$, and $(x_3, y_3, z_1)$  equal $|\det(A)$|?
Comment: Possible duplicate of [Determinant of transpose?](http://math.stackexchange.com/questions/598258/determinant-of-transpose)
Comment: @AOrtiz, the title of the question certainly suggests it is a duplicate of the question you linked to.  However, the question at the end of the post seems quite different from what the title suggests.  I don't think this is a duplicate (of that question at least).  A bit of a misleading title...
Answer:
Here is a 2D example.
$$\begin{pmatrix}
2&3\\
1&4\\
\end{pmatrix} \mapsto_{transpose}
\begin{pmatrix}
2&1\\ 3&4\\
\end{pmatrix}$$
I'm still thinking of a satisfying (geometric) explanation as to why this always works, but pictures are always good.
Comment: I really like this picture. As for the geometric explanation, for the 2d case I think you might be able to use Heron's formula: https://en.wikipedia.org/wiki/Heron%27s_formula, specifically the version $A= \frac{1}{4} \sqrt{4 a^2b^2 - (a^2 + b^2 -c^2)^2}$. If we have a matrix $$M = \begin{bmatrix} m_1 & m_2 \\ m_3 & m_4 \end{bmatrix}$$ then $a^2 = m_1^2 + m_3^2, b^2 = m_2^2 + m_3^2, c^2 = (m_2 - m_1)^2 + (m_4 - m_3^2)$. When we take the transpose $M^T=M'$, then in the formula for $A'$, we have $a^2= m_1^2 + m_2^2, b^2 = m_3^2 + m_4^2, c^2 = (m_4-m_2)^2+(m_3-m_1)^2$.
Comment: Clearly for both triangles $a^2 + b^2$ is the same, although $c^2$ is not. However, the term $4a^2b^2=(2ab)^2$ compensates exactly for the difference.
Answer: Short answer is no.
For example suppose that $A$ is the identity matrix.  The vectors are then $(x_1, y_1, z_1)=(1,0,0)$, $(x_2, y_2, z_2)=(0,1,0)$, and $(x_3,y_3,z_3)=(0,0,1)$.  And $\text{det}(A)=1$.  However, you could make a permutation $(x_1, y_2, z_3)=(1, 1, 1)$ and $(x_2, y_1, z_1)=(0, 0, 0)$ and $(x_3, y_3, z_2)=(0, 0, 0)$.  The volume enclosed by those vectors is certainly not 1--in fact it is $0$.
Comment: It is preserved, however, if you permute rows or columns. You just can't permute in a way that can't be done by permuting rows and columns. To be clear, the area remains the same, though the sign of the determinant can change.
Comment: @abnry, I think you meant to comment on the question (not this answer).  The example provided by the OP includes permutations other than just permuting the rows.


How can I make my AMP redundant?

Question: *I have made a static HTML page using the AMP boilerplate which contains details of a fruit product say apple, so my URL looks like
www.xyz.com/apple
The page contains a simple <amp-carousel> and some data with src relevant to apple.(product in route) Which contains the title 'Apple', 3 images inside <amp-img> of <amp-carousel>, and an <amp-list> with src depending upon URL route/path.
Lets say I have other products whose details I want to show by changing route path to www.xyz.com/orange, www.xyz.com/pears, www.xyz.com/grapes etc.
SupposeI want to keep it dynamic depending upon the URL, say for www.xyz.com/orange, my static page would now contain similar information, but relevant to URL path - ie. orange/pears/grapes
As the different product contains the different title, different number of images for amp-list, amp-carousel or any simple list, how can I make my content dynamic for updated path in URL using ReactJS/ES6 syntax.
Also, provide any information about data flow/lifecycle methods for AMP pages before HTML is made on the server(which I assume I am missing).
Answer: First off, you can't use ReactJS or ES6 in an AMP page as stated in the AMP spec here.
What you're trying to do will require a fairly basic set up on the backend that'll take the path to determine what data to use to build an AMP page.

How can I make my AMP redundant?


Retrive entire column to a new file if it matches from list of another file

Question: I have a huge file and I need to retrieve specific columns from File1 which is ~ 200000 rows and ~ 1000 Columns if it matches with the list of file2. (Prefer Bash over R )
for example my dummy data files are as follows,
file1
gene    s1  s2  s3  s4  s5
a      1    2   1   2   1
b      2    3   2   3   3
c      1    1   1   1   1
d      1    1   2   2   2

and file2
sample
s4
s3
s7
s8

My desired output is
gene       s3   s4
    a       1   2
    b       2   3
    c       1   1
    d       2   2

likewise, i have 3 different file2 and i have to pick different samples from the same file1 into a new file.
I would be very greatful if you guys can provide me with your valuable suggestions
P.S: I am a Biologist, i have very little coding experience
Regards
Ateeq
Comment: Thanks, Cyrus for letting me know that Novice are not allowed here. but I think I fall under Enthusiastic group, if not professional. anyways, i used the following code, awk -F',' 'NR==FNR{c[$1]++;next};c[$1] > 0' list_genes.csv file2.csv.....for this i need to transpose the data which i want to avoid.
Comment: Since I guess you haven't done it yet: take the [tour](https://stackoverflow.com/tour) and take a look at SO's [Help Center](https://stackoverflow.com/help).
Comment: thanks Cyrus! its really helpful!!!
Comment: Novices are allowed and encouraged, but if you really want anyone trying to help you, give the information as easy as possible to work with. Nobody will translate the images into text to try posible solutions. But if you give text (that can be copied and pasted) chances are many people will try to help you.
Comment: I have removed the image, and created a dummy file and data, since whenever i paste it is forcing me to save the data as an image. Apologies !!!
Answer: $ cat file1
gene    s1  s2  s3  s4  s5
a      1    2   1   2   1
b      2    3   2   3   3
c      1    1   1   1   1
d      1    1   2   2   2
$ cat file2
gene
s4
s3
s8
s7
$ cat a
awk '
NR == FNR {
  columns[ NR ] = $0
  printf "%s\t", $0
  next
}
FNR == 1 {
  print ""
  split( $0, headers )
  for (x = 1 ; x <= length(headers) ; x++ )
  {
    aheaders[  headers[x]] = x
  }
  next
}
{
  for ( x = 1 ; x <= length( columns ) ; x++ )
  {
    if (length( aheaders[ columns[x]  ] ) == 0 )
      printf "N/A\t"
    else
      printf "%s\t" , $aheaders[ columns[x] ]
  }
  print ""
}
' $*

$ ./a file2 file1 | column -t

gene  s4  s3  s8   s7
a     2   1   N/A  N/A
b     3   2   N/A  N/A
c     1   1   N/A  N/A
d     2   2   N/A  N/A

The above should get you on your way.  It's an extremely optimistic program and no negative testing was performed.
Awk is a tool that applies a set of commands to every line of every file that matches an expression.  In general, the awk script has the form:
<pattern> <command>

There are three such pairs above.  Each needs a little explanation:
NR == FNR {
  columns[ NR ] = $0
  printf "%s\t", $0
  next
}

NR == FNR is a awk'ism.  NR is the record number and FNR is the record number in the current file.  NR is always increasing but FNR resets to 1 when awk parses the next file.  NR==FNR is an idiom that is only true when parsing the first file.
I've designed the awk program to read the columns file first (you are calling this file2).  File2 has a list of columns to output.  As you can see, we are storing each line in the first file (file2) into an array called columns. We are also printing the columns out as we read them.  In order to avoid newlines after each column name (since we want all the column headers to be on the same line), we use printf which doesn't output a newline (as opposed to print which does).
The 'next' at the end of the stanza tells awk to read the next line in the file without processing any of the other stanzas.   After all, we just want to read the first file.
In summary, the first stanza remembers the column names (and order) and prints them out on a single line (without a newline).
The second "stanza":
FNR == 1 {
  print ""
  split( $0, headers )
  for (x = 1 ; x <= length(headers) ; x++ )
  {
    aheaders[  headers[x]] = x
  }
  next
}

FNR==1 will match on the first line of any file.  Due to the next in the previous stanza, we'll only hit this stanza when we are on the first line of the second file (file1).  The first print "" statement adds the newline that was missing from the first stanza.  Now the line with the column headers is complete.
The split command takes the  first parameter, $0, the current line  and splits it according to whitespace.  We know the current line is the first line and has the column headers in it.  The split command writes to an array named in the second parameter , headers.  Now headers[1] = "gene" and headers[2] = "s4" , headers[3] = "s3", etc.
We're going to need to map the column names to the column numbers.  The next bit of code takes each header value and creates an aheaders entry.  aheders is an associative array that maps column header names to the column number.
aheaders["gene"] = 1
aheaders["s1"] = 2
aheaders["s2"] = 3
aheaders["s3"] = 4
aheaders["s4"] = 5
aheaders["s5"] = 6

When we're done making the aheaders array, the next command tells awk to skip to the next line of the input.  From this point on, only the third stanza is going to have a true  condition.
{
  for ( x = 1 ; x <= length( columns ) ; x++ )
  {
    if (length( aheaders[ columns[x]  ] ) == 0 )
      printf "N/A\t"
    else
      printf "%s\t" , $aheaders[ columns[x] ]
  }
  print ""
}

The third stanza has no explicit .  Awk will process this as always true.  So this last  is executed for every line of the second file.
At this point, we want to print the columns that are specified in columns array.  We walk through each element of the array in order.  The first time through the loop, columns[1] = "gene_symbol".  This gives us:
printf "%s\t" , $aheaders[ "gene" ]

And since aheaders["gene"] = 1  this gives us:
printf "%s\t" , $1

And awk understands $1 to be the first field (or column) in the input line.  Thus the first column is passed to printf which outputs the value with a tab (\t) appended.
The loop then executes another time with x=2 and columns[2]="s4".  This results in the following print executing:
printf "%s\t" , $5

This prints the fifth column followed by a tab. The next iteration:
columns[3] = "s3"
aheaders["s3"] = 4

Which results in:
printf "%s\t" , $4

That is, the fourth field is output.
The next iteration we hit a failure situation:
columns[4] = "s8"
aheaders["s8"] = ''

In this case, the length( aheaders[ columns[x]  ]  ) == 0 is true so we just print out a placeholder - something to tell the operator their input may be invalid:
printf "N/A\t"

The same is output when we process the last columns[x] value "s7".
Now, since there are no more entries in columns, the loop exists and we hit the final print:
print ""

The empty string is provided to print because print by itself defaults to print $0 - the entire line.
At this point, awk reads the next line out of file1 hits the third   block again (only).  Thus awk continues until the second file is completely read.
Comment: You meant ["without further ado"](https://idioms.thefreedictionary.com/without+further+ado). But you just don't need that for your answer.


Python unit test cannot find module

Question: I have a question about how to correctly import module in python unit test module.
this is my directory structure
project -
        | _ Library _
        |            |_ TimeCalculator.py
        | _ Test _
                  |_ UnittestFile.py

and I want to test the function in TimeCalculator.py
so in UnittestFile.py I write
from .Library.TimeCalculator import TimeCalculator

but the error come out saying ImportError: attempted relative import with no known parent package
I want to ask how to import without setting the PATH in this case.
Answer: As stated in python - Running unittest with typical test directory structure - Stack Overflow, you should create a __init__.py file in both folders, Library and Test.
For your specific structure:
project
├── Library
│   ├── __init__.py         # make it a package
│   └── TimeCalculator.py
└── test
    ├── __init__.py         # also make test a package
    └── UnittestFile.py

Then, you should remove the first . from your import sentence:
from Library.TimeCalculator import TimeCalculator

PD: Not sure if is a repeated question, because the answer is almost the same than python - Running unittest with typical test directory structure - Stack Overflow but is sightly different because he has to remove the first .
Comment: I think that's a good duplicate target. The `.` just seems like a typo.

Python unit test cannot find module


Display title with React Helmet

Question: I'm using Gatsby's inclusion of react-helmet to display <title /> and <meta /> tags in the . What I'd really like to do is send the same title to my global  component so the title is displayed in the actual text of the page as well as in the head. How would I accomplish something like this with React? I'm used to Ember where I can just set a pageTitle property on the Application controller/route and pass it down to components as well as update the  values with something like ember-wormhole.
I understand I could use Flux for a global state or I could pass setTitle to my page components and they could send up a setTitle action on each Page component's componentDidMount, but is there a better way to handle this? Perhaps with React Router 4?
So far, I was able to pull in the location context like so:
const TemplateWrapper = (args) => {
  const { children, location } = args
  return (

      <Helmet title={location.pathname} />

        {children()}

  )
}

So I could add a function in there to lookup a page title based on the path, but I'd like the "Title" of the page to be set globally instead.
Answer: React Helmet has an onChangeClientState property that can be used to get the newState when a <Helmet> component changes state.
Using the example in the post's question:
class Template extends Component {
  state = {
    title: 'Default Title'
  }
  render() {
    return (

        <Helmet onChangeClientState={(newState) => this.setState({ title: newState.title }) } />

          {this.props.children}

    );
  }
}

This way if you set title in a sub-component with <Helmet> the global title state will change to reflect and update the title elsewhere in the app.
Comment: According to [the docs](https://github.com/nfl/react-helmet/blob/master/README.md#reference-guide), it's actually supposed to be `onChangeClientState`

Display title with React Helmet


How to inverse this equation which can give the devisors values of numbers

Question: The roots of the following equation
$f(x) = sin^2(\pi*x) + sin^2(\pi*n/x)$
are the positive and negative devisor of ($n$)
For example, if we set ($n=7$) then ($x$) will have 4 real values {-7,-1,1,7}
and so for all prime numbers.
To make sure try to set integers to ($n$) and draw the equation.
Now the question is:
Is there any way to inverse this equation
$sin^2(\pi*x) + sin^2(\pi*n/x) = 0$
and find $x = f(n)$ by using Lambert W-function or any other technique?
If it is found then we can check the given number $n$ whether it is a prime or not by only calculating the equation real roots.
Comment: $a^2 +b^2=0$ Find out condition for $x$ any then you will get $n$.
Comment: Sometimes, in analytic number theory, a trick of this general nature can lead to very useful results. But I do not see a way to exploit your very nice observation.
Comment: @AndréNicolas Why? The OP wanted a relation between $x$ and $n$ . and I gave that in my answer. Have I done it wrong?
Comment: @Qwerty: My comment was intended for Nasser Dawood. Of course your explanation of why the result holds is correct. But the question seemed to be at least in large part about using the fact to produce a primality test, or more generally to factor $n$.
Comment: @Qwerty Indeed the explanations in your answer are most probably how the OP concocted their formula in the first place.
Answer: $\sin(\pi x)=0\implies x=\{k:k\in\Bbb{Z}\}$
$\sin(\pi n/x)=0\implies n/x=\{m:m\in\Bbb{Z}\}\implies n=\{xm:x,m\in\Bbb{Z}\}$


How to write the following pattern mathematically?

Question: $$
\begin{array}{c|l}
n & k \\
\hline
4&6\\
5&9\\
6&\frac{25}{2} \\
7&\frac{33}{2} \\
8&21 \\
9&26 \\
10&\frac{63}{2} \\
11& \frac{75}{2}
\end{array}$$
I observed the following pattern.
$$\underbrace{6 \to 9}_{3} \underbrace{\to \frac{25}{2}}_{\frac{7}{2}} \underbrace{\to \frac{33}{2}}_{4} \underbrace{\to 21}_{\frac{9}{2}} \underbrace{\to 26}_{5} \underbrace{\to \frac{63}{2}}_{\frac{11}{2}} \underbrace{\to \frac{75}{2}}_{6}$$
Then the difference between two consecutive resulting numbers is $\frac{1}{2}$.
How to write the relation between $n$ & $k$?
Comment: You've noticed that the second differences are constant, and so you should be looking for a quadratic equation.
Comment: Where is this pattern coming from?  Are you just given a bunch of terms?
Comment: I found a pattern in this number set. I just
Comment: You can interpolate them with a function which has a derivative which integrates to a linear function. Which functions have a linear derivative?
Comment: Hint: Write the integer differences as halves of integers and you'll see a clearer pattern. Then Use @Joppy 's observation to find a quadratic expression for $k$ as a function of $n$.
Comment: Thank you! I got the recursive formula!
Comment: Why did you remove text from your question?
Answer: Hint Since the successive differences $\Delta k = k(n + 1) - k(n)$ are linear, $k$ is given by a quadratic expression in $n$.
Alternatively, one can modify appropriately the usual identity $$\sum_{i = 1}^m i = \frac{1}{2} m (m + 1)$$ to produce an expression for the partial sum of any arithmetic sequence.

In response to a comment, here's how one can apply the second hint:
The observed pattern says that $k(4) = 6$ and that the value $k(n)$ is given by adding to $k(4) = 6$ the $n - 4$ half-integers starting with $3$:
$$k(n) = 6 + \sum_{i = 1}^{n - 4} \left(3 + \frac{i - 1}{2}\right) .$$
Notice that if one only wants some explicit expression for $k(n)$, this above certainly suffices. It works for $n = 4$, too, taking the usual convention that an empty sum has value zero. Now, if one wants a closed-form expression for this quantity, we can manipulate this sum so that we can take advantage of the above formula for the sum of the first $m$ integers:
$$
\begin{align*}
k(n)
&= 6 + \sum_{i = 1}^{n - 4} \left(\frac{5}{2} + \frac{i}{2}\right) \\
&= 6 + \frac{5}{2} (n - 4) + \frac{1}{2} \sum_{i = 1}^{n - 4} i \\
&= -4 + \frac{5}{2} n + \frac{1}{2} \sum_{i = 1}^{n - 4} i .
\end{align*}
$$
Taking $m = n - 4$ in the sum formula and substituting gives
$$k(n) = -4 + \frac{5}{2} n + \frac{1}{2} \left[\frac{1}{2} (n - 4)[(n - 4) + 1]\right] = \frac{1}{4} n^2 + \frac{3}{4} n - 1.$$
Comment: Thank you very much for answering !
Comment: You're welcome.
Comment: By using the recursive formula I could obtained the sequence. But I didn't understand the relation of the partial sum.
Comment: @Oily I've added some details about how one can use that formula for the partial sum to produce a closed-form formula for $k(n)$.
Comment: You're welcome, I hope it was useful.
Comment: Yes. It was the exact idea that I needed to know. Thank you once again!
Answer: It is a sequence, right? You can define it recuresively as:
$a_0 = 0$, $a_1 = 1.5$ and
$a_{n+1} = a_n + (a_n-a_{n-1}) + \frac{1}{2}$ for $n\geq 1$
Answer: Hint$$g(k) = \int_{k}^{k+1} \frac{\partial f(x)}{\partial x} \partial x$$
where $g$ is the function you enumerate and the integral is your observation.


Accessing the UI object from a background thread

Question: While developing an application for windows Phone 7.1 , i encountered the below problem.
I have separate thread for managing my views . And i want this to access the Navigation stack which is a part of the UI thread. How can i achieve this ?
I have a function in my view manager which gets triggerd every time a view change (navigation) occurs.
Any help ?
Answer: You could use the Deployment.Current.Dispatcher.BeginInvoke to execute the passed delegate on the UI thread. I am not clear about the specifics of your requirement. Could you add more context? Also, this question has more insight into it.
Comment: BackEntries should be manipulated only on the UI thread. The API is synchronous and should be called from the UI thread. Things could go wrong if you could wipe the stack from another thread. You'll have to pass your methods into the BeginInvoke (as a delegate) to do [this](http://msdn.microsoft.com/en-us/library/system.windows.navigation.navigationservice.removebackentry(v=vs.92).aspx).
Comment: I need to clear my navigation history, in order to do that i need access to Navigation stack. This action i want to do it in a separate thread.


Markov transition kernels of process with independent increments

Question:
Suppose that $\{X_t : Ω → S := \mathbb{R}^d, t\in T\}$ is a stochastic
process with independent increments and let $\mathcal{B}_t :=\mathcal{B}_t^X$ (natural filtration) for all $t\in T$. Show, for all
$0 ≤ s < t$, that $(X_t − X_s )$ is independent of $\mathcal{B}_s^X$ and then
use this to show $\{X_t\}_{t\in T}$ is a Markov process with
transition kernels defined by $0 ≤ s ≤ t$, $$q_{s,t}(x, A) := E [1_A (x + X_t − X_s )]\text{ for all }A\in \mathcal{S}\text{ and }x\in\mathbb{R}^d.$$

The first part showing that $X_t-X_s$ is independent of $\mathcal{B}^X_s$. I more or less understand from a monotone class lemma.
For the part where I need to compute the transition kernel, I am not sure what I have to show. Is seems to me I have to show $P(X_t\in A|X_s)=q_{s,t}(X_s,A)$, is that correct? To do this I observe
\begin{align}
P(X_t\in A|X_s)=E(1_{X_t\in A}|X_s)=E(1_A(X_t)|X_s)=E(1_A(X_t-X_s+X_s)|X_s)
\end{align}
But then I am not sure how to finish. The exercise hintes that I should use that $X_t-X_s$ is independent of $\mathcal{B}^X_s$.
Comment: @USER408858, maybe this was the right idea. I tried to make it more formal in my own answer to my question
Comment: The right hand side of $P(X_t\in A|X_s)=q_{s,t}(x,A)$ takes a value $x$, which should occur on the left hand side, too. Note, that $E[Y|\mathcal{G}]=E[Y]$, if $Y$ is independent from $\mathcal{G}$.
Comment: Yes, that was a typo. Yes but $X_t-X_s$ is independent of $\mathcal{F}_s$, so independent of $X_s$ and as consequence $1_A(X_t-X_s)$ is independent of $X_s$. But we don't have that $X_t$ is independent of $\mathcal{F}_s$ or $X_s$ no? So Why is $1_A(X_t)$ independent of $X_s$?
Comment: I have to say, it's a while ago, since I studied on Markov kernels. However, it seems, when you plug in $\omega$, you have $q_{s,t}(X_s(\omega),A)=E[1_A(X_s(\omega)+X_t-X_s)]$, so $1_A(X_s(\omega)+X_t-X_s)$ would still be treated as $f(X_t-X_s)$.
Answer: $\newcommand{\G}{\mathcal{G}}
\newcommand{\F}{\mathcal{F}_s}$
I am going to try to answer my question using these three sources source1, source2, source3.
The result seems to be based on this result I didn't know:

lemma : Let $X$ be measurable with respect to $\G$ and $Y$ be independent with respect to $\G$. Then $E[f(X,Y)|\G]=E[f(x,Y)]|_{x=X}$.
Proof : Define $g(x)=E[f(x,Y)]$. By the averaging property of conditional expectation, we need to show that $E[f(X,Y)Z]=E[g(X)Z]$
for every bounded $\G$-measurable $Z$. Also note that since $X$ and
$Z$ are $\G$-measurable, $(X,Z)$ is $\G$-measurable and since Y is
independent of $\G$ we have that $(X,Z)$ is independent of $Y$. Then
$$E[f(X,Y)Z]=\int f(x,y)z d\mu_{X,Y,Z}=\int d\mu_{X,Z}z\left[\int
d\mu_{Y}f(x,y)\right]=\int d\mu_{X,Z}zg(x)=E[g(X)Z].$$ Since $g(X)$ is
$\G$-measurable, we have proven $E[f(X,Y)|\G]=g(X)=E[f(x,Y)]|_{x=X_s}$.

To show that we have a Markov process we need to show $P(X_t\in A|\F)=P(X_t\in A| X_s)$. However $$P(X_t\in A|\F)=E[1_A(X_t-X_s+X_s)|\F]$$ and since $X_t-X_s$ is independent of $\F$ and $X_s$ is $\F$-measurable, we can apply the lemma to find $$P(X_t\in A|\F)=E[1_A(X_t-X_s+x)]|_{x=X_s}.$$ Last, since $\sigma(X_s)\subset\F$ we can apply the tower property and the same reasonning as above to see $$P(X_t\in A|X_s)=E[1_A(X_t-X_s+X_s)|X_s]=E[E[1_A(X_t-X_s+X_s)]|\F]|X_s]=E[E[1_A(X_t-X_s+x)]|_{x=X_s}|X_s]=E[1_A(X_t-X_s+x)]|_{x=X_s}$$ were the last equality comes from the fact that $h(X)=E[1_A(X_t-X_s+x)]|_{x=X_s}$ is clearly $\sigma(X_s)$-measurable. Then we have shown that $P(X_t\in A|\F)=P(X_t\in A| X_s)$ and moreover $P(X_t\in A|\F)=E[1_A(X_t-X_s+x)]|_{x=X_s}$. However, since $P(X_t\in A|X_s)=q_{st}(X_s,A)$ this means $q_{st}(x,A)=E[1_A(X_t-X_s+x)]$
Comment: Great! I'm glad my idea helped. Your answer has some slight mistakes, I guess. I think you should have written $P(X_t\in A|X_s)=E[1_A(X_t-X_s+X_s)|X_s]=E[E[1_A(X_t-X_s+X_s)]|\mathcal{F}_s]|X_s]=E[E[1_A(X_t-X_s+x)]|_{x=X_s}|X_s]=E[1_A(X_t-X_s+x)]|_{x=X_s}$
Comment: Since I get a bit confused of the "$\Big|_{x=X_s}$" notation myself, I wrote an additional answer. I hope, you can find some further inspiration from it.
Comment: @USER408858, Yes thank you. I is always useful to have different perspectives.
Answer: The lemma you cite, states following: If $Y$ is independent of $\mathcal{G}$, it holds
$$h(X,Y)(\omega)=E[f(X,Y)|\mathcal{G}](\omega)=E[f(X(\omega),Y)]=g(X)(\omega),$$
Note: Because of the independence of $Y$ from $\mathcal{G}$, the random variable $E[f(X,Y)|\mathcal{G}]$ loses the randomness of $Y$, so to speak.
$$ $$
In the situation of the question, we use $f(x,y)=1_A(x+y)$ and find
$$E[1_A(X_s+X_t-X_s)|\mathcal{F}_s](\omega)=E[1_A(X_s(\omega)+X_t-X_s)]=g(X_s)(\omega),$$
i.e.
$$E[1_A(X_s+X_t-X_s)|\mathcal{F}_s]=g(X_s)$$
Note: The notation "$\Big|_{x=X_s}$" turns the expression on the left of it into a function of $X_s$: $$E[1_A(x+X_t-X_s)]\Big|_{x=X_s(\omega)}=E[1_A(X_s(\omega)+X_t-X_s)]=g(X_s)(\omega)$$
$$ $$
Using the tower-property and the fact, that $g(X_s)$ is $\sigma(X_s)$-measurable, we find
$$
\begin{align}
P(X_t\in A|\mathcal{F}_s)&=E[1_A(X_s+X_t-X_s)|\mathcal{F}_s]\\
&=g(X_s)\\
&=E[g(X_s)|X_s]\\
&=E[E[1_A(X_s+X_t-X_s)|\mathcal{F}_s]|X_s]\\
&=E[1_A(X_s+X_t-X_s)|X_s]\\
&=P(X_t\in A|X_s)
\end{align}
$$
$$ $$
From this, we have also found the transition kernel:
$$q_{s,t}(X_s(\omega),A)=P(X_t\in A|X_s)(\omega)=P(X_t\in A|\mathcal{F}_s)(\omega)=E[1_A(X_s(\omega)+X_t-X_s)]$$
Note: The transition kernel is exactly the function, that we used in the lemma, since $$q_{s,t}(X_s(\omega),A)=g(X_s(\omega))$$
Comment: let's share the reward. I keep my answer and you take the bounty
Comment: By the way what do you think about the "reverse question" : Given a process $X_t$ , say we construct a process with kernels $q_{st}(x,A)=1_A(X_t-X_s+x)$ then this process will have automatically independent increments?
Comment: I don't think this must hold true. There is a theorem that states, that any set of markov kernels define a markov process and vice versa, such that the marginal distribution of $X$ is well-defined via the markov kernels. (Klenke, Theorem 17.8) However, the Ornstein-Uhlenbeck process seems to be a Markov process without independent increments, according to the following source: https://math.stackexchange.com/a/1758122/408858


como remover todos os resquícios de dados no cache do google busca?

Question: já desabilitei a indexação (robots.txt) e já fiz a inserção da meta tag (<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">) no  da página, porém quando eu procuro no meu site para ver se há algum resquício de dado no google busca, percebo que há várias informações alí ainda.
há uma outra maneira de remover todas informações do meu site de uma vez só? eu sei da existência deste link:
https://www.google.com/webmasters/tools/removals
porém, é necessário adicionar link por link.
Comment: Você quer remover seu site da busca do Google?
Comment: Quando você fez esses ajustes?
Comment: eu fiz as modificações no meio de outubro. quando eu pesquiso "nome do meu site + nome da pessoa" os dados aparecem em forma de cache (são dados antes de outubro). são alguns dados sigilosos.
Comment: Tentou testar em navegador de outras pessoas que nunca acessaram o site?
Comment: como assim? é no google search que faço a busca
Comment: O tempo de reindexação pode ser de até 1 ou 2 semanas pelo que eu me recordo. Se informe melhor a respeito disso, mas te garanto que as modificações não acontecem no ato, você terá que esperar alguns dias...
Comment: não tem mais nenhum dado do dia 20 de outubro para cá (quando fiz a indexação), o problema são os dados já antigos, todos ainda estão lá e são bastante. se eu remover um por um, vai dar um trabalhão.
Answer:
Apenas como observação, não é possível dizer com toda a certeza o como o google funciona, apenas podemos interpretar as informações na documentação no google então estarei apenas deixando uma sugestão do que pode estar causando isso

O que sabemos pela documentação
Primeiro de tudo, o robots.txt indica apenas que o google não deve indexar o seu site, porém se o site já está indexado a documentação não indica que isso seria o suficiente par remover este conteúdo.
https://support.google.com/webmasters/answer/6062608
O uso da meta noindex vai impedir que o google de indexar o seu site, porém para isso ele precisa poder enxergar esta tag, se você usar o robots para bloquear a página ele nunca vai ver esta tag.
https://support.google.com/webmasters/answer/93710
Então o que pode estar acontecendo
Uma possibilidade é de que o google ao tentar buscar conteúdo atualizado de seu site se depare com o robots.txt que pede para ele não indexar o site, e como o google respeita seu pedido ele nem mesmo chega a ver se o conteúdo de sua página mudou.
Porém o google já possui uma página sua indexada, e esta página que ele possui indexada no cache dele não possui nenhuma informação de que ela não deve estar lá, o que pode ser o que está fazendo o google manter sua página nas pesquisas dele.
O que poderia resolver o problema
Talvez o que você precise fazer não é impedir o crawler do google de verificar o seu site, ao contrário talvez permitir ele fazer isso temporariamente possa fazer com que seu problema seja resolvido.
Remover o robots.txt para permitir que ele tente buscar estas mesmas páginas que ele já possui indexadas vai fazer com que ele encontre a meta noindex, e permitindo que ele atualize seu cache, removendo a página antiga.
Caso isso funcione e não apareçam mais resultados das suas páginas você pode voltar o robots.txt para diminuir as requisições ao seu site vindas do crawler do google.


How do I create a view that uses data from an external site

Question: I have a site that needs to get articles data from a view in site A in order to display these articles as a view in site B.
I found the module Services Views, which i don't completely understand.
I have installed it in site A, and created a services resource of a view with services display.
But how do I create a view in site B that displays the articles using that services endpoint?
Answer: You can use views_database_connector and include connection details to your settings.php and database will be available to views
add connection details to your settings.php
<code>"example_db" = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'example',
      'username' => 'example_user',
      'password' => 'example_pass',
      'host' => 'xxx.xxx.xxx.xxx',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);
</code>
and when you create a view you can choose specific table from this database to connect to
Should work for both drupal 7 & 8
Answer: You can do it in 2 ways, Store the data in site B and not store the data
By Storing the data

expose data from the site A.
Grab the data and store it in site B.
Display the data in site B.

To achieve (1) you can use many modules for this; I would suggest Views data export
For (2) You can use Feeds module, it will grab the data and import it.
For (3) You just create a view of the content you store.
Without Storing the data
Use Views Database Connector
Answer: A view was intended to pull data from the site DB, so you can not just add a view to site B.
After you added a services resource to site A you need to add some client code on site B that would pull this data and display it to the user. You can either code it all by yourself or use, for instance, Web Service Clients.


How is AUC helpful when we only need one threshold of a classifier

Question: AUC is a summation of performance at different thresholds, but do we only care about a good performance at one threshold?
Imagine a classifier with a low ROC but shots up at point of a low FP and high TP, is it better than another classifier with a higher and smooth ROC?
Maybe a more reasonable example: classifier A has a larger AUC with fuller and smoother ROC, while B`s ROC is flatter but has a hump. Which to choose?
Comment: One alternate statistic is the Kolmogorov-Smirnov test statistic. Basically, the maximum of the difference between the true positive rate and the false negative rate. At this point, though, you should probably define what the maximum "acceptable" TPR/FPR values are, or as other functions of the confusion matrix. You can tune models with these statistics in mind, but that's really up to your discretion.
Answer: If you are using a 2-class classification model which outputs a likelihood of datapoint being in positive class, then the ratio of True Positives (TPs) and False Positives (FPs) will only monotonically increase with the increase in the threshold value, for any sane model.
Since this likelihood can be any real number between 0 and 1 in our setting, intuitively, it is expected that the ratio of TPs and FPs will also increase smoothly as the likelihood increases. So any spikes or sudden/sharp increases in ROC are not a very good sign. It is undesirable that the performance of a model drastically changes/decreases with only slight changes in threshold, as it can impact the stability of the resulting predictions especially if such models are put to production.
Comment: Thanks @Aravind G.! I like the 'smoothly' explaination.

Let me use another example: classifier A has a larger AUC with fuller and smoother ROC, while B`s ROC is flatter but has a hump. Which to choose?
Comment: If I have to choose a model between A and B to put in production, with only this limited information, I would definitely go with classifier A.

@LinZhu But say, if I'm writing a research paper and I have to showcase the best results, I'll investigate more into what's causing the hump in B's ROC, and I might go with either A or B depending on the situation.
Answer: For notations, ROC AUC is some metric to measure the quality of binary classifiers (assigning 0 and 1), that return for each case some score $s$ indicating how much the classifier favors this case to be considered as 1.
First, I am not sure what you refer to by "hump", but keep in mind that the ROC curve can only go up and to the right, so there are no real humps.
Second, maybe you think of two ROC curves, where the first has larger ROC AUC, but the second one is crossing the first one at some point, such that it is "above" the first one. But note that "being above another curve" is not really a sign of quality, e.g. completely random classifiers can be, more towards the right or the diagram, above a good classifier.
The very point of ROC AUC is that you have a metric that is independent of a threshold for $s$. Imagine some anomaly detection method $C$, which scores all measurements with the score $s$, indicating how likely $C$ considers them to be anomalies. Now, the standard way to work through the results is to first investigate the cases that are most likely to be anomalies, and then work your way down as your time permits. Note, that you don't use a threshold here. You cannot do this with classifiers that only give you a binary result, because you don't know which is most likely to be an anomaly. But you can do this with classifiers that return a score. And ROC AUC is a metric that compares this capability of classifiers. A scoring classifier is better if it shows you the real anomalies first. And that is exactly what ROC AUC measures.
But it always depends on what you want. If you want to turn a classifier, that returns scores, into a classifier, that only returns 1 or 0 depending on whether the score $s$ is above or below the threshold, because you as a domain expert know that this is the exact threshold to use and no other would be correct, then you shouldn't use ROC AUC.


find the derivative with fundamental theorem of calculus

Question: I came to cos(cos(sin(x)^3)+sin(x)), which is incorrect. I have a hunch that the error is somewhere around the sin x and the exponent. I'm just not sure what to do to fix it.
Answer: Let $g : \mathbb{R} \to \mathbb{R}$ be defined by
$$g(u) = \int_{-1}^u \cos(t^3) + t ~ dt$$
Then $g'(u) = \cos(u^3) + u$ by the fundamental theorem of calculus. Using $F(x) = g(\sin(x))$ and the chain rule for derivatives, we have
$$\frac{d}{dx} F(x) = \frac{d}{dx} (g(\sin(x))) = g'(\sin(x)) \cdot \sin'(x) = (\cos(\sin(x)^3) + \sin(x)) \cdot \cos(x).$$
Answer: Hint
The fundamental theorem of calculus is $$\frac{d}{dx}\int_{a(x)}^{b(x)} F(t) \, dt=F(b(x)) b'(x)-F(a(x)) a'(x)$$
Applied to your case, this uses $F(t)=\cos(t^3)+t$, $a(x)=-1$, $b(x)=\sin(x)$ then $a'(x)=0$, $b'(x)=\cos(x)$.
I am sure that you can take from here and find where you made a mistake.


Multi Domain Kerberos configuration with 1 way trust

Question: I had configured Multi Domain Kerberos SSO for documentum client with 1 way trust between the domains... But while logging into client, i am getting the below error...
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: resetting state...
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: principal = 'HTTP/mdk1waytrustd3.wtmdk1waydom3.com'
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: realm = 'WTMDK1WAYDOM3.COM'
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: Found name servers using JNDI
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: mdk1waytrustd2.wtmdk1waydom2.com (10.31.70.183)
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: mdk1waytrustd1.wtmdk1waydom1.com (10.31.69.52)
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: MDK1WAYTRUSTD3.WTMDK1WAYDOM3.COM (10.31.70.184)
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: mdk1waytrustd4.wtmdk1waydom4.com (10.31.71.34)
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: corpinba8.corp.emc.com (10.30.48.37)
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: corpgefr3.corp.emc.com (18.104.22.168)
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: The old JCSI Kerberos code for the Windows LSA is now disabled by default;
if you really want it (rather than the new WinSSPI code) you must set
        -Djcsi.kerberos.lsa.enable=true
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: Creating LSA credential cache
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: Could not locate default cache: com.dstc.security.kerberos.KerberosException: Could not create credential store com.dstc.security.kerberos.KerberosException: Native in-memory credential cache not supported on this platform (Windows Server 2008 R2)
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: login succeeded
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: loaded InputStream based keytab at time 1351158964992 m/secs, 5 entries
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: binding principal to subject
[DEBUG] Thu Oct 25 02:56:04 PDT 2012 jcsi.kerberos: binding credentials to subject
Can someone can help me in overcoming this issue???
Comment: Where is the error? I see only debug output!
Answer: Root caused due to 'krb5login.conf' using dstc login module rather than the old sun.security.auth module. Try modify your krb5login.conf as follows and you will be happy. :)
<code>HTTP-mdk1waytrustd3-wtmdk1waydom3-com
{
com.dstc.security.kerberos.jaas.KerberosLoginModule required
principal="HTTP/mdk1waytrustd3.wtmdk1waydom3.com"
noTGT=true
debug=true
refreshKrb5Config=true
useKeyTab=true
storeKey=true
doNotPrompt=true
useTicketCache=false
isInitiator=false
realm="WTMDK1WAYDOM3.COM"
keyTab="C:\\keytab location\\keytab.keytab";
};
</code>


How to use try and except in django?

Question: I wanted to use try and except in djagno template is there is any way to use it.
I want to check either attendance table has any data of not. and if not it has to show error text
{% try %}
    {% for attendances in attendance %}
        ....
    {% endfor %}
{% except %}

Error Attendance table has no data.

Answer: Instead of try-catch, you can use Django's built-in for..empty template tag.
{% for attendances in attendance %}
        ....
{% empty %}

Error Attendance table has no data.

{% endfor %}

This will show the error message if the table is empty.

How to use try and except in django?


nginx valid_referer for all files inside a directory

Question: I have this config
<code>location /mirror/files {
    valid_referers none server_names example.com *.example.com;
         if ($invalid_referer) {
            rewrite ^/(.*)$ http://example.com/;
        }
    index index.php;
}
</code>
If I visit a link http://example.com/mirror/files/test.zip with referer that start with "http://example2.com" I can access the file.
How to make it work?
UPDATE: I can see from the server logs the referer is sent so it's not empty.
Answer: OK the reason was that I was using a localhost referer (my local development env) and apparently nginx treats that if it's coming from the local server which is silly since the IP should be checked if it's local as well.
Solution is either use real domains as referers or set your local server with another severname than localhost.


Change hot spot color in HTML on mouse over

Question: How to change hot spot color in HTML on mouse over?
Comment: What is a hot spot color?
Answer: if you mean the hover-color , you could do it like this (:hover-pseudo-class):
.myelement:hover{
  color:#ff0000;
  background-color:#00ff00;
}

(this works also with class- or tag-selectors, but only on a in old IE versions)
if anything else is meant by "hot spot color": i've no idea what you're talking about...


Eigenvalues of a tridiagonal trigonometric matrix

Question: Let $D$ be the diagonal matrix w/alternating in sign diagonal entries:
$$D_{kk}=(-1)^{k+1}\tan(\frac{k\pi}{2n+1}),$$
where $k=1,2,\dots n\in N$, and let $B$ be the $n$ by $n$ square $(0,1)$-matrix
$$B=
\begin{pmatrix}
 0     & 1 & 0 & \ldots & 0 \\
 1     & 0 & 1 & \ldots & 0 \\
 0     & 1 & \ddots & \ddots & \vdots \\
 \vdots    & \vdots & \ddots & 0 & 1 \\
 0     & 0  & \ldots & 1 & 1 \\
\end{pmatrix}.
$$
(a) Prove, that the eigenvalues of the product matrix $(-1)^{n+1}DB$ are
$$
 2\sin\left(\frac{k\pi}{2n+1}\right), \,\, k=1,2,\dots,n.
$$
The result follows from a continued fraction identity w/a lengthy proof and an exercise from the open Wiki book "On 2D Inverse Problems" (http://en.wikibooks.org/wiki/On_2D_Inverse_Problems), but a direct shorter proof w/some geometric intuition would be very useful.
(b) The matrix $D$ is a discrete version of the operator $\frac{d^2}{dx^2}+2+\delta$. Is there differential/continuous/limiting equation version of the result in (a)?
Comment: Are you completely sure you need the factor $2$ in the denominator of tangent?
Answer: Let me use $n=5$ to show the result. It is easy to generalize the result for general $n$. For $n=5$, let $a_k=\tan\frac{k\pi}{11}$ and
$$ A=\left(\begin{matrix}a_1&0&0&0&0\\
0&-a_2&0&0&0\\
0&0&a_3&0&0\\
0&0&0&-a_4&0\\
0&0&0&0&a_5\\
\end{matrix}\right),D=\left(\begin{matrix}0&1&0&0&0\\
1&0&1&0&0\\
0&1&0&1&0\\
0&0&1&0&1\\
0&0&0&1&1\\
\end{matrix}\right). $$
Then the corresponding characteristic polynomial is
\begin{eqnarray*} p(\lambda)&=&\det(\lambda I-AD)=\left(\begin{matrix}\lambda&-a_1&0&0&0\\
a_2&\lambda&a_2&0&0\\
0&a_3&\lambda&-a_3&0\\
0&0&a_4&\lambda&a_4\\
0&0&0&-a_5&\lambda-a_5\\
\end{matrix}\right)\\
&=&\lambda^5-a_5x^4+(a_1a_2+a_2a_3+a_3a_4+a_4a_5)x^3-(a_1a_2a_5+a_2a_3a_5+a_3a_4a_5)x^2\\
&=&+(a_1a_2a_3a_4+a_1a_2a_4a_5+a_2a_3a_4a_5)x-a_1a_2a_3a_4a_5.
\end{eqnarray*}
Let
$$f(\lambda)=(\lambda-b_1)(\lambda-b_2)(\lambda-b_3)(\lambda-b_4)(\lambda-b_5)$$
where $b_k=2\sin\frac{k\pi}{11},k=1,2,3,4,5$. Now we show that $p(\lambda)$ and $f(\lambda)$ are have the same coefficient for each $x^k$, $k=0,1,2,3,4$ and hence $b_k,k=1,2,3,4,5$ are the eigenvalues of $AD$. For simplicity, we just show that the constant terms of these two polynomials and the coefficients of $x^4$ are the same, respectively, namely.
$$ b_1b_2b_3b_4b_4b_5=a_1a_2a_3a_4a_5, b_1+b_2+b_3+b_4+b_5=a_5 $$
and the rest will be tedious computations.
In fact, since
\begin{eqnarray*}
&&32\cos\frac{\pi}{11}\cos\frac{2\pi}{11}\cos\frac{3\pi}{11}\cos\frac{4\pi}{11}\cos\frac{5\pi}{11}\\
&=&\frac{32\sin\frac{\pi}{11}\cos\frac{\pi}{11}\cos\frac{2\pi}{11}\cos\frac{3\pi}{11}\cos\frac{4\pi}{11}\cos\frac{5\pi}{11}}{\sin\frac{\pi}{11}}\\
&=&\frac{16\sin\frac{2\pi}{11}\cos\frac{2\pi}{11}\cos\frac{3\pi}{11}\cos\frac{4\pi}{11}\cos\frac{5\pi}{11}}{\sin\frac{\pi}{11}}\\
&=&\frac{8\sin\frac{4\pi}{11}\cos\frac{3\pi}{11}\cos\frac{4\pi}{11}\cos\frac{5\pi}{11}}{\sin\frac{\pi}{11}}=\frac{4\sin\frac{8\pi}{11}\cos\frac{3\pi}{11}\cos\frac{5\pi}{11}}{\sin\frac{\pi}{11}}\\
&=&\frac{-4\sin\frac{3\pi}{11}\cos\frac{3\pi}{11}\cos\frac{6\pi}{11}}{\sin\frac{\pi}{11}}=-\frac{2\sin\frac{6\pi}{11}\cos\frac{6\pi}{11}}{\sin\frac{\pi}{11}}=-\frac{\sin\frac{12\pi}{11}}{\sin\frac{\pi}{11}}=1,
\end{eqnarray*}
we have
\begin{eqnarray*}
b_1b_2b_3b_4b_4b_5&=&32\sin\frac{\pi}{11}\sin\frac{2\pi}{11}\sin\frac{3\pi}{11}\sin\frac{4\pi}{11}\sin\frac{5\pi}{11}\\
&=&(\tan\frac{\pi}{11}\tan\frac{2\pi}{11}\tan\frac{3\pi}{11}\tan\frac{4\pi}{11}\tan\frac{5\pi}{11})(32\cos\frac{\pi}{11}\cos\frac{2\pi}{11}\cos\frac{3\pi}{11}\cos\frac{4\pi}{11}\cos\frac{5\pi}{11})\\
&=&a_1a_2a_3a_4a_5.
\end{eqnarray*}
Using that
$$ \sum_{k=1}^N\sin k\theta=\frac{1}{2}\cot\frac{\theta}{2}-\frac{\cos(N+\frac{1}{2}\theta)}{2\sin\frac{\theta}{2}}  $$
we have
\begin{eqnarray*}b_1+b_2+b_3+b_4+b_5
&=&2(\sin\frac{\pi}{11}+\sin\frac{2\pi}{11}+\sin\frac{3\pi}{11}+\sin\frac{4\pi}{11}+\sin\frac{5\pi}{11})\\
&=&2\cdot\frac{1}{2}\cot\frac{\pi}{22}=\tan(\frac{\pi}{2}-\frac{\pi}{22})=\tan\frac{5\pi}{11}=a_5
\end{eqnarray*}
Comment: How has nobody upvoted this???
Comment: Actually, to show that the rest of the coefficients are the same is to use some identities like the following $$ \sum_{k=1}^n\sin\frac{k\pi}{2n+1}=\frac{1}{2}\cot\frac{\pi}{2(2n+1)} $$ and $$ \prod_{k=1}^n\cos\frac{k\pi}{2n+1}=\frac{1}{2^n} $$ and others.
Comment: Do you have intuition on why the rest of the coefficients of the polynomials are equal?
Comment: The answer to this question may be helpful: http://math.stackexchange.com/questions/392908/a-trigonometric-identity-for-special-angles
Comment: @Daved Thank you for telling me this link.


Given the word SCHOOL, how many different 3 letter arrangements can you form?

Question: I found this question in an assessment book and noticed the answer key was wrong (via manual listing and an alternative method) but could not figure out why (the answer key's method seems reasonable).

Can you help me understand why the answer key's method undercounts?
Can you help me fix the working in the answer key (but use the same approach)?

Please comment for question 1 even if you can't solve question 2!
Working and comparison of methods:
Comment: The division by $2!$ would have been done in order to "forget" which O was which since there are two of them in order to not differentiate between words like O**O**L and **O**OL.  However, such a distinction doesn't matter when there is only one or no O's used in the word.
Comment: "*Can I fix method 2*"  I wouldn't bother trying to shoehorn it in... its not worth the effort.  That said, method1 isn't as efficient as it should be either.  You can break into *two* cases rather than three.  Either both O's are used, giving $4\times 3=12$ outcomes (*choose the other letter used other than O, and which position it occupies in the word*), or at most one O is used, giving $5P3=5\times 4\times 3=60$ outcomes (*using your notation*) for a total of $12+60=72$
Comment: Hi, please add some thought you have put into this/attempts you have made. Also try to use [mathjax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for mathematical expressions, since it is searchable and pictures are not. As a hint to why it is wrong: $^6P_3$ counts the permutations that contain 2 times the letter 'O' twice. To compensate for that, they divide by 2, but that not all strings of 3 letters contain 'O' twice so you divide 'too many possibilities' by 2. A solution could be to look at strings that contain one or zero times the ...
Comment: ...letter 'O' and look at the cases that contain both 'O' 's seperately.
Comment: Thank you for the replies! I came up with method 1, which I write in full form for clarity over efficiency (includes 1 more term). I find method 2 very attractive as it has only 1 term and presently suppose you are right and it cannot be made to work. Please let me know if you have an ingenious method of making method 2 work!
Answer: $60 = \frac {5!}{2!}$ counts all of the three-letter combinations of the elements $\{S,C,H,O,L\}$ -- the distinct letters of SCHOOL.
It does not count strings with 2 O's
There are $12$ three-letter strings with two O's.  (4 for the choice of the 3rd letter times 3 for its placement in the string.)
Comment: In your first line, it would be better to say all the $3$-combinations of the letters of SCHOL or all the three-letter strings that can be formed using distinct letters of SCHOL.


Bound on location of critical points of a rational function

Question:
Let $f$ be a rational function with $j$ zeros and $k$ poles, all of which reside in the closed unit disk (excepting of course the zeros or pole at $\infty$ when $j\neq k$).  What is the smallest number $R>0$ such that all the critical points of $f$ must lie in the closed disk centered at the origin with radius $R$?

When $j\neq k$, a lower bound for the answer is $\dfrac{j+k}{|j-k|}$, as can be seen by inspecting the example $f(z)=\dfrac{(z-1)^j}{(z+1)^k}$. I suspect that $R=\dfrac{j+k}{|j-k|}$ is the answer in general (again assuming $j\neq k$).
Comment: unless $j=k$ doesnt $f$ have a zero or a pole at infinity, I guess you don't "count" them ?
Comment: @mercio Thanks, I will edit the question to say that all *finite* zeros and poles lie in the unit disk.
Comment: I thought that this problem had received a correct answer several months ago, but then I came back to look at it, and do not find an answer.  Did the user delete it?
Answer: $\def\Re{\mathop{\mathrm{Re}}}\def\e{\mathrm{e}}\def\i{\mathrm{i}}\def\peq{\mathrel{\phantom{=}}{}}$Define $D = \{z \in \mathbb{C} \mid |z| \leqslant 1\}$.

Lemma 1: For any $z_0 \in D$ and $z = r \e^{\i θ} \in \mathbb{C} \setminus D$,$$
\Re\left( \frac{\e^{\i θ} + z_0}{r \e^{\i θ} - z_0} \right) \geqslant 0.
$$
Proof: It suffices to prove that $\Re((\e^{\i θ} + z_0)(r \e^{-\i θ} - \overline{z_0})) \geqslant 0$. Suppose $z_0 = r_0 \e^{\i θ_0}$, then\begin{align*}
&\peq \Re((\e^{\i θ} + z_0)(r \e^{-\i θ} - \overline{z_0})) = \Re(r- \overline{z_0} \e^{\i θ} + rz_0 \e^{-\i θ} - |z_0|^2)\\
&= \Re(r- r_0 \e^{\i (θ - θ_0)} + rr_0 \e^{\i (θ_0 - θ)} - r_0^2)\\
&= r - r_0 \cos(θ - θ_0) + rr_0 \cos(θ_0 - θ) - r_0^2\\
&= r + r_0 (r - 1) \cos(θ_0 - θ) - r_0^2\\
&\geqslant r - r_0 (r - 1) - r_0^2 = (r + r_0)(1 - r_0) \geqslant 0.
\end{align*}

Lemma 2: For any $z_1, \cdots, z_n \in D$ and $z \in \mathbb{C} \setminus D$,$$
\frac{n}{|z| + 1} \leqslant \left| \sum_{k = 1}^n \frac{1}{z - z_k} \right| \leqslant \frac{n}{|z| - 1}.
$$
Proof: For the RHS,$$
\left| \sum_{k = 1}^n \frac{1}{z - z_k} \right| \leqslant \sum_{k = 1}^n \frac{1}{|z - z_k|} \leqslant \sum_{k = 1}^n \frac{1}{|z| - |z_k|} \leqslant \frac{n}{|z| - 1}.
$$
For the LHS, suppose $z = r \e^{\i θ}$, then\begin{align*}
&\peq \left| \sum_{k = 1}^n \frac{1}{z - z_k} \right| = \frac{1}{|r \e^{\i θ} + \e^{\i θ}|}·\left| \sum_{k = 1}^n \frac{r \e^{\i θ} + \e^{\i θ}}{r \e^{\i θ} - z_k} \right| = \frac{1}{r + 1} \left| n + \sum_{k = 1}^n \frac{\e^{\i θ} + z_k}{r \e^{\i θ} - z_k} \right|\\
&\geqslant \frac{1}{r + 1} \Re\left( n + \sum_{k = 1}^n \frac{\e^{\i θ} + z_k}{r \e^{\i θ} - z_k} \right) = \frac{1}{r + 1} \left( n + \sum_{k = 1}^n \Re\left( \frac{\e^{\i θ} + z_k}{r \e^{\i θ} - z_k} \right) \right)\\
&\geqslant \frac{n}{r + 1} = \frac{n}{|z| + 1},
\end{align*}
where the last inequality is from Lemma 1.

Now, suppose$$
f(z) = \frac{\prod\limits_{m = 1}^j (z - a_m)}{\prod\limits_{m = 1}^k (z - b_m)},
$$
where $a_1, \cdots, a_j \in D$ are zeros of $f$ and $b_1, \cdots, b_k \in D$ are poles, and there are no $1 \leqslant m_1 \leqslant j$ and $1 \leqslant m_2 \leqslant k$ such that $a_{m_1} = b_{m_2}$.
For any critical point $z_0$ of $f$, i.e. $f'(z_0) = 0$, if $z_0 \in D$, then $|z_0| \leqslant 1 \leqslant \dfrac{j + k}{|j - k|}$. Otherwise, $|z_0| > 1$ implies $z_0 \not\in \{a_1, \cdots, a_j\} \cup \{b_1, \cdots, b_k\}$. Note that$$
0 = f'(z_0) = f(z_0) \left( \sum_{m = 1}^j \frac{1}{z_0 - a_m} - \sum_{m = 1}^k \frac{1}{z_0 - b_m} \right),
$$
thus$$
\sum_{m = 1}^j \frac{1}{z_0 - a_m} = \sum_{m = 1}^k \frac{1}{z_0 - b_m}.
$$
From Lemma 2,$$
\frac{j}{|z_0| + 1} \leqslant \left| \sum_{m = 1}^j \frac{1}{z_0 - a_m} \right| = \left| \sum_{m = 1}^k \frac{1}{z_0 - b_m} \right| \leqslant \frac{k}{|z_0| - 1},
$$
then $\dfrac{|z_0| + 1}{|z_0| - 1} \geqslant \dfrac{j}{k}$. Analogously, $\dfrac{|z_0| + 1}{|z_0| - 1} \geqslant \dfrac{k}{j}$. Without loss of generality, assume $j > k$, then$$
\frac{|z_0| + 1}{|z_0| - 1} \geqslant \frac{j}{k} \Longrightarrow k|z_0| + k \geqslant j|z_0| - j\\
\Longrightarrow |j - k|·|z_0| = (j - k)|z_0| \leqslant j + k \Longrightarrow |z_0| \leqslant \frac{j + k}{|j - k|}.
$$


Dynamically loading new jobs in a SidekiqStatus container to monitor completion

Question: I built a small web crawler implemented in two Sidekiq workers: Crawler and Parsing. The Crawler worker will seek for links while Parsing worker will read the page body.
I want to trigger an alert when the crawling/parsing of all pages is complete. Monitoring only the Crawler job is not the best solution since it may have finished but there might be several Parser jobs running.
Having a look at sidekiq-status gem it seems that I cannot dynamically add new jobs to the container for monitoring. E.g. it would be nice to have a "add" method in the following context:
<code>@container = SidekiqStatus::Container.new

# ... for each page url found:

jid = ParserWorker.perform_async(page_url)

@container.add(jid)
</code>
The closest to this is to use "SidekiqStatus::Container.load" or "SidekiqStatus::Container.load_multi" however, it is not possible to add new jobs in the container a posteriori.
One solution would be to create as many SidekiqStatus::Container instances as the number of ParserJobs and check if all of them have status == "finished", but I wonder if a more elegant solution exists using these tools.
Any help is appreciated.
Answer: You are describing Sidekiq Pro's Batches feature exactly.  You can spend a lot of time or some money to solve your problem.
https://github.com/mperham/sidekiq/wiki/Batches
Comment: Thank you Mike, I am sure this could be easily done with Sidekiq Pro. Unfortunately $750/y is over my budget this time...
Answer: OK, here's a simple solution. Using the sidekiq-status gem, the Crawler worker keeps  track of the jobs IDs for the Parser jobs and halts if any Parser job is still busy (using the SidekiqStatus::Container instance to check job status).
<code>def perform()
  # for each page....
    @jids << ParserWorker.perform_async(page_url)
  # end

  # crawler finished, parsers may still be running
  while parsers_busy?
    sleep 5 # wait 5 secs between each check
  end

  # all parsers complete, trigger notification...

end

def parsers_busy?
  status_containers = SidekiqStatus::Container.load_multi(@jids)

  for container in status_containers
    if container.status == 'waiting' || container.status == 'working'
      return true
    end
  end

  return false
end
</code>


Statistical test to compare means when I have two observations per group?

Question: I am trying to interpret the results of my experiment but am not sure what statistical method I should choose. For my experiment, I added 3 types of different fertilizers to soil, with a control, and measured their growth. I only had two replicates per treatment, so my data looks like this:
Treatment   Replicate  Length
Control       1          16
Control       2          18
Fert1         1          20
Fert1         2          17
Fert2         1          25
Fert2         2          27
Fert3         1          23
Fert3         2          21

I think people usually do a minimum of 3 replicates to calculate a "meaningful" standard deviation, but the logistics made it just not possible to do so. In this case, if I want to compare the means of each treatment, and determine whether a specific treatment significantly enhanced or repressed growth, what would be the best method to use? Can I use ANOVA with two observations per group? Would it be better to use the t-test between Control and Fert1 (or Fert2 or Fert3) separately to evaluate effect of each fertilizer to conrol? Would any of these statistical tests (or other tests I'm not aware of) be heavily biased toward having only two observations per group?
Comment: The problem is not bias but power. With too small samples there is hardly any chance to find a significant difference even if a true difference exists. Furthermore there is no way to meaningfully check model assumptions.
Answer: First, the sample variance of a sample of size 2 may
not be the best estimate of the population variance,
but it does exist, so your model with 2 replications
per level of a one-factor experiment should work
according to the usual formulas. in R:
y = c(16, 18);  var(y)
[1] 2

I input your data as follows (please proofread):
x = c(16,18, 20,17, 25,27, 23,21)
g = as.factor(c(4,4, 1,1, 2,2, 4,4))

Notice that for procedures in R that use lm for ANOVA require
that the group vector be declared as.factor.
Standard one-factor ANOVA in R gives results as follows:
anova(lm(x~g))

Analysis of Variance Table

Response: x

          Df Sum Sq Mean Sq F value  Pr(>F)
g          2 71.375  35.688  5.0264 0.06359 .
Residuals  5 35.500   7.100
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R also implements an ANOVA that does not require equal
variances among population levels. The denominator degrees
of freedom are reduced according as sample variances
among the levels differ (in this instance decreased from
5 to 2.68).
oneway.test(x ~ g)

        One-way analysis of means
        (not assuming equal variances)

data:  x and g
F = 9.1961, num df = 2.0000, denom df = 2.6839, p-value = 0.06294

The Kruskal-Wallis nonparametric test, which is somewhat
analogous to a one-factor ANOVA, also works for your
data, provided there are not (many) ties in the x vector.
kruskal.test(x~g)

        Kruskal-Wallis rank sum test

data:  x by g
Kruskal-Wallis chi-squared = 4.125, df = 2,
  p-value = 0.1271

Comment: Thank you for these suggestions! Just to clarify, when you defined `g`, did you mean to set it as `c(4,4, 1,1, 2,2, 3,3)` to reflect different treatments (instead of having two pairs of `4,4`)?
Comment: Also, I looked up the Kruskal-Wallis test and the major difference between that and the one-way ANOVA test seemed to be that the former assumes data is not normally distributed, while the latter assumes a normal distribution. Since I only have two data per treatment (not enough data to check for normal distribution), how should I decide which distribution (normal or not normal) is a more accurate description of my data?
Comment: Unless you have reason to believe data are not normal, I would be comfortable assuming normality. The differences between the two replicates in each group are modest and about the same, which is consistent with normal and even with equal variances. Also, the K-W test has low power with such small samples. So I'd use one of the ANOVAs. // If this is all the data you're going to have for now, you won't have significance at the 5% level, but significance at the 10% level, which might encourage a more extensive look. // (As for K-W: It does not _assume_ normal data, but works OK with normal data.)
Answer: You can run an ANOVA and then do a post-hoc comparison.  With only two observations per group there needs to be decent size differences between the groups.  You can also run Dunnet's Test to compare all three against the control.  See code below.
There is no minimum rule sample size such as 3.  All depends on the effect size you're trying to detect.
library(tidyverse)

a1 = tibble(treatment=c("Control","Control","Fert1","Fert1","Fert2","Fert2","Fert3","Fert3"),
       length=c(16,18,20,17,25,26,23,21))

a1 %>% group_by(treatment) %>% summarize(mean(length),sd(length))

fit=aov(length~treatment,data=a1)
TukeyHSD(fit)

library(DescTools)
DunnettTest(x=a1$length, g=as.factor(a1$treatment))

Comment: Thank you for your suggestion! I ran your code, but when I printed `fit` out, it gives a 2*2 table, with `Sum of Squares` and `Deg. of Freedom` as rows and `treatment` and `Residuals` as columns. This looked very different from other tables I googled, which has variables like `treatment` as rows and `Df`, `Sum sq`, `Mean Sq`, `F value`, `Pr` as columns. Did I make a mistake while I was running this?
Comment: Try `summary(fit)`


Why the question was marked as "unclear" if it is totally clear?

Question: Today 5 users marked this question https://magento.stackexchange.com/review/close/120294 as "Unclear what you asking" when the question is totally clear. How could this happen? What can look unclear in this question? I have nominated this question to reopen, but this is not the main goal because I only want to understand why 5 of 5 reviewers did make such a decision?
Note: here the description of the "Unclear what you asking":

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.

PS: I read similar question What should I do when a question has been incorrectly marked as duplicate? where the answer from the moderator was

The best (and only) thing to do is to post here in Meta for us to review.

because of that, I ask this question here.
UPDATE:
In both cases (see answer given by Mr. sv3n), there are candidates for moderators among the reviewers:

Sander Mangel
Keyur Shah
Manoj Deswal

I would very much like to hear their opinion on this matter in context of election.
Comment: Agree to @BabyinMagento ... missed your name at nomination list.
Comment: please nominate atleast next time, we really & really need moderators like you......
Answer: Can we agree that it is not a good question? I wouldn't even call it "perfectly clear", but rather had down voted and commented than closing it immediately.
What's the problem with it you may ask.
It does not provide any context that would explain what OP is actually trying to achieve, what they already know or what they tried.
"using object manager" is oddly specific. If they know about the object manager, they should know how to get an object from it. That's all, the object manager does and it's the same for any class, so why the question about this particular collection?
Or are they looking for the right class name? That should have been mentioned in the question then.
Why do they even ask for the object manager? It should be used automatically via dependency injection. Do they have a reason not to? Do they not know about it? It might be a case of the x-y problem
So many open questions from a badly worded one liner
Comment: Absolutely right. But the question should not be closed since it is answerable. We don't need to do strict scrutiny here since we already a stable site. Rather, we should encourage OP to improve his/her question by asking or instructing through a comment.
Comment: Yes, this question is very simple and could be googled in 1 minute, but... Why it marked as unclear? What exactly unclear in it? For the answer, we have the "Low Quality" mark, but if this mark does not exist for the question - I think we should not mark a question as unclear when it just has low quality. Does it have sense?
Comment: I agree @RajeevKTomy
Answer: uchukhlebau, thanks for reaching out. In this case when I read the question it didn't come accross to me as clear. Maybe I misread it, that might very well be it.
Now, looking at the with the answers that provide context I do get it.
In general adding more context to your question might have helped here.
As @rajeev-k-tomy explains quite well if you do not agree with the closing there are several ways of responding to that. Also posting here is a good way to go about it.
Comment: Commenting questions on the close-queue is hell of a job. So I recommend the "SKIP" button or preferably you can choose a right option from the closing reasons!!!
Comment: Thank you for clarifying your point of view. I'm voted for you in the primary election and please, be not so strict in future :)
Comment: @SiarheyUchukhlebau Next time I will leave a comment motivating my decision, this might be more useful for someone else in the future
Comment: "Skip" should also be used more often for flags on comment  :P
Answer: Totally agree. I guess it's just because a really short questions without some code, but its clear.
But therefor read tooltips of up/downvotes and use them. If there are possible duplicates, do I quick search.
First time I saw this review today I just skipped it, because I had no time to search for duplicate. I voted to reopen too ...

Same here ... Allow edit product attributes on user permission ... first close vote was before I changed title and answered. Still no good description, but it was nearly clear what he was looking for.

Edit:
Sometime it's a split desicion ... asking for more information again and again takes time. Time that the author should have spent first. I agree with Fabian, there are too much questions with poor description/no effort ... so better flag as "too broad" or "offtopic - with comment"? Maybe it's more correct then use "unclear" flag. However ... if we are more strict at this side, "reopen" votes have to be checked more exact after edits.

Edit 2:
If you "skip" reviews, they will popup later again! So there is no need for a fast decision ...
Comment: Thank you for your answer and for another kind of question with the same problem. Based on it I updated my question, where I mentioned candidates for moderators election from the reviewers' list. It is very interesting to hear what are they thinking about it.
Answer: As @sv3n mentioned, this question is clear in my point of view. So you can do two things here.

You can reopen it. You can do this, if you have the privilege of Cast Close And Reopen Votes.
If you do not have the privilege to reopen the question or you see that the reopen request is again getting rejected, then in that case you can flag that question to the moderator with an "other" reason and state that I would like to answer this question as it seems clear for me. In this case, if the moderator feels that its a genuine reason, then he will reopen it for you.

Other than this, one thing you can do to reopen a question is just edit that question. Editing a question will put the question in reopen request queue so that the moderators can evaluate it. But the tendency which I see here is such questions will remain as closed.
Now why do this happen?
Many reasons are there. But people have a tendency to close the question if the content is very less. Some people are too lazy to read the content and judge the question with it's heading. This trend is not good for the community.
I request all my fellow community members to read the content of a question in case you are dealing close queue. If you are not sure what should do with the question or answer (it may happen), then better skip that question rather than do a false judgement.
Comment: @SiarheyUchukhlebau the thing is we are not sure the people who you quoted in your comment doing their moderation like I described above. But.. yes it would be nice if we know their view point on this.
Comment: Thank you for your answer, as you say *Some people are too lazy to read the content and judge the question with it's heading.* and there are candidates for moderators among the reviewers, so it is very interesting, what they thinking about this problem and how they can moderate this community if they are so lazy to read two-lines question?


Sincronismo de eventos em javascript

Question: Estou a trabalhar numa aplicação web que tem uma framework, esta framework foi desenvolvida em ASP.net, sendo que nela posso adicionar javascript aos ecrãs.
Num dos ecrãs adicionei uma assinatura digital, em que escreve num quadro "canvas" á medida que detecta eventos dos ratos ou do touch, de seguida guardo os dados na base de dados.
Este javascript executa um onload dentro de um onready fazendo um appendChild a um elemento do ecrã de origem. Desta forma adiciono a minha assinatura digital ao ecrã original.
A minha assinatura digital é um Canvas 2d responsivo.
Com o canvas responsivo, é necessário ter um backup do canvas sempre que este recebe alterações nas dimensões, porque sempre que as dimensões do canvas são alteradas todo o seu conteudo é limpo.
Desta forma, adicionei um evento window.onresize que desenha o meu backup no canvas, após fazer set da width e da height.
Na próxima secção desta pergunta, deixarei a negrito análises do ponto de vista do programador, em bold normal análises do ponto de vista do utilizador.
O utilizador carrega a página, são disparados onready, onload, dentro do onload adiciono elementos ao DOM
<code>var stringAssina = "<canvas id="quadro" style="display:block;overflow: hidden;width: calc(100% - 10px);height:400px;border:1px solid"></canvas>";

jQuery(document).ready(function() {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_pageLoaded(function () {

        jQuery(stringAssina).insertAfter("#ctl00_conteudo_pbDadosMB");

        // recarrega canvas com dimensões da janela
        window.onresize = function(event) {
             var quadro = document.getElementById('quadro');
             quadro.width = quadro.clientWidth;
             quadro.height = quadro.clientHeight;
             console.log('resize');
             var img = new Image;
             img.onload = function() {
             var ctx = quadro.getContext("2d");
             ctx.drawImage(img, 0, 0, quadro.clientWidth, quadro.clientHeight);
              };
              img.src = dataURL;
</code>
Neste momento o utilizador com os eventos do rato ou touch, ao tentar escrever no canvas. Estará a escrever em sitios que não correspondem ás coordenadas dos rato. Isto porque o canvas.width e canvas.height são undifined.
Para resolver este problema ainda no onload, preciso fazer set no canvas.width e canvas.height, desta forma estaremos a escrever nos sítios certos.
Por isso, ainda no onload tenho
<code>          var img = new Image;
          var quadro = document.getElementById('quadro');
                   console.log(quadro.clientWidth);
                  quadro.width = quadro.offsetWidth;
                  quadro.height = quadro.offsetHeight;
                  var img = new Image;
          img.onload = function() {
            var ctx = quadro.getContext("2d");
            ctx.drawImage(img, 0, 0, quadro.offsetWidth, quadro.offsetHeight);
          };
          img.src = dataURL;
</code>
Este código faz set das dimensões do canvas para 0. Ou seja o quadro.offsetWidth and quandro.offsetHeight são 0.
Conclusão:
O meu código funciona a partir do momento que faço um reajuste na janela.
O canvas offsetWidth and offsetHeight estão a 0.
Nota: ao código citado não foram adicionados os eventos de escrita no canvas, estes eventos existem dentro do onload.
[UPDATE - 11-06-2019 14:18]
Passei a fazer o insertAfter dentro do ready. O clientWidth e o offsetWidth do canvas, continuam a ser 0 na primeira ocorrencia do onload.
Consegui resolver indo buscar a largura do pai, no entanto eticamente não é eficiente, porque deveria ser possível buscar a largura do canvas no primeiro onload.
Answer: Para adicionares elementos ao DOM deves fazê-lo no ready, pois o onload só acontece depois de toda a DOM e conteúdo (imagens, etc.) estarem carregados. A manipulação dos elementos que adicionares deve acontecer depois de garantires que esses já existem ou em eventos seguintes, como é o caso do onload.
E atenção que poderás ter uma diferença no tamanho do canvas uma vez que estás a tentar obter duas a sua dimensão através de propriedades diferentes.

clientWidth is the inner width (ie. the space inside an element including padding but excluding borders and scrollbars)
offsetWidth is the outer width (ie. the space occupied by the element, including padding and borders)
  scrollWidth is the total width including stuff that is only visible if you scroll

Se necessário cria um JSFiddle para que te possamos ajudar melhor.
Comment: Consegui dar a volta, no onload fiz  if(!document.getElementById(mycanvas)) adiciono o canvas e faço set das dimensões do pai.
Comment: Obrigado pelo teu contributo. Na verdade melhorou o meu código, contudo o clientWidth do canvas continua a 0 no onload. Consegui resolver alternativamente, peguei no elemento pai e fui buscar o offsetWidth.
Comment: Quando inseria o elemento dinamicamente no onload(agora com a tua ajuda coloquei no onready) conseguia pegar na mesma na largura do pai, e fazer set do canvas. No entanto, alguma coisa setava ele de novo para 0.
Comment: Talvez algum conteúdo que fosse acrescentado na página fizesse os elementos ajustar as dimensões, mas é um long shot esta teoria. Ainda bem que resolveste!
Comment: Surgiram novos problemas, nesta página em que estou a adicionar elementos via javascript. existem botões que fazem executar o onload, sem executar o ready. Digo isto porque os elementos que insiro no ready, deixam de aparecer no html, ou no DOM.
Comment: Por `onload` queres dizer o `window.onload`? Não é correto teres botões a executar esse método. Consegues criar um JSFiddle com a parte do código que precisas ajuda funcional?
Comment: Estou a trabalhar numa aplicação web, tem uma área de framework para programadores que permite adicionar javascript aos ecãs. Esses botões que chamam window.onloads são de origem da aplicação web. Esta é a desvantagem de trabalhar em frameworks, o não saber o como está programado por trás da programação que está a ser feita por mim.
Comment: Se considerares que a resposta inicial foi válida para resolveres o problema marca como correta por favor

Sincronismo de eventos em javascript


Instead of Case when I need IF..Else

Question: I have a table it's called solr. using this below Scripti'm updating this into solr table.but here my doubt is instead of this i need to use If...Else condition.
I'm not getting any idea about this one. Kindly help me with on this.
UPDATE solr
SET Stock=
  CASE
    WHEN SUD.D_price='ABC'
    OR SUD.D_price  ='CDE'
    AND WIS.StockID >0
    THEN 'Y'
    WHEN SUD.Display_price='XYZ '
    OR SUD.Display_price  ='PQR'
    AND WIS.StockID       >0
    AND WI.StockName NOT LIKE '%GGR%'
    THEN 'Y'
  END
FROM InventoryItems WIS
JOIN solr SUD
ON WIS.ProductID=SUD.ProductId
JOIN WS_Inventory WI
ON WI.StockID=WIS.StockID

Comment: You can use ELSE part of CASE statement for this: CASE WHEN condition1 THEN value1 WHEN condition2 THEN value2 ... ELSE defaultvalue END
Comment: I think Case is pretty suited for this scenario.
Comment: using the above script i got my result...but i need as if(-------) -condition and else condition in oops how we are using like that.
Comment: I doubt you *need* to use IF. IF in SQL would be to run various queries or when building dynamic SQL - not as part of a single query. Check msdn documentation for the IF http://technet.microsoft.com/en-us/library/ms182717.aspx
Answer: I don't really understand your question, but I do know this... whenever you mix AND with OR in  a condition, you should use parenthesis to control the order of operations.
  CASE
    WHEN (SUD.D_price='ABC' OR SUD.D_price  ='CDE')
         AND WIS.StockID >0
    THEN 'Y'
    WHEN (SUD.Display_price='XYZ' OR SUD.Display_price ='PQR')
         AND WIS.StockID > 0
         AND WI.StockName NOT LIKE '%GGR%'
    THEN 'Y'
    ELSE -- You should probably have some value here.
  END

Comment: Good observation. With IN one could even get rid of the ORs and wouldn't need parentheses at all: `WHEN SUD.D_price IN ('ABC', 'CDE') AND WIS.StockID > 0 THEN ...`
Comment: @ThorstenKettner I agree.  In this specific situation it is possible to remove the OR condition, but that is not always the case.  Behind the scenes, the query optimizer will translate the IN condition to OR so there are no performance implications.  I chose to leave it this way because it clearly illustrates the problem and the solution, which is especially useful when you cannot combine the OR's to an IN.
Answer: You don't explain exactly what you want, but I surmise that you need an else clause.  If you want to set the value to 'N', then use:
UPDATE solr
    SET Stock = (case when SUD.D_price = 'ABC' OR SUD.D_price = 'CDE' AND WIS.StockID > 0
                      THEN 'Y'
                      WHEN SUD.Display_price='XYZ ' OR SUD.Display_price='PQR' AND WIS.StockID>0 AND WI.StockName NOT LIKE '%GGR%'
                      THEN  'Y'
                      ELSE 'N'
                 end)
   from solr SUD join
        InventoryItems WIS
        on WIS.ProductID = SUD.ProductId JOIN
        WS_Inventory WI
        ON WI.StockID = WIS.StockID;

Perhaps you want:
                      ELSE stock

This will not change the value.  You can also put conditions in the where clause to only update to Y, if that is your intention.  I don't see a need for if.
Answer: Dont know about the data at all but my guess is you nested ANDs and ORs are messing it up use paranthesis to force the order in which they are evaluated, as the default behaviour is NOT takes presedence over AND , AND takes presedence over OR.
NOT -->  AND --> OR
this can be a bit confusing if you dont pay much attention to in what order sql server is going to evaluate each expression. Using Paranthesis makes is much simpler.
UPDATE SUD
SET SUD.Stock = CASE
                    WHEN (SUD.D_price='ABC' OR SUD.D_price  ='CDE')
                             AND WIS.StockID > 0
                       THEN 'Y'
                    WHEN (SUD.Display_price='XYZ ' OR SUD.Display_price  ='PQR')
                        AND WIS.StockID > 0  AND WI.StockName NOT LIKE '%GGR%'
                       THEN 'Y'
                   --ELSE 'N'  --<-- Default value
                  END
FROM InventoryItems WIS INNER JOIN solr SUD
ON WIS.ProductID = SUD.ProductId
INNER JOIN WS_Inventory WI
ON WI.StockID = WIS.StockID

Answer: You could add ELSE..
UPDATE  solr
SET     Stock = CASE WHEN SUD.D_price = 'ABC'
                          OR SUD.D_price = 'CDE'
                          AND WIS.StockID > 0 THEN 'Y'
                     WHEN SUD.Display_price = 'XYZ '
                          OR SUD.Display_price = 'PQR'
                          AND WIS.StockID > 0
                          AND WI.StockName NOT LIKE '%GGR%' THEN 'Y'
                     ELSE 'N'
                END
FROM    InventoryItems WIS
        JOIN solr SUD ON WIS.ProductID = SUD.ProductId
        JOIN WS_Inventory WI ON WI.StockID = WIS.StockID

I've just assumed N in this case.

Instead of Case when I need IF..Else


Views PHP: how to get the `end-date` value within `Global(PHP)`?

Question: I am rewriting the output a view block with a Global(PHP) field from the module Views PHP, and one of the fields I am rewriting is a Date field.
The value for the field is : 2015 - 08:30 to 09:30
I am looping through the fields and simply printing them to see the output:
foreach ($data->field_field_item_timespot as $timeEntry) {
  $time = $timeEntry['raw']['value'];
  print $time;
}
This is the output: 2015-01-01 08:30:00
The issue that I am having is that it is only printing the start-date of the field, when I need both start-date & end-date. I am specifying the Date field to display start and end date values, and it does in the view, but not inside the Global(PHP).
Any ideas how to get the end-date value within Global(PHP)?
Answer: $time = $timeEntry['raw']['value'] == Start Date
$time = $timeEntry['raw']['value2']== End Date


Monitoring a one-off service

Question: We do not have any sort of proper server monitoring solution in place (a situation I'd like to rectify this summer), but I've got one service in particular that I'd like to monitor.  [Our current monitoring system, waiting for clients to call in with a problem, works well for widely-used systems, but this does not affect as many people, as, say, DHCP.]
I'm running All The Right Type 3 Server on (sigh) an OS X 10.3 (Panther) box [because it doesn't start itself automatically on something newer and our software procurement person really doesn't want to get updated software.]  The client software is working fine the student's machines, under OS X 10.5 (Leopard).
Now then, I occassionally get a call that this server is down [and the machine itself is still up!], and I'd really prefer to know before someone has to pick up the phone.  The process appears to be called "atrtserv.osx".  While it does use the network, I would be surprized if the documentation for it spoke of how to send a message to see if the service is up, so something gross-grained, like check every five minutes that the process exists.
Is there a simple way to monitor one service, esp. on the Mac?
Answer: Well, the real simple way probably looks like:
<code>pgrep atrtserv.osx >/dev/null || (
    date |
    mail -s 'atrtserv.osx down on yourmachine.foo' firstname.lastname@example.com
)
</code>
in a cron job running at the interval of your choice.
Answer: I don't guarantee that this code works right (most especially the line that starts with "RUNNING=", but substitute some test of your own that can return a string if it's running and no string when it isn't.
<code>#!/bin/bash

while true ; do
RUNNING=`ps aux | grep atrtserv | grep -v grep`
if [ -n "$RUNNING" ] ; then
    echo "atrtserv.osx is broken" | mail -s "atrtserv down" email@example.com
    sleep 300
else
    sleep 300
    fi
done
</code>
Edit
Use the pgrep above instead of my hack
Comment: I haven't tried it yet, but this sure looks like the right answer.  pgrep is not built-in on the Mac.
Answer: You could write a small script that runs ps, and have cron run it every 5 mins.
mail will then mail you if it finds something wrong.
Total implementation time would be able 15 minutes I think.
Answer: Try monit from darwinports.

Monitoring a one-off service