2005 BMO2 showing that at least three different sets in the list are subsets of at least four sets in X.

Question: Consider the following problem:

Let $X = \{A_1, A_2, … , A_n\}$ be a set of distinct 3-elements
subsets of $\{1,2, … ,36\}$ such that

$A_i$ and $A_j$ have non-empty intersection for every $i, j$;

The intersection of all the elements of X is the empty set.

Show that $n ≤ 100$.

How many such sets $X$ are there when $n = 100$?

From the solution, assuming that $A_1 = \{1, 2, 3\}$.
Choose $A_{i_1}$, $A_{i_2}$, $A_{i_3}$ with $1$ not in $A_{i_1}$, $2$ not in $A_{i_2}$ and $3$ not in $A_{i_3}$.
Suppose that $A_{i_1} = \{a_1, a_2, a_3\}$, $A_{i_2} = \{b_1, b_2, b_3\}$ and $A_{i_3} = \{c_1, c_2, c_3\}$.
Every set in the collection $X$ has one of the following doubleton sets as a subset:
$$\{1, a_1\}, \{1, a_2\}, \{1, a_3\}, \{2, b_1\}, \{2, b_2\}, \{2, b_3\}, \{3, c_1\}, \{3, c_2\}, \{3, c_3\},$$
and call this list of subsets $(t)$.
I don't understand the following part of the solution:
To show that at least three different sets in the list $(t)$ are subsets of at least four sets in $X$.
Suppose that at most two different sets in the list $(t)$ are subsets of at least four or more sets in $X$.
Every set in $X$ contains at least one set in list $(t)$, so the total number of sets in $X$ is at most $34\cdot2+7\cdot3=89<100=|X|$.  Therefore, there are at least three different sets $P1, P2$ and $P3$ in the list $(t)$ which are subsets of at least four sets in $X$.
Comment: 1) What do you not understand about the solution? What do you currently understand? 2) Can you link to the original writeup? It seems to be written in a slightly weird manner, so I'm wondering if this from an official solution.
Comment: As I'm reading the official solution, I don't understand the statement of "at least three different sets in the list (t) are subsets of at least four sets in X."  and the proof of it.
Comment: I understand that the result can be used to prove the cases of intersection of P1, P2 and P3 to find the final answer.
Comment: Can you link to the solution, or take a photo/screenshot of it?
Answer: This is not meant to a complete solution to the original problem.
It's my understanding/interpretation of the part of the solution that was shown.

Let's show that for all other configurations, $ n \leq 100$.
WLOG $A_1 = \{1, 2, 3 \}$.
Choose Ai1, Ai2, Ai3 with 1 not in Ai, 2 not in Ai2 and 3 not in Ai3.
Suppose that Ai1 = {a1, a2, a3}, Ai2 = {b1, b2, b3} and Ai3 = {c1, c2, c3}.
Every set in the collection X has at least one of the following doubleton sets as a subset: {1, a1}, {1, a2}, {1, a3}, {2, b1}, {2, b2}, {2, b3}, {3, c1}, {3, c2}, {3, c3} -----(t)
A pair may appear at most twice in this list.
For each of the 9 (not necessarily distinct) pairs $\{x,y\}$, let $T_{x,y }$ be the number of triples $A_i$ for which $\{x,y\}$ is a subset.
Claim: If $T_{x,y} < 4$  for at most 2 pairs of (t), then $ n \leq 100$.
Proof: Since each triple of X contains at least one of these subsets of (t), we can bound $n \leq \sum T_{x,y}$.
For the 2 pairs of (t) with $ T_{x,y} \geq 4$, they are contained in at most 34 triples of the form $\{x, y, z\}$.
For the other 7 pairs of (t) with $T_{x,y} < 4$, by definition, they are contained in at most 3 triples.
Thus, we have  $ n \leq 2 \times 34 + 7 \times 3 = 89 $ triples.
Corollary: If $n \geq 90$, then we must have $T_{x,y} \geq 4$ for at least 3 pairs of (t).
(I've not thought about how to continue form here.)

Note: Ideally this is stated at the start of the solution, to provide some motivation for how the thought process.
We provide an example where $ n = 100$ is possible.
Take $ \{1, 2, 3 \}, \{1, 2, 4 \}, \{1, 3, 4 \}, \{2,3, 4 \}, \{ 1, x, y\}$ where $ x \in \{2, 3, 4 \}$, $y \in \{5, 6, \ldots \}$.
this gives $ 4 + 3 \times 32 = 100$ sets that fulfill the conditions of the problem.
Following the above approach, the first 4 sets correspond to $A_1, A_{i3}, A_{i2}, A_{i1}$.
The collection (t) is $ \{ 1, 2 \} \times 2, \{1, 3 \} \times 2, \{1, 4 \} \times 2, \{2, 3\}, \{2, 4\}, \{3, 4\}$.


Matlab: Publish function runs endless loop

Question: I've created an .m file that pulls and sorts data into a UI table, then I have the ability to publish this to either html or pdf form. I can click in the GUI of matlab publish button and it perfectly prints the table once to publication, but if i insert:
publish('MTRChecks.m','html');
at the end of the code, then the program will loop endlessly regenerating the same table without publishing it.
I am using Matlab 2013 B, while not ideal it is my only option.
Comment: Welcome! This is probably not enough code to tell what is going on. Can you make a small sample that exhibits the problem?
Answer: Have a look here, you are most probably using the publish call in the wrong way, as publish function call takes care of running the script provided as the first argument, adding the call at the bottom of the script would lead such an infinite call.
Comment: If you find that a question is a duplicate of another question, flag it as duplicate. That is much more helpful than linking the duplicate question into an answer. Thanks!


Marginalizing over a Chinese Restaurant Process prior

Question: I am reading a paper by Kemp et al. and there is a part about marginalising over a Chinese Restaurant Process and I am quite clueless about how could one marginalise over such a prior! The details of the model can also be seen in the following lines of the paper:

According to Wiki the CRP has the following probability over the partitions:
$$\Pr(B_n = B) = \dfrac{\prod_{b\in B} (|b| -1)!}{n!}$$
Should I consider that this is the prior and consider that in the marginalising any $P(y|z)$ where $z$ has more elements than number of observations is zero in marginalising?
Answer: I just read the Appendix, but I would say that:

Forget about this formula you found in Wikipedia. You want to access to $p(\mathbf{z})$ by using $p(z_i)$, which has the classic form Kemp provided in the Appendix (the one that says that the probability of sitting in a existing table is proportional to the number of people in the table, and the probability of opening a new table is proportional to $\gamma$ (by the way, usually denoted as $\alpha$)).
If you need to take samples from $p(\mathbf{z})$, you sample from $z_1$, $z_2$.. one at a time. Every time you sample $z_i$ you consider the others have the values of their last samples.

Since know you know how to take $N$ samples from $p(\mathbf{z})$, and you know how to get, or how to sample from, $p(y | \mathbf{z})$, then you can multiply every pair of samples $p(y^{(s)} | \mathbf{z}^{(s)}) p(\mathbf{z}^{(s)})$ to get a new sample from the posterior $\mathbf{z}^{(s)} | y$.
And from this posterior, you can multiply each sample by $p(\theta^{(s)} | y^{(s)}, z^{(s)})$
I didn't get the notation $y'$ and why it does not depend on $z$, though. But I hope it gives you some intuition. The main idea is to do the integrals by using Monte Carlo.
So, the short answer to your question is: you don' really marginalize over a CRP, you sample from it and use these samples to compute the things that depend on $\mathbf{z}$.
Even shorter:
$$
p(y) = \int p(y | z) p(z) \text{d}z \approx \frac{1}{N}\sum_{s=1}^Np(y |z^{(s)})
$$


How to use Azure application insights metrics separately for each web test in .Net

Question: I want to use metrics from app insights separately for web test wise instead of average from all the web tests
Comment: And the question is?
Comment: It is ask regarding exporting metrics data into .Net Application
Answer: You can achieve this with Analytics. For instance, with this query:
<code>availabilityResults
| where timestamp > ago(1d)
| summarize avg(duration) by bin(timestamp, 10m), name
| render timechart
</code>
Comment: Thanks @ZakiMa , is there any API to fetch all these results seperately for web tests..from https://dev.applicationinsights.io/apiexplorer/metrics we are  getting output as average of all web tests


Is the framework within the framework a problem?

Question: I used pods in the Cocoa framework.
Is there a problem when you include this project in your main project and upload it to the App Store? What is the reason for rejection?
<code>pod 'SnapKit'
pod 'GzipSwift'
pod 'RealmSwift'
</code>
Answer: I have an app in appstore which includes a framework and that framework includes many frameworks in it and it's approved by apple.
I think in your case , you might be using a framework which tries to access Private APIs of iOS.
Hope this helps.
Include apple's rejection message to give you more insights.


Calcular distancias entre duas coordenadas

Question:
Estou usando essa função abaixo para calcular a diferença entre duas coordenadas. Atraves do google maps é informado uma diferença de uns 2 a 3km. Mas a função está me retornando o resultado 56.480188542761 Km.
Gostaria de saber se tem algo errado na função ou se existe mais algum calculo a ser feito.
function distancia($lat1, $lon1, $lat2, $lon2, $unit) {

    $theta = $lon1 - $lon2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $unit = strtoupper($unit);

    if ($unit == "K") {
        return ($miles * 1.609344);
    } else if ($unit == "N") {
        return ($miles * 0.8684);
    } else {
        return $miles;
    }
}

// -12.971683, -38.460108 = bairro pernambues em salvador
// -12.981290, -38.465043 = shopping iguatemi em salvador
echo distancia(-12.971683, -38.460108, -12.981290, -38.981290, "k") . " Km
";

Comment: Só pra mim entender melhor, K = kilometro, e o N?
Comment: 2 respostas com valores diferentes de resultado, cuidado para não fazer asneira.
Comment: O N é para milhas náuticas (dado o factor de conversão usado).
Comment: Quem sabe!?  :)  Esquece o N. Precisarei apenas de quilometros.
Comment: Outra coisa @RafaelSoufraz, a distância que o google maps informa, considera as ruas a trafegar, e quando você utiliza a fórmula de Haversine, ela calcula a distância em linha reta.
Comment: Eu sei disso. Mas ainda assim não justifica o resultado da função. 56.480188542761 Km
Comment: Tenta com a resposta que coloquei.
Answer: Fórmula de Haversine aplicada em PHP
function distancia($lat1, $lon1, $lat2, $lon2) {

$lat1 = deg2rad($lat1);
$lat2 = deg2rad($lat2);
$lon1 = deg2rad($lon1);
$lon2 = deg2rad($lon2);

$dist = (6371 * acos( cos( $lat1 ) * cos( $lat2 ) * cos( $lon2 - $lon1 ) + sin( $lat1 ) * sin($lat2) ) );
$dist = number_format($dist, 2, '.', '');
return $dist;
}

echo distancia(-12.9813346,-38.4653612, -12.9741491,-38.4696483) . " Km
";

// 0.92 Km

Ou assim, verificando o Delta.
function distancia($lat1, $lon1, $lat2, $lon2) {

$lat1 = deg2rad($lat1);
$lat2 = deg2rad($lat2);
$lon1 = deg2rad($lon1);
$lon2 = deg2rad($lon2);

$latD = $lat2 - $lat1;
$lonD = $lon2 - $lon1;

$dist = 2 * asin(sqrt(pow(sin($latD / 2), 2) +
cos($lat1) * cos($lat2) * pow(sin($lonD / 2), 2)));
$dist = $dist * 6371;
return number_format($dist, 2, '.', '');
}

echo distancia(-12.9813346,-38.4653612, -12.9741491,-38.4696483) . " Km
";

// 0.92 Km

Comment: Eu utilizei esta mesma fórmula, para encontrar os pontos mais próximos em linha reta, dentro de um cadastro de cidades, e após isto, traçar a distãncia das rotas das cidades mais próximas, já com coordenadas estabelecidas com a API do googleMaps.
Dá uma olhada: https://gist.github.com/aymone/00c4e4e8be907bdedda7
Answer: Seguindo Haversine do wikipedia
<?php

function distancia($lat1, $lon1, $lat2, $lon2) {
$lat = deg2rad($lat2-$lat1);
$lon = deg2rad($lon2-$lon1);
$t = sin($lat/2) * sin($lat/2) + cos(deg2rad(lat1)) * cos(deg2rad($lat2)) *sin(lon/2) * sin(lon/2);
$l = 2 * atan2(sqrt($t), sqrt(1-$t));
$result = 6371 * $l;
return $result;
}

echo distancia(-12.9813346,-38.4653612, -12.9741491,-38.4696483) . " Km";

?>

Resultado aqui foi 0.798991145405 Km
Comment: Porque retirou o seu resultado?
Comment: Então, a fórmula original é em graus, então não faz sentido calcular o delta em radianos, pelo menos entendo desta forma, posso estar errado.
Answer: Para se calcular a distancia entre dois pontos,use a seguinte formula:
Raiz quadrada de: ( Xa - Xb )^2 + ( Ya - Yb )^2
Exemplo
12, 14 é a coordenada A.
4, 3 é a coordenada B.
O primeiro valor da coordenada equivale a X e o segundo a Y,portanto:
`(Xa-Xb)^2+(Ya-Yb)^2` = `(12-4)^2+(14-3)^2`

= `(8)^2+(11)^2`

= `(8)^2+(11)^2`

= `64+121`

A distancia entre A e B é a raiz quadrada de 185 ou ~13,6
Leia http://www.brasilescola.com/matematica/distancia-entre-dois-pontos.htm
Comment: Isso num plano, mas a Terra é esférica (ou quase esférica).
Comment: Obrigado. Me explicou como calcular mas o calculo já está sendo feito. Só preciso entender o resultado final e ou converte-lo.
Comment: É,eu não havia notado,só me toquei com o comentário do Marcelo sobre a Fórmula de Haversine.


similar to excel vlookup

Question: Hi
i have a 10 year, 5 minutes resolution data set of dust concentration
and i have seperetly a 15 year data set with a day resolution of the synoptic clasification
how can i combine these two datasets they are not the same length or resolution
here is a sample of the data
> head(synoptic)
        date synoptic
1 01/01/1995        8
2 02/01/1995        7
3 03/01/1995        7
4 04/01/1995       20
5 05/01/1995        1
6 06/01/1995        1
>
head(beit.shemesh)
  X........................ StWd  SHT PRE  GSR RH Temp  WD  WS PM10  CO   O3
1                        NA   64 19.8   0 -2.9 37 15.2  61 2.2  241 0.9 40.6
2                        NA   37 20.1   0  1.1 38 15.2 344 2.1  241 0.9 40.3
3                        NA   36 20.2   0  0.7 39 15.1  32 1.9  241 0.9 39.4
4                        NA   52 20.1   0  0.9 40 14.9  20 2.1  241 0.9 38.7
5                        NA   42 19.0   0  0.9 40 14.6  11 2.0  241 0.9 38.7
6                        NA   75 19.9   0  0.2 40 14.5 341 1.3  241 0.9 39.1
  No2 Nox  No SO2                       date
1 1.4 2.9 1.5 1.6  31/12/2000 24:00
2 1.7 3.1 1.4 0.9  01/01/2001 00:05
3 2.1 3.5 1.4 1.2  01/01/2001 00:10
4 2.7 4.2 1.5 1.3  01/01/2001 00:15
5 2.3 3.8 1.5 1.4  01/01/2001 00:20
6 2.8 4.3 1.5 1.3  01/01/2001 00:25

any idea's
Comment: Related question : http://stackoverflow.com/questions/5465383/merging-aggregate-data-in-r/5465638#5465638
Comment: Joris has answered your question so I deleted by answer, but the following recommendations on how to help us help you merit sticking around.

It is unclear from your question:

 1. What information is in common between the two datasets that you want to combine them on
 2. What you want your final output to look like
 3. How to create a replication dataset that people can test (please use dput for this)
Answer: Make an extra column for calculating the dates, and then merge. To do this, you have to generate a variable in each dataframe bearing the same name, hence you first need some renaming. Also make sure that the merge column you use has the same type in both dataframes :
beit.shemesh$datetime <- beit.shemesh$date
beit.shemesh$date <- as.Date(beith.shemesh$datetime,format="%d/%m/%Y")
synoptic$date <- as.Date(synoptic$date,format="%d/%m/%Y")
merge(synoptic, beit.shemesh,by="date",all.y=TRUE)

Using all.y=TRUE keeps the beit.shemesh dataset intact. If you also want empty rows for all non-matching rows in synoptic, you could use all=TRUE instead.

similar to excel vlookup


xampp mac os x "this application requires admin privileges"

Question: When I try to start xampp (manager-osx) on Mac OS X Yosemeti 10.10,
I get this error :

this application requires admin privileges

It doesn't ask any password like it used to.
Comment: This question is off-topic. It isn't a programming question.
Answer: I find the solution:
for some reason, owner has been changed. I changed it back to root, and now it works again :
$ cd /Applications/XAMPP/xamppfiles
$ sudo chown -R root manager-osx.app

Then input your system password when requested and press enter.
Comment: This happened to me as well... had to do sudo on the chown command... the bigger question is... why did this ownership change occur?
Comment: For others who are wondering why this solution did not work for them , Make sure you are navigating to xamppfiles folder not stopping on XAMPP
Answer: It works with this
$ cd /Applications/XAMPP/xamppfiles
$ sudo chown -R root manager-osx.app
Answer: Neither of the suggestions by @sonique or @ishaalans worked in my case:

Right click to open application package contents (logged in as an admin)
Find the executable file of the app in question
Type sudo into Terminal
Drag and drop the executable on the Terminal cursor after sudo and it will populate the file path
Click enter and enter admin password
Voila! It opened immediately for me and should for you if all else fails


Is this the correct way of iterating through users and check if they have a determined permission?

Question: I'm developing a module where I need to retrieve all users of a website and check if they have a specific permission.
<?php
$reviewers = array();

$result = db_query('SELECT uid, name FROM {users} ORDER BY uid');

while ($record = db_fetch_object($result)) {

    if ($record->uid != 0) {
        if (user_access('review article', user_load($record->uid), TRUE)) {

            $reviewers[$record->uid] = (string) $record->name . '@domain.com';

        }
    }
}

I'm using this code and it works but it can become quite slow. I've tested in a site with 5.000 bogus users and it takes about 30 secs to complete.
Answer: That code works, but as you found out, it needs to load each user completely and is therefore very slow.
Unfortunately, the database schema of permissions/roles in D6 is really crappy. It stores all permissions of a role in a single role, separated with a comma.
But still, it should be possible to query that information directly. What you want to query is  which roles have a specific permission and then which users that have at least one of these roles.
Something like this:
db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid INNER JOIN {permission} p ON p.rid = ur.rid WHERE p.perm LIKE '%s'", '%, $permission_name_here,%');

There are a few special cases where this doesn't work/needs additional checks:

uid 1 does have all permissions
all users automatically have the authenticated user role (rid 2) but that is not stored in the users_roles table. So if a permission could possibly be assigned to that role, then you need to explicitly check that and if yes, return all users.
It is possible to dynamically assign roles to users based on some conditions. In this case, the query won't work for that...


How can I remove last dot (period) from a string in bash

Question: In a bash file I get an input argument $1. It may contains a dot at its end or not like (test. or test)
I would like to have test in both cases to add an extension to it and create for example test.py from it
Comment: Okay, the questions are similar, however its hard to find ending with slash when you search for ending with DOT. But why downvote?!!
Answer: Parameter expansion has an operator % to trim characters from the end of an expansion.
$ set test.
$ echo "$1"
test.
$ echo "${1%.}"
test

If there is no trailing dot, the expansion is left unchanged:
$ set test
$ echo "${1%.}"
test

Answer: you can use parameter expansions like this :
yourVar=${1/.}
echo $yourVar

Result :
$ ./test.sh "test."
> test
$ ./test.sh "test"
> test

Comment: assuming input could have multiple periods this appears to remove just the first period, eg: `set test.1.2.3.. ; echo ${1/.}` => `test1.2.3..`


Cannot connect colab to my google drive as it doesn't appear when searching

Question: From my google drive, I'm trying to connect google colab to my google drive without success.
Please, find below the steps that I took:

more
connect more apps
typed 'colab' in the search bar and I didn't find the app.

Thank you in advance for helping me out.

While in Drive, click on New button (marked with a + New) on left-hand side and select More > Connect more apps

Then, by using the magnifying glass icon to "Search apps" and typing in colab, it returns no results
Answer: You are trying in correct direction, but Google has removed that option from Google Drive, you have to go via Google Colab itself, and save to Colab Notebooks Folder.
From there you can open them into Google colab, but creating new notebooks directly from Google Drive is not available as it used to be in past few years
Answer: Step 1:
Sign into the site thru the link https://colab.research.google.com.
From there, there will be a Google Drive tab with the ability to create new notebooks.

Step 2:
Then, next to the notebook, to the direct right of the Last opened column there is a small folder icon and clicking on that will bring you to your Google drive folder called My Drive > Colab Notebooks


gradient ascent vs gradient descent update rule

Question: I'm trying to understand the differences between the update rule for stochastic gradient ascent and descent. I've read some articles and still don't understand how to calculate the update rule:
Gradient Descent:
$\frac{∂NLL(θ)}{∂θ_j} = (hθ(x(i))-y(i))x(i)$
So the update rule uses a minus sign because we want to minimize the log-likelihood:
$θ_j:= θ_j−α(\frac{∂NLL(θ)}{∂θ_j}) = θ_j−α[(hθ(x(i))-y(i))x(i)]$
Gradient Ascent:
$\frac{∂LL(θ)}{∂θ_j} =(y(i) - hθ(x(i)))x(i)$
So the update rule uses a minus sign because we want to maximize the log-likelihood:
$θ_j:= θ_j+α(\frac{∂LL(θ)}{∂θ_j}) = θ_j+α[(hθ(x(i))-y(i))x(i)]$
Now, if I take the -1 from the derivative of the NLL I end up with the same equation as for the update rule for the gradient ascent:
$θ_j:= θ_j−α(\frac{∂NLL(θ)}{∂θ_j}) = θ_j−α(-1)[(-hθ(x(i))+y(i))x(i)] = θ_j+α[(y(i)-hθ(x(i)))x(i)]$
So, I know I'm wrong as they shouldn't be the same right? I'll appreciate your help understanding this.
Answer: You used $- \alpha (-1)$. You need to pick one, either you use $- \alpha$ or $+ \alpha(-1)$.

So, I know I'm wrong as they shouldn't be the same right?

They should be the same. Maximizing function $f$ is the same as minimizing $-f$. Gradient ascent of $f$ is the same as gradient descent of $-f$.
Comment: ok, so for the update rule in gradient descent I have to use either $−α(\frac{∂LL(θ)}{∂θ_j})$ or $+α(\frac{∂NLL(θ)}{∂θ_j}) $ right?
Comment: @CrisTina maximizing a function $f$ is the same as minimizing $-f$.


Move a web app project from eclipse to tomcat standalone

Question: Can you help please me with deploy an web app from eclipse to tomcat standalone
I have a web app run on context path "localhost:8080" and all request will go through a Main Filter like that
@WebFilter("/*")
public class MainFilter implements Filter {

    /**
     * Default constructor.
     */
    public MainFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;

        String path = req.getRequestURI();
        request.setAttribute("uri", path);

        if( path.contains("/user")){
            if( path.contains("/post")){
                if( path.contains("/comment")){
                    req.getRequestDispatcher("/CommentServlet").forward(request, response);
                    return;
                }
                req.getRequestDispatcher("/PostServlet").forward(request, response);
                return;
            }

Could you tell me how to I can deploy it on tomcat with anything relate like create web.xml or config anything. Please help me here !
Comment: are you using maven?
Comment: @user1136403 I heard it before but I don't for sure. I you tomcat plugin on eclipse
Answer: If you are not using maven, generate your projects war file and then go to your webapp directory which is under the tomcat folder. It might be something like that if you are using windows C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps copy war file here. Then under the bin\ start your tomcat with startup.bat. This is old school method without maven. Take a look and research about maven.
Comment: yes ! I did that too but it just not go through the Filter ex: when I enter localhost:8080/blog/welcome.html it will run but if the url not match any file it will 404? can you tell me more details
Answer: yes I'm done ! just post here for if other people look at
I was add a web.xml file like that

http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<filter>
    <filter-name>MainFilter</filter-name>
    <filter-class>MainFilter</filter-class>
    <init-param>
        <param-name>sleep-time-in-seconds</param-name>
        <param-value>10</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>MainFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
    <welcome-file>welcome.html</welcome-file>
</welcome-file-list>

And export my web to war file in webapps folder and change to ROOT.war
notice : my MainFilter in default package


Why Go cqlsh can't get a token while keeps running requests good?

Question: My service runs in AWS cluster and uses Keyspaces. The service has a role and gets, AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID, AWS_SESSION_TOKEN, AWS_SECURITY_TOKEN env vars.
To connect Keyspaces I do the following:

import (
    "context"
    "time"

    credentialsV1 "github.com/aws/aws-sdk-go/aws/credentials"
    ec2rolecredsV1 "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
    ec2metadataV1 "github.com/aws/aws-sdk-go/aws/ec2metadata"
    aws_sess "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin/sigv4"
    "github.com/gocql/gocql"
)

type Repository struct {
    session *gocql.Session
    ...
}

func (r *Repository) ConnectCassandra(ctx context.Context) {
    awsSession, err := aws_sess.NewSession()

    creds := credentialsV1.NewChainCredentials(
        []credentialsV1.Provider{
            &credentialsV1.EnvProvider{},
            &ec2rolecredsV1.EC2RoleProvider{
                Client: ec2metadataV1.New(awsSession),
            },
        },
    )

    value, err := creds.Get()

    auth := sigv4.NewAwsAuthenticator()
    auth.SessionToken = value.SessionToken
    auth.AccessKeyId = value.AccessKeyID
    auth.SecretAccessKey = value.SecretAccessKey

    cluster := gocql.NewCluster(Host)

    cluster.Timeout = 10 * time.Second
    cluster.ConnectTimeout = 10 * time.Second
    cluster.Consistency = gocql.LocalQuorum
    cluster.Keyspace = Keyspace
    cluster.Port = Port

    cluster.Authenticator = auth

    r.session, err = cluster.CreateSession()

}

func (r *Repository) GetData() (*Data, error) {
    iter := r.session.Query(...)

    scanner := iter.Scanner()

    for scanner.Next() {
        ...
    }
}

The service periodically requests some data. After some time (~24h) I start getting errors:
2022/02/10 20:29:50 error: failed to connect to XX.XX.XX.XX:9142 due to error: Authentication failure: Session token expired at Wed Feb 09 10:11:42 UTC 2022

Meanwhile requests are running with no errors. Obviously that means that finally gocql driver retrieves a token. But why I get these errors and what's done wrong? What should I change to stop getting and to be sure that everything works as it should?
Answer: A SessionToken is a temporary credential that is retrieved using your AccessKeyId and SecretAccessKey. Session Tokens have an expiration, and are only valid for a period of time.
When it expires, any AWS API call made using that token will return that expiration error you are getting. There are a couple of ways to handle this, but effectively you want to 'refresh' the creds you are using by retrieving a new token, and retrying failed calls.
Looking at your code, you may want to define a cred refresh method on your Repository struct that can be called to get new creds again when that specific error is hit, and retry the failed call.
Can read more here: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html
Comment: Do I need to recreate gocql session after creds update?


SQL join: selecting last records from duplicates

Question: I am working on python project "Linux Server Monitor". When you load monitoring website you create your servers and table look like this:
Servers:
<code>+-----------+-----------+---------+-------------+
| server_id | auth_code | user_id | server_name |
+-----------+-----------+---------+-------------+
|         0 | xyz123    |       1 | My Server 1 |
|         1 | aabb      |      45 | BlaBlaUser  |
|         2 | asdfh1    |       1 | My Server 5 |
+-----------+-----------+---------+-------------+
</code>
After the server is created, you start python script and it starts to upload monitoring data to this table (where all data is stored, from all users):
Monitoring Data:
<code>+----+-----------+---------+---------+------------+-----------------+------------------+
| id | auth_code | user_id | os_name | os_version |   external_ip   | some_other_table |
+----+-----------+---------+---------+------------+-----------------+------------------+
|  0 | aabb      |      45 | Ubuntu  |      16.04 |    188.8.131.52 | dynamic data     |
|  1 | aabb      |      45 | Ubuntu  |      16.04 |    18.104.22.168 | dynamic data 2   |
|  2 | aabb      |      45 | Ubuntu  |      16.04 |     10.10.10.10 | dynamic data 3   |
|  3 | xyz123    |       1 | Fedora  |         27 |     188.8.131.52 | different data 1 |
|  4 | xyz123    |       1 | Fedora  |         27 |     184.108.40.206 | different data 2 |
|  5 | xyz123    |       1 | Fedora  |         27 |     184.108.40.206 | different data 3 |***
|  6 | asdfh1    |       1 | CentOS  |          7 |         18.104.22.168 |  some new data 1 |
|  7 | asdfh1    |       1 | CentOS  |          7 |         18.104.22.168 |  some new data 2 |
|  8 | asdfh1    |       1 | CentOS  |          7 |         184.108.40.206 |  some new data 3 |###
+----+-----------+---------+---------+------------+-----------------+------------------+
</code>
I want to join first and second table to show user "important" information like this:
Your Active Servers:
<code>+-----------+-------------+---------+------------+-----------------+
| server_id | server_name | os_name | os_version |   external_ip   |
+-----------+-------------+---------+------------+-----------------+
|         0 | My Server 1 | Fedora  |         27 |     126.96.36.199 |***
|         2 | My Server 5 | CentOS  |          7 |         188.8.131.52 |###
+-----------+-------------+---------+------------+-----------------+
</code>
If I join first and second table by user_id it will load duplicates too but I want only last inserted record of that particular user's server. In this case on last record "external_ip" of one server changed but other one remained the same (marked with *** and ###).
Answer: you could use an inner  join on subselect for the max id for user, server on monitorig
<code>  select s.server_id, s.server_name, m.os_name, m.os_version, m.external_ip
  from servers s
  inner join Monitoring  m  on m.user_id = s.user_id  and s.auth_code = m.auth_code
  inner  join (
    select max(id) max_id,  user_id, os_name, os_version
    from Monitoring
    group by  user_id, os_name, os_version
  ) t  on t.max_id =  m.id
  where user_id = 1
</code>
Comment: On last line it throws "clause is ambiguous" so i added s.user_id = 1 and it worked but it "clone" servers. You can see in output: https://i.imgur.com/74oxIqG.png

And here is output that is correct without cloning:https://i.imgur.com/frgogAI.png
Comment: asnwer  updated .. add the the condition for auth code  too


Menu of canvas Ajuda

Question: Eai galera , tenho um menu aqui que ao clicar ne um ícone ele aparece.
como faço p/ quando o usuário entrar na página ele ja exibir o menu ?
Grato :D
Index ->

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Off-Canvas Menu Effects - Side Slide</title>
    <meta name="description" content="Modern effects and styles for off-canvas navigation with CSS transitions and SVG animations using Snap.svg" />
    <meta name="keywords" content="sidebar, off-canvas, menu, navigation, effect, inspiration, css transition, SVG, morphing, animation" />
    <meta name="author" content="Codrops" />
    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" type="text/css" href="css/normalize.css" />
    <link rel="stylesheet" type="text/css" href="css/demo.css" />
    <link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.2.0/css/font-awesome.min.css" />
    <link rel="stylesheet" type="text/css" href="css/menu_sideslide.css" />

             <?php echo $nome; ?>

                     <?php echo $saldo; ?>

                    Extratos
                    Rede Credenciada
                    Sair

            <button class="close-button" id="close-button">Close Menu</button>

        <button class="menu-button" id="open-button">Open Menu</button>

JS's
(function() {
    var bodyEl = document.body,
        content = document.querySelector( '.content-wrap' ),
        openbtn = document.getElementById( 'open-button' ),
        closebtn = document.getElementById( 'close-button' ),
        isOpen = false;
    function init() {
        initEvents();
    }
    function initEvents() {
        openbtn.addEventListener( 'click', toggleMenu );
        if( closebtn ) {
            closebtn.addEventListener( 'click', toggleMenu );
        }

        // close the menu element if the target it´s not the menu element or one of its descendants..
        content.addEventListener( 'click', function(ev) {
            var target = ev.target;
            if( isOpen && target !== openbtn ) {
                toggleMenu();
        }
    } );
}

function toggleMenu() {
    if( isOpen ) {
        classie.remove( bodyEl, 'show-menu' );
    }
    else {
        classie.add( bodyEl, 'show-menu' );
    }
    isOpen = !isOpen;
}

init();

})();

Comment: window.onload("#classname"); Adiciona isso no javascript
Answer: Basta chamar toggleMenu quando a página for carregada.
Observação: a função init deveria ser executada quando a página fosse carregada também, pois dependendo da posição do seu elemento script, os eventos podem não ser adicionadas aos elementos na sua página. Se o script é declarado no fim da tag body na página, então está tudo bem.
(function() {

    var r = (window["requestAnimationFrame"] ||
             window["webkitRequestAnimationFrame"] ||
             window["mozRequestAnimationFrame"] ||
             window["msRequestAnimationFrame"] ||
             function(b) { setTimeout(b, 16) });

    (function c() {
        // Checa se a página foi carregada
        if(document["readyState"] === "complete")
            // Faz qualquer coisa...
            init(), toggleMenu();
        // Se não, então checa novamente
        else r(c);
    })();

})();

Menu of canvas Ajuda


Calculate the average rate of an investment with periodic deposits

Question: Let's say I make an investment with monthly deposits of 100€ (starts from 0 and add 100 every month).
After 10 years my account have 16.000€ (120 deposits of 100€).
How could I calculate the yearly average rate of this investment over the 10 years?
The interests are payed at the end of the year, and I would like to take into account the compound interests.
I have the following formula but I don't manage to isolate the rate:
$Ac = De * ( \frac{(1 + Ra)^{n+1} - 1}{Ra} - 1 )$
Ac: amount of money at the end (after the 10 years = 16.000)
De: amount of a deposit (100)
Ra: monthly rate
n: number of deposits (120)
Comment: Sorry, it was typo in my previous comment $161*Ra+1=(1+Ra)^{121}$. [WolframAlpha](https://www.wolframalpha.com/input/?i=solve+161x%2B1%3D(1%2Bx)%5E121) result is $0.00456063$ monthly or  $=5.472756\%$ yearly interest.
Comment: Do you make the deposits at the beginning of the month and withdraw at the end of month $120$ so the last deposit earns one month interest?
Comment: How did you get this formula?
Comment: @yW0K5o I found the formula on this web site : https://www.cbanque.com/placement/versement_periodique.php
Comment: @Nicolas, I take a look at the website. They explain in reverse, i.e. yearly return rate is known. Here's what I understand about your question. You need to find the yearly return rate base on the total value after 10 years, do you?
Comment: I verified the formula. It is correct. So solve it $\frac{7}{3}=\frac{(1+Ra)^{121}-1}{Ra}$ for $Ra$ (monthly interest) and convert it to yearly interest.
Comment: @yW0K5o thanks for your comment I didn't know the WolframAlpha website.
Answer: For your specific case, as yW0K5o wrote in comment, you need to find the zero of function
$$f(x)=161\,x+1-(1+x)^{121}\qquad \text{where} \qquad x=Ra$$ and for that, as already said, you need some numerical method.
You can have reasonable estimates considering that $x \ll1$. For example, using the binomial expansion or Taylor series, you would get
$$f(x)=40 x-7260 x^2-287980 x^3+O\left(x^4\right)$$ which reduces to a quadratic equation; its positive solution is
$$x=\frac{\sqrt{2041}-33}{2618}\approx 0.00465142$$ corresponding to $5.582$% which is not too bad compared to the exact solution.
Sooner or later, you will learn than, better than with Taylor series, functions can be approximated using Padé approximants. A rather simple one could be
$$f(x)=\frac{40 x-\frac{11642740 }{1327} x^2} {1-\frac{50218 }{1327}x+\frac{878339 }{2654}x^2 }$$ leading to
$$x=\frac{2654}{582137}\approx 0.00455906$$ corresponding to $5.471$% which is much better.
For an exact solution, Newton method would be easy. Considering the first two terms of the Taylor expansion, let us start using $x_0=\frac{40}{7260}=\frac{2}{363}$.
The iterates would be
$$\left(
\begin{array}{cc}
 n & x_n \\
 0 & 0.0055096419 \\
 1 & 0.0047266909 \\
 2 & 0.0045673223 \\
 3 & 0.0045606399 \\
 4 & 0.0045606282
\end{array}
\right)$$
Comment: @yW0K5o. In this case, it is just the binomial expansion limited to third order. Don't worry : you will learn very soon about them and I am sure that you will enjoy them. I felt in love with them 61 years ago and I use them almost every day.
Comment: Thank you for mentioning my idea in your post. Could you tell in more details how to use Taylor series and Newton method?
Comment: @yW0K5o. To me, quoting you is normal since I started from your comment. Could you clarify your request ? Do you already about Taylor series or not ? What about numerical methods for finding the zero of a function ? I am totally ready for any discussion around these topics.
Comment: How you get to $f(x)=40x−7260x^2−287980x^3+O(x^4)$ by using Taylor series. I am  not familiar with Taylor series.
Comment: @ClaudeLeibovici, thanks for your interesting solutions! Could you explain how you calculated the iterances $x^n$ with the Newton method?
Comment: @Nicolas. The usual formula  $$x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}$$ Select $x_0$ and run.
Comment: @ClaudeLeibovici, I try to get $x_1$ : $x_1 = x_0 - \frac{f(x_0)}{f'(x_0)} = \frac{2}{363}-\frac{0.057121}{-72,956} = 0.00629$
With :
$x_0 = \frac{2}{363}$
$f(x_0) = -(\frac{2}{363}+1)^{121}+161*\frac{2}{363}+1 = 0.057121$
$f'(x_0) = -121*(x_0+1)^{120}+161 = -121*(\frac{2}{363}+1)^{120}+161 = -72,956$
Comment: @Nicolas. A small sign mistake $$x_1 = x_0 - \frac{f(x_0)}{f'(x_0)} = \frac{2}{363}-\frac{\color{red}{-}0.057121}{-72.956} =0.00472669$$ $f(x_0)=-0.057121$
Comment: @ClaudeLeibovici, thanks for your correction!
Answer: You can't isolate the rate algebraically.  You need a numerical approximation.  Spreadsheets have an IRR (internal rate of return) function, or you can make a table that assumes an interest rate and computes the final balance.  Then use Goal Seek to adjust the interest rate to make the final balance correct.  If you have all positive inflows and one withdrawal at the end there will be only one interest rate that works.  If you have a mix of inflows and outflows along the way there can be more than one.
Assuming deposits at the beginning of the month and withdrawal at the end, so the last deposit earns one month interest, I find an annual interest rate of about $5.473\%$ works.
Comment: Thanks for your answer, I hoped there was a formula to calculate it.
I will try as you suggest with a table, but that seems fastidious and not very accurate.
Comment: If you are using a numerical method that needs a starting value, you can just do simple interest.  Here you have on average $6000$ on deposit for $10$ years and earned $4000$.  The rate would be $\frac {4000}{6000\cdot 10}\frac 1{15}\approx 6.6667\%$.  The actual rate will be somewhat smaller due to compounding
Comment: @RossMillikan, it look like I get the same result: **5.472756%**


Vertical centering with `position: relative` and `top: 50%`

Question: I'm trying to vertically center the .spinner element in the following markup (fiddle):

row 1 cell 1	row 1 cell 2

row 2 cell 1	row 2 cell 2

row 3 cell 1	row 3 cell 2

With the following styling:
.spinner {
    position: relative;
    top: 50%;
    left: 50%;
    height: 3px;
    width: 3px;
    background-color: red;
}

If I set the .spinner top property to some pixel value, the browser actually positions it according to the value, but if I try to set it to a percentage, it does not work.
How do I vertically center the .spinner element?
NOTE: I understand I could set the .grid position to relative and the .spinner position to absolute, but I'd prefer to keep the grid statically positioned. Is this possible without modifiying the .grid's styling?
Comment: In response to your note at the end, no, it's not possible with static positioning of the `.grid` element (unless you add a wrapper within the `.grid` element).
Comment: @bfrohs thnx, you should update your answer w/ that, that's good info!
Comment: I added it to my answer and expanded on it a bit.
Answer: First, you should use absolute positioning, with the .grid set to relative positioning. Then, set top, bottom, left, and right to 0 on the .spinner element. Since you have a fixed width/height, the positioning along with margin:auto; will center the element perfectly (example):
.grid {
    position:relative;
}
.spinner {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin:auto;
    height: 3px;
    width: 3px;
    background-color: red;
}

table {
    width: 100%;
}

In response to your note at the end, no, it's not possible with static positioning of the .grid element (unless you add a wrapper within the .grid element). This is because the .spinner element has no way of knowing the height dimensions of the table without having a container of some sort with relative positioning (which is where position:relative; on the .grid element comes in to play). You can work around this with negative margins or relative positioning all you want, but it will never be able to accommodate dynamic content (with the current set of browsers/standards).


Dollar in conditional variable assignment operator in Makefile

Question: Is it possible to pass value with single dollar from shell to Makefile, or I it is only way to put double dollar in bash and then to call make?
Makefile is:
HASH ?= $$6$$salt$$val

.PHONY: tst
tst:
        echo '$(HASH)'

Command to run:
> make HASH='$6$salt$val'
echo 'altal'
altal

If I use double quotes, all is fine:
> make HASH='$$6$$salt$$val'
echo '$6$salt$val'
$6$salt$val

But is it possible do not make substitution $ to $$ in bash?
Comment: See this may be help you:  https://stackoverflow.com/questions/26564825/what-is-the-meaning-of-a-double-dollar-sign-in-bash-makefile
Comment: @Šerg thank you for reply, but question is for conditional assignment from bash with ?=. Inside Makefile all is clear.
Answer: How about writing the initialisation within the file identical to the one coming from the command line? The below script demonstrates how to rewrite a variable with the override directive:
quote-one-level = $(eval override $1=$(subst $,$$$$,$(value $1)))

var-info = $(info $1=$(value $1) flavour=$(flavor $1) origin=$(origin $1))

A ?= $abc

$(call var-info,A)
$(call quote-one-level,A)
$(call var-info,A)

$(call var-info,B)
$(call quote-one-level,B)
$(call var-info,B)

export A
export B

all:
    @echo A = '$(A)'
    @echo B = '$(B)'
ifeq ($(MAKELEVEL),0)
    $(MAKE)
endif

Inflating one $ to $$$$ (and not just $$) is necessary because the eval command literally generates make code, thereby obviously reducing the quoting level by one. Resulting output:
$ make B='$abc'
A=$abc flavour=recursive origin=file
A=$$abc flavour=recursive origin=override
B=$abc flavour=recursive origin=command line
B=$$abc flavour=recursive origin=override
A = $abc
B = $abc
make
make[1]: Entering directory
A=$abc flavour=recursive origin=environment
A=$$abc flavour=recursive origin=override
B=$abc flavour=recursive origin=command line
B=$$abc flavour=recursive origin=override
A = $abc
B = $abc
make[1]: Leaving directory

Answer: Try this:
In console:

export HASH='$6$salt$val'; make

in Makefile:
.PHONY: tst
tst:
        @echo "$$HASH"

Result:
$6$salt$val


Regex: Full matching for a string split by delimiter

Question: I am having a string which has a delimiter like "|"
e.g. "South NY, US | South-East NY, US| North NY, US"

note: the space around the pipe on either side may or may not appear.
I have been trying to use .contains() to match a given string, but it also match the case like "East NY, US"
I have got a small function (in java) to match a search string, but it is inefficient.
boolean fullmatch (String search, String text) {
    String[] split = text.split ("\\|");
    for (int i = 0; i < split.length; i++) {
         if (split[i].trim().equals (search)) {
             return true;
         }
    }
    return false;
}

What would be the equivalent regex for this? Thanks you
additional: What would be the equivalent regex in SQL too? (trying not to pull out large amount of data for comparison in Java)
Answer: I doubt that your method is too inefficient, or that you can make it much more efficient; but for cleaner and simpler code (which also will perform at least somewhat better), you can write:
boolean fullmatch (String search, String text) {
    return Pattern.compile(
        "(?:^|\\|)\\s*" + Pattern.quote(search) + "\\s*(?:\\||$)")
        .matcher(text).find();
}

For example, if your search is "South-East NY, US", then the above will return true if text contains a substring matching (?:^|\|)\s*South-East NY, US\s*(?:\||$) (start-of-string-or-pipe, plus optional whitespace, plus the search-string, plus optional whitespace, plus pipe-or-end-of-string).
Answer: Try this:
boolean fullmatch (String search, String text) {
    return text.matches(".*(^|\\|)\\s*" + search + "\\s*(\\||$).*");
}

Comment: This will not be very efficient since `matches` will have to iterate over entire text, even if it will find correct element at start of it.
Comment: @Pshemo I suppose you mean mean efficient. Point accepted.


Proof of $n^{th}$ derivative Test

Question: Proof needn't be a rigourous , but should give an insight of how $n^{th}$ derivative test (higher order derivative test) works as i know how to use it in application but i don't much understand it ,especially the inflexion point thing.
Answer: For intuition, you can think about the Taylor series of a function $f$ near a point $x_0 \in \mathbb R$:
\begin{equation}
f(x) \approx f(x_0) + f'(x_0)(x - x_0) + \frac12 f''(x_0)(x - x_0)^2 +
\cdots + \frac{1}{n!} f^{(n)}(x_0)(x - x_0)^n.
\end{equation}
What happens if the first $n - 1$ derivatives of $f$ at $x_0$ are equal to $0$ (and $f^{(n)}(x_0) \neq 0$)?  Then those terms disappear, leaving us with
\begin{equation}
f(x) \approx f(x_0) + \frac{1}{n!} f^{(n)}(x_0)(x - x_0)^n. \tag{$\spadesuit$}
\end{equation}
And this approximation is good when $x$ is close to $x_0$.
We can easily visualize the graph of the right hand side of $(\spadesuit)$. Doing so suggests that if $n$ is even, then $f$ has a local extremum at $x_0$, and if $n$ is odd then $f$ has an inflection point at $x_0$.
Here are some graphs to help with the visualization.
Comment: @NotNotLogical haha, what's the normal way to make equation labels on math.stackexchange?
Comment: No idea, but I think most people just number their equations $(1),\;(2),...$ and so on. But hearts are fine! I suppose they add a little visual "spice"... anyway, nice answer :) +1
Comment: If you want to use equation labels you should just use the `\tag{}` function instead of messing with spacing. If you use `\qquad` to try and place tags it shifts the equation to the left. I have edited the tag in for you but feel free to roll it back if you do not want it. I just changed it to `\tag{$\spadesuit$}`.
Comment: @Prasanna Here is a carefully written fully detailed rigorous proof: https://faculty.utrgv.edu/eleftherios.gkioulekas/papers/submitted/2nd-deriv-gen.pdf
Comment: Is it really necessary to use hearts for equation labels? :)
Comment: @Brad Awesome, thank you!
Comment: @ littleO what about Rn(Remainder). It cant be omitted. Isn't it??
Comment: @Prasanna This is just an intuitive argument, not a rigorous proof.  A rigorous proof would have to account for the remainder term.
Comment: @littleO thanks for the reply. can you please suggest a website or something containing rigorous proof? I've searched and hasn't found one yet.
Comment: Indeed, this is not a rigorous proof.
Comment: @uniquesolution Note that the question says "Proof needn't be rigorous".
Comment: It is not a proof at all, rigorous or not. Even if you add the missing details, you still are using the fact that the n'th derivative is continuous, a fact which is neither needed nor given. A correct proof, rigorous or not, will have to use other arguments.
Answer: Let $f$ be $C^k$ (i.e., differentiable $k$ times with continuous $k$th derivative; we can relax this condition a bit, but it's not really useful here) on a neighborhood of a point $x$ , which we'll assume without loss of generality is $0$. Then by Taylor's theorem, we have
$$f(x) = f(0) + f'(0)x + \frac{1}{2}f''(0)x + \cdots + \frac{1}{k!} f^{(k)}(0) x^k + o(x^k)$$
near $x = 0$. If the first $(k-1)$st derivatives vanish then we're left with
$$f(x) = \frac{1}{k!}f^{(k)}(0) x^k + o(x^k).$$
Near $0$, the term $\frac{1}{k!} f^{(k)}(0) x^k$ dominates the sum above. If $k$ is even, then $x^k$ has a minimum at $x = 0$, which turns into a minimum or maximum of $f$ depending on the sign of $f^{(k)}(0)$. If $k$ is odd, then $f$ behaves like $x^k$ near $0$, which has neither a minimum nor a maximum at $x = 0$.
Answer: The following is based off patterns I have noticed and seems to make some sense (to me at least).
The derivative can be seen as having a special space; related to the original function, such that it's correlation to the original function corresponds to its 'n' . Think of it like using a ruler with a certain degree of accuracy. Each derivative can be seen as using more and more precise units of measurement. Let me try to explain.
The initial measure of change ${\frac {\rm d^0}{{\rm d^0}x}}f \left( x \right)$can be said to measure change at a scale of
                       "identity space."
Because the projected
                         identity space
 , space is equal to that of the initial space which the function lies in (ie. Euclidean Orthogonal...other coordinate systems also), its graph will be equal to the original function.
The next derivative ${\frac {\rm d^1}{{\rm d^1}x}}f \left( x \right)$will set up a space, which resembles the function
$a+x^0 = a+1$.This means that the "scale" of the derivative becomes sensitive to changes where the original function becomes a constant...(at 0). It takes this point of constant change and maps it to a zero (when
$f(x)$changes from
$a+1\mapsto a+x$.[form, imagine creating the function as you ride along it, and the type of degrees you would have to use to mimic the type of changes]).
The derivative after that ${\frac {\rm d^2}{{\rm d^2}x}}f \left( x \right)$, sets up a space resembling
$a+x^1=a+x$.Causing the derivative to become 'sensitive' to when the original function changes relative to the degree, meaning it maps points when
$f(x)$ changes from a $
a+x\mapsto a+x^2
$[form]
This change is called the inflection point.  Note(Imagine plotting and function=
                           $ a+x$
,  onto an inflection point of another function. Notice that the function being analyzed crosses the function
=$a+x$.)
Each time a derivative is taken it makes this "scale" more exact (while leaving out less exact "scales"), leading to ${\frac {\rm d^n}{{\rm d^n}x}}f \left( x \right)$ measuring at a scale of
$a+x^{(n-1)}$;
Thus:
$ \frac{d ^{n }}{d ~x ^{
n }}f \left(x \right)=0~,\forall \Delta f \left(x \right)\mid
  \exists \Delta f \left(x \right):~a + x _{
{\it form} }^{n -1}~~~\mapsto ~a + x _{{\it form} }^{n }$
$\therefore\frac{d ^{n }}{d x ^{n }}f \left(x \right):\left\{\Delta
f \left(x \right): \left( a+  x _{{\it form} }^{n
-1}\mapsto a+ x _{{\it form} }^{n }, \right )\right\}\mapsto 0~
\mathop{\rm }
$ in initial coordinate system.
(Says the derivative maps points which it is "sensitive to to zero")

Proof of $n^{th}$ derivative Test


load dependency to angularjs app after bootstrap

Question: I have angular js 1.3.3 app.
I'm loading a module from other website with :

RequireJS

I want to bootstrap my application and then load the external module Immediately after.
My code :
var app = angular.module("myApp");
app.run(function(){
   // Load external module
   require("some js url", function(){
      app.requires.push("externalApp");
    });
});
angular.bootstrap($("html"), "myApp");

This code is not working (In "myApp" there not access to services from the "externalApp"), What's wrong ?
Would appreciate help, Thanks a lot
Refa.
Comment: Are you creating or just referencing your module "myApp" there?
Comment: just referencing the create it's done before @tiagodws
Answer: The require call of RequireJS is asynchronous. By the time angular.bootstrap executes, there's no guarantee that app.requires.push(...) will have run. In fact, it is extremely likely it won't have run because the require call presumably entails loading a module from somewhere, and that takes time.
You should restructure your code so that the require is outside so that you are sure that app.requires.push(...) runs before you bootstrap your application.
require("some js url", function () {
  var app = angular.module("myApp");
  app.run(function () {
    // Load external module
    app.requires.push("externalApp");
  });
  angular.bootstrap($("html"), "myApp");
});

Comment: but i want to up the application before that I loading the external module after the angular.bootstrap


Marginalizing multivariate Gaussian distribution

Question: While working through the exercises in Mathematics for machine learning I have encountered a claim (Eq. (6.68)) that the marginal of a two-dimensional normal distribution $\mathcal{N}(x, y |\mathbf{\mu}, \mathbf{\Sigma})$ is simply $\mathcal{N}(x |\mu_x, \Sigma_{xx})$. This claim is echoed by Wikipedia and some of the answers in this site.
Yet, the direction calculation gives a different result:
$$
p(x,y) = \frac{1}{2\pi\sqrt{\Sigma_{xx}\Sigma_{yy} - \Sigma_{xy}^2}}
e^{-\frac{1}{2}\left[\Sigma_{xx}(x-\mu_x)^2 + \Sigma_{yy}(y-\mu_y)^2 + 2\Sigma_{xy}(x-\mu_x)(y-\mu_y)\right]},\\
p(x) = \int dy p(x,y) = \frac{1}{\sqrt{2\pi}\left(\Sigma_{xx} - \frac{\Sigma_{xy}^2}{\Sigma_{yy}}\right)}
e^{-\frac{1}{2}\left(\Sigma_{xx} - \frac{\Sigma_{xy}^2}{\Sigma_{yy}}\right)(x-\mu_x)^2},
$$
where I use
$$
\int dy e^{-py^2 + qy} = \sqrt{\frac{\pi}{p}}e^{\frac{q^2}{4p}},
$$
which is just a shortcut for completing the square.
My result seems to be confirmed by a different representation of the bivariate Gaussian distribution:
$$
p(x,y) = \frac{1}{2\pi\sigma_1\sigma_2\sqrt{1-\rho^2}}
e^{\frac{-1}{2(1-\rho^2)}\left[\left(\frac{x-\mu_1}{\sigma_1}\right)^2 -2\rho
\left(\frac{x-\mu_1}{\sigma_1}\right)
\left(\frac{y-\mu_2}{\sigma_2}\right) +
\left(\frac{y-\mu_2}{\sigma_2}\right)^2\right]},
$$
where, as notation implies,
$$
\Sigma_{xx} - \frac{\Sigma_{xy}^2}{\Sigma_{yy}} = \frac{1}{\sigma_1^2}.
$$
It is hard to believe in a widespread error of this magnitude. On the other hand, the calculation is very straightforward... I will appreciate clarifications.
Comment: I fear your direct calculation is wrong. See http://fourier.eng.hmc.edu/e161/lectures/gaussianprocess/node7.html
Comment: @Sergio It is actually my definition of the multivariate Gaussian that is wrong - I forgot that it is the inverse of $\Sigma$ in the exponent! Thanks for pushing me in the right direction!
Answer: I think that a few results from Robb J. Muirehead, Aspects of Multivariate Statistic Theory, might be useful.
Definition 1.2.3. The $m\times 1$ random vector $\mathbf{X}$ is said to have an $m$-variate normal distribution if, for every $\mathbf{a}\in\mathbb{R}^m$, the distribution of $\mathbf{a}^T\mathbf{X}$ is univariate normal.
Theorem 1.2.6. If $\mathbf{X}$ is $N_m(\boldsymbol{\mu},\boldsymbol{\Sigma})$ and $\mathbf{B}$ is $k\times m$, $\mathbf{b}$ is $k\times 1$, then
$$\mathbf{Y}=\mathbf{BX}+\mathbf{b}\quad\text{is}\quad N_k(\mathbf{B}\boldsymbol{\mu}+\mathbf{b}, \mathbf{B}\boldsymbol{\Sigma}\mathbf{B}^T)$$
Proof. Direct consequence of Definition 1.2.3, and of a few well known facts.
Theorem 1.2.7. If $\mathbf{X}$ is $N_m(\boldsymbol{\mu},\boldsymbol{\Sigma})$ then the marginal distribution of any subset of $k$ ($<m$) components of $\mathbf{X}$ is $k$-variate normal.
Proof. This follows directly from the Definition, of from Theorem 1.2.6. For example
$$\mathbf{X}=\begin{bmatrix} \mathbf{X}_1 \\ \mathbf{X}_2 \end{bmatrix},\quad
\boldsymbol{\mu}=\begin{bmatrix}\boldsymbol{\mu}_1\\\boldsymbol{\mu}_2\end{bmatrix},\quad
\boldsymbol{\Sigma}=\begin{bmatrix}\boldsymbol{\Sigma}_{11} & \boldsymbol{\Sigma}_{12}\\ \boldsymbol{\Sigma}_{21} & \boldsymbol{\Sigma}_{22}\end{bmatrix}$$
Putting
$$\underset{k\times m}{\mathbf{B}}=[\mathbf{I}_k:0],\qquad\mathbf{b}=\mathbf{0}$$
in Theorem 1.2.6 shows immediately that $\mathbf{X}_1\sim N(\boldsymbol{\mu}_1,\boldsymbol{\Sigma}_{11})$.
This is much clearer and easier, IMHO. But I love linear algebra :)


Execute custom JavaScript code after Webform has been submited with Webform Ajax Module

Question: I have an Webform that uses Webform Ajax modules, Steps module and few others.
I would like to execute some custom JavaScript code after the WebForm has been validted and submited.
I know I could execute custom PHP code by modyfing function _webform_ajax_callback_completed($form, $form_state) {...} inside of webform_ajax.module:
elseif ($form['#node']->webform['webform_ajax'] == WEBFORM_AJAX_CONFIRM){
...
//my custom code
...

But I don't want to mess with this module's code. And I want to execute JavaScript not PHP code.
Is there an way to do so, e.g. via some hook? Or maybe I can detect that form has been submited in JavaScript?
Answer: Okay, try this. After the ajax request is completed on "#myform", it runs the function.
$("#myform").bind('ajax:complete', function() {

     // tasks to do

});

Source | API Documentation
Comment: Please don't post code-only answers. While this might solve the problem, it doesn't explain _why_ or _how_ it solve the problem.
Comment: Okay, updated answer


Existe collections no TypeScript, como por exemplo, java?

Question: Se não existir, qual o porquê de não existir já que a orientação a objeto no typescript é tão 'bem estruturada'?
Answer: Implementado não, mas existe extensões como essa no link abaixo:
<code>https://www.npmjs.com/package/typescript-collections
</code>
Espero ter ajudado.
Comment: TypeScript nada mais que um High Level de JavaScript, ele sempre vai ser transpilado em JS . E fazendo isso você pode declarar um array de objeto, que um dentro desse array tem um outro array de objeto. Mas JavaScript esta evoluindo, logo vai ter essa estrutura.
Comment: JavaScript não possui um tipo de dados array específico. https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Indexed_collections

Nesse link você vai ver o tipo de coleções: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Keyed_collections

Mas nenhuma vai ser uma Collections igual do Java, porém essa extensão promete trabalhar  transpilar para as coleções do link acima.
Comment: Saberia me dizer o porquê de não ter implementado ?


What is the recommended method to add an RSS icon to an Open Scholar scholar site?

Question: I would like to add a linked RSS icon to the footer of a scholar site using Open Scholar. I know that the URL to an RSS feed will be:
example.com/professorname/feed
However, I'm unsure of how to programmatically get the URL to the scholar site ("example.com/professorname") so I can build the link and insert it into the page.tpl.php for a few scholar sub-themes. Is there a recommended method for this?
Comment: Cross-posted at D.o, but no answers as of this writing: http://drupal.org/node/1414822
Answer: If you have a footer menu, you could add the RSS feed to it, and then attach a bit of CSS to your theme.  The exact selectors would depend on what is being output, but you could do something like:
ul#footer-menu li.menu-1234 {
  padding-left: 20px;
  background: url(/path/to/rss.png) left center no-repeat;
}

You may need to adjust other styles to get the whole icon to appear.
There are bunches of sites with royalty free RSS icons.
Comment: Sorry I wasn't clear. I don't need CSS help, I need help in building the path.
Answer: In your theme's template_preprocess_page() function, you can pass in the base URL of the site in a custom variable... then in page.tpl.php you can access the base url.
Something like this:
<?php
function THEMENAME_preprocess_page(&$variables) {
  global $base_url;
  global $base_path;
  $variables['site_base_url'] = $base_url . $base_path;
}
?>

...and in page.tpl.php:
<?php
  // Wherever you want to print out the path, use $feed_path:
  $feed_path = $site_base_url . 'feed';
?>

Comment: ...assuming you're using 'professorname' as a site name prefix or something? (in this case, $base_path would be /professorname/).
Comment: Thanks, but unfortunately this did not work. base_path is /, not /professorname
Comment: I'm not too familiar with the way Open Scholar is set up, but I was presuming each professor had his own site, with the base_path as his name. You'll probably need to do something more specialized to get at the professor name. Try using arg(0) to see if you can get the professorname out of that.
Answer: Turns out this was an easy to do in the GUI:

Go to the Control Panel for the scholar site
Click on Site Building
Click on Layout
Drag the various feed option icons to where you want them to display
Have a beer


Display a message is not giving result?

Question: I like to show a message on 1 page of my website after login. Therefore I made a rule. To determine the mobile device I use module : mobile_detect.
I installed the corresponding library. Checking the status is saying it is available.
They module readme shows the example code:
<code>$detect = mobile_detect_get_object();
$is_mobile = $detect->isMobile();
</code>
So when I rewrite this in a message with php eval like this:
<code>#
<?php
$detect = mobile_detect_get_object();
$is_mobile = $detect->isMobile();
print ($is_mobile);
?>
#
</code>
So the result should be : #TRUE# or #FALSE# but I get back # #.
What can I do to solve this?
Answer: According to PHP manual

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

You can use below code instead
<code>print ($is_mobile ? "TRUE" : "FALSE");
</code>
Comment: thxs, it worked

Display a message is not giving result?


$f_n \rightarrow f$ a.e and $\int_\mathbb{R} f_n dm \rightarrow \int_\mathbb{R} f dm$ implies $\int_E f_n dm \rightarrow \int_E f dm$

Question: Let $\{f_n\}$ be a sequence of nonnegative lebesgue  measurable functions on $\mathbb{R}$ and $f \in L_1(\mathbb{R}) $.
if $f_n \rightarrow f$ a.e on $\mathbb{R}$ and
$$\int_\mathbb{R} f_n dm \rightarrow \int_\mathbb{R} f dm \quad \text{as} \quad n \rightarrow \infty $$
 prove that  $$\int_E f_n dm \rightarrow  \int_E f dm \quad \text{as} \quad n \rightarrow \infty .$$  for all measurable subsets E
Here are a couple of ideas that I have.
$f_n \rightarrow f$ a.e on $\mathbb{R}$ implies
if we let $A:=\{x\in \mathbb{R}:|f_n (x)-f(x)|>\epsilon\}$. then $m(A)=0$
Let $\mathbb{R}=A\cup B$ where $B=\mathbb{R}\backslash A$
then  $E \subset \mathbb{R} = (E\cap A) \cup ( E\cap B)$
$$lim_{n \rightarrow \infty}\int_\mathbb{R} f_n dm=lim_{n \rightarrow \infty}\big[\int_A f_n dm+\int_B f_n dm\big]=lim_{n \rightarrow \infty}\int_B f_n dm = \int_\mathbb{R} f_n dm$$
i.e since $m(A)=0$ , $\int_A f_n dm \overset{?}= 0$ $\forall n$
On the other hand
$$lim_{n \rightarrow \infty}\int_E f_n dm=lim_{n \rightarrow \infty}\int_\mathbb{R} f_n \chi_E= lim_{n \rightarrow \infty}\int_\mathbb{R} f_n \chi_{(E\cap A) \cup ( E\cap B)}= lim_{n \rightarrow \infty}\big[\int_\mathbb{R} f_n \chi_{(E\cap A) }dm+\int_\mathbb{R} f_n\chi_{(E\cap B)}dm\big]$$
But $(E\cap A) \subset A $ so $m((E\cap A))=0$ $\Rightarrow \int_\mathbb{R} f_n \chi_{(E\cap A)}=0$ $\quad$ Hence
$$=lim_{n \rightarrow \infty}\int_\mathbb{R} f_n\chi_{(E\cap B)}$$
If a sequence $a_n$ converges to $a$, then every subsequence $a_{n_k}$ of $a_n$ converges to $a$ [is this correct correct?]
So $$lim_{n \rightarrow \infty}\int_\mathbb{R} f_n\chi_{(E\cap B)}=\int_\mathbb{R} f dm$$.
can someone Kindly verify or correct it, or produce a proof? Thank you.
Comment: See [this](http://math.stackexchange.com/questions/1212418/showing-int-e-f-lim-n-to-infty-int-e-f-n-for-all-measurable-e).
Comment: You should add, in the end of the statement of the theorem, "for all measurable subsets $E\subset R$".
Comment: okay, I just did.
I understand your proof below. but does mine make  sense?
Comment: Duplicate of http://math.stackexchange.com/q/678282/
Comment: No, your proof is not correct since $m(A)$ does **not** equal $0$.
Comment: Okay. But I believed that is the definition of convergence a. e.
That is,  the set of points for which the condition does not hold has a measure of zero.
Comment: @J.Kyei that's right, but your definition for $A$ is not the same as the set of all $x$ for which $f_n(x)$ does not converge to $f(x)$.
Answer: By Fatou's lemma,
$$\int_{\Bbb R\setminus E} f\, dm \le \liminf\int_{\Bbb R\setminus E} f_n\,dm$$
or
$$\int_{\Bbb R} f\, dm - \int_E f\, dm \le \liminf \left(\int_{\Bbb R} f_n\, dm - \int_E f_n\, dm\right)$$
Using the condition $\int_{\Bbb R} f_n \, dm \to \int_{\Bbb R} f\, dm$, the inequality becomes
$$\int_{\Bbb R} f\, dm - \int_E f\, dm \le \int_{\Bbb R} f\, dm - \limsup \int_E f_n\, dm$$
Since $\int_{\Bbb R} f\, dm$ is finite, we deduce
$$\int_E f\, dm \ge \limsup \int_E f_n\, dm$$
On the other hand, Fatou's lemma also gives
$$\liminf \int_E f_n\, dm \ge \int_E f\, dm$$
Therefore $\int_E f_n\, dm \to \int_E f\, dm$.
Comment: How do we know that $\int_{\Bbb R\setminus E}f_n \ dm \to \int_{\Bbb R\setminus E}f \ dm$ so that we may apply Fatou's lemma?
Comment: @Addem it is assumed that $\{f_n\}$ is a sequence of nonnegative measurable functions converging pointwise a.e. to $f$. So Fatou's lemma may be applied to obtain $\int_{\Bbb R\setminus E} f\, dm \le \liminf\int_{\Bbb R\setminus E} f_n\ , dm$.


Equivalent condition of Hausdorff

Question:
This claim is from Ulrich Gortz and Torsten Wedhorn's  Algebraic Geometry I. First I think there are some errors that (ii) and (iii) should be
For every topological space $Y$ and every continuous map $f : Y\to X$ its graph $\{(y,f(y)); y\in Y\}$ is closed in $Y\times X$.
For every topological space $Y$ and any two continuous maps $f, g : Y\to X$ the kernel $\{y\in Y ; f(y) = g(y)\}$ is closed in $Y$.
But even for this, I wonder if this is correct? For example, I know that if $X$ is Hausdorff, then for every topological space $Y$ and every continuous map $f : Y\to X$ its graph $\{(y,f(y)); y\in Y\}$ is closed in $Y\times X$, but is the converse true?
Similarly, I wonder if for every topological space $Y$ and any two continuous maps $f, g : Y\to X$ the kernel $\{y\in Y ; f(y) = g(y)\}$ is closed in $Y$ we can conclude that $X$ is Hausdorff?
Comment: $X,Y$ should also be interchanged in $(iii)$ so that the indicated 'kernel' makes sense as a subset of the domain.
Comment: @Mirko are you sure? I think William's answer works perfectly well with my correction
Comment: @Mirko the Hausdorff space needs to be the image for the graph statement do $Y\times X$ is correct. And the kernel is a subspace of $Y$ indeed.
Answer: Hausdorff implies (i).
If (x,y) not in the diagonal, exists open U,V that separate x,y.
Since U,V are disjoint, open U×V misses the diagonal.
Thusly the complement of the diagonal is open.
(i) implies (iii).
f×g:Y×Y -> X×X, (x,y) -> (f(x), g(x)) is continuous.
{ y : f(y) = g(y) } = (f×g)$^{-1}$({ (x,y) : x = y }
is the inverse image of a closed set by a continuous function, hence closed.
(iii) implies (ii).  (ii) is a special case of (ii).
(ii) implies (i).  (i) is a special case of (i).
(i) implies Hausdorff.
Proof is left for the enjoyment of the diligent reader,

Equivalent condition of Hausdorff


Interpreting logistic regression

Question: I need to perform a logistic regression to to see if a group of variables which are found to be significantly associated with an outcome (by univariate tests) have significant impact on the outcome when they are put together.
In this case, from my reading, I gathered that in SPSS I need to use the enter method. When I applied this method, my new model decreased the prediction percent (not sure if this is the correct term) in the classification table in comparison to the constant only model (90.5 in constant only to 89.8 in new model). I have excluded multiple collinearity earlier.
Omnibus Tests of Model Coefficients
        Chi-squaredf    Sig.
Step 1  Step    27.441  7   .000
         Block  27.441  7   .000
         Model  27.441  7   .000

Model Summary
Step    -2 Log likelihood   Cox & Snell R Square    Nagelkerke R Square
  1               164.185a                .086                   .184

(a Estimation terminated at iteration number 6 because parameter estimates changed
by less than .001)

Hosmer and Lemeshow Test
Step     Chi-square    df     Sig.
1            6.317      7     .503

Given my objective of seeing if the independent variables when put together can have a significant impact on the outcome or not, can I use this model for that purpose to identify the variables that have and do not have independent effects on the outcome when compared together?
In answer to the comments:

As for the "measure of predictive accuracy", could I please know it in layman's terms please? My statistical vocabulary is inefficient to answer precisely though I understand what is should mean.
I ran collinearity diagnostics to see there is an issue of multicollinearity between independent variables.

I cannot paste the ROC curve itself, but the tables is given below, given the values I guess I may still use the model as it is rather than changing any other parameter. Opnion on this is welcome. Thank you everyone for suggestions.
Area Under the Curve
Test Result Variable(s): Predicted probability
Area    Std. Error a   Asymptotic Sig. b    Asymptotic 95% Confidence Interval
                                            Lower Bound             Upper Bound
.756    .042           .000              .67                           .839

The test result variable(s): Predicted probability has at least one tie between the
positive actual state group and the negative actual state group. Statistics may be biased.
a Under the nonparametric assumption
b Null hypothesis: true area = 0.5

Now I have an additional problem, or two rather
1. I have another outcome variable, again my onjective is to identify independant predictors for the given outcome amongst predictors with a p<0.01 in univariate analysis. I tried different combinations of covariates manually using the enter method, and non of a combinations seem to give a statistically acceptable models in terms of correctly classified proportions in classification tables or in ROC curves. Individially taken, these variables would give acceptable values (>0.8) in ROC despite not improving the correctly classified rates. Can I take this as being evidence of these covariants not haveing independant effects on the outcome? (number of independant variables available 7)
As the dependant variable in this is 30 day mortality, I think I can try Cox regression. However, the only time dependant variable I have is length of hospitalization, I am not too sure if I can use this at the "time" cage in SPSS.
Thank you in advance. (I am not too sure if I need to post this as a new question)
Comment: For the record, this question is related to [How do I conduct model selection for logistic regression in SPSS?](http://stats.stackexchange.com/q/32893/930)
Comment: what is your measure of prediction accuracy?
Comment: What exactly does it mean that you "excluded multiple collinearity earlier"?
Comment: See also: https://stats.stackexchange.com/questions/109851/using-proper-scoring-rule-to-determine-class-membership-from-logistic-regression,    https://stats.stackexchange.com/questions/359909/is-accuracy-an-improper-scoring-rule-in-a-binary-classification-setting
Answer: Check out the University of California Los Angeles site for detailed help on logistic regression using SPSS.
Further the link contains the annotated SPSS output with interpretations.
Comment: Thank you very much for the suggestion, I read the given link and a number of more books and articles, however couldn't find the answer that I am looking for. That is in cases where the overall percentage in classification tables for the test model is less than that of the constant only model, how to proceed. The objective of the analysis is to check if certain indepandant variables can individually predict an outcome when thet are acting together. There independant variables were found to be significantly associated with outcomes in univariant models.. Thank you
Answer: It's not unusual to see, with a relatively weak model, that the correct classfication rate (CCR) does not improve, or even drops, from what it was with a null (baseline) model.  A lot of authors and analysts rely on other indicators of a model's predictive power and disregard the CCR as a general policy because it oversimplifies:  it turns predictive information at the level of probability for each observation (continuous, from 0 to 1) into a binary decision (correct or incorrect classification).
However, if you find the CCR to be an important indicator in your context, you might improve results by changing your threshold for identifying a case as "1" as opposed to "0". SPSS's default is to call a case "1" if the predicted probability is over .5, but you may decide to use a threshold of, say. .4 or .35. I say this realizing that it can take on the aspect of "cherry picking" and may open you to criticism.  It's best to change this threshold only if you have a theoretical basis for doing so--not merely to improve the CCR after the fact.
Another approach is to examine ROC curves, which you can obtain from SPSS in a different menu if you first save each observation's logistic regression predicted probabilities.  Through the ROC procedure you can check those probabilities' matchup with the values on the binary outcome variable.
Comment: @cb80 You will need to [register your account](http://stats.stackexchange.com/faq#login) to post comments and access system-wide notification. In the meantime, I've merged your two accounts.
Comment: +1, nice points @rolando2. I can imagine someone arguing that using a different threshold is "cherry picking", but I wouldn't agree w/ them; you haven't changed what covariates are included, your alpha, etc., & other global model quality metrics would be unchanged. In general, w/ LR, unless I misremember, classification accuracy is maximized if the threshold is equal to the proportion of 1's in the population (which, in practice, is assessed by the proportion in your sample). Eg, if 35% get sick, predict that a given patient will get sick if $\hat p>.35$.
Comment: Thank you very much, extermely helpful. I will perform ROC and see if the model is "fitting".
Comment: Thanks gung. That sounds like an intuitive strategy but such things are often deceiving.  Can you think of a reference or two on that--or can others weigh in as to whether they have found it to be true?

Interpreting logistic regression


Quando rodo no html a classificação sempre mostra undefined, mas quando rodo no console ele traz a resposta da variavel _class alguem pode me ajudar?

Question:

Answer: Você só precisa mudar a sua linha de código document.write(`Classificação:${_class}`); para o final da sua condição lógica.
Aí sua variável _class já vai estar preenchida.
 //função que calculao IMC do paciente.
    function CalcImc(peso,altura){
    var imc = p/(a*a);
    return imc;

    }   //Entrada de dados e declaração de variaveis.
        var nome = prompt("Digite o seu nome:");
        var idade = parseFloat(prompt("Digite a sua idade:"));
        var p = parseFloat(prompt("Digite o seu peso:"));
        var a = parseFloat(prompt("Digite a sua altura:"));
        var _class;

        //invocando a função imc.
        CalcImc(p,a);
        //Imprimindo na tela as informações.
        document.write("===============
");
        document.write("CALCULO DE IMC
");
        document.write("===============
");
        document.write(`Paciente:${nome}<br>`);
        document.write(`Idade:${idade} anos<br>`);
        document.write(`Peso:${p}kg<br>`);
        document.write(`Altura:${a} metros<br>`);
        document.write(`Seu IMC é:${CalcImc(p,a)}<br>`);

        //Estrutura condicional que informa a classificação do paciente.
            if (CalcImc(p,a) < 18.5) {
                _class = "Abaixo do Peso";

            }else if((CalcImc(p,a) == 18.5) && (CalcImc(p,a) <= 24.9)){
                _class = "Peso normal";

            }else if ((CalcImc(p,a) == 25.0) && (CalcImc(p,a) <= 29.9)){
                _class = "Sobrepeso";

            }else if((CalcImc(p,a) == 30.0) && (CalcImc(p,a) <= 34.9)){
                _class = "Obesidade grau I";

            }else if((CalcImc(p,a) == 35.0) && (CalcImc(p,a) <= 39.9)){
                _class = "Obesidade grau II";

            }else{
                _class = "Obesidade grau III";

            }
       document.write(`Classificação:${_class}`);

Comment: Entendi, eu tinha colocado document.write(`Classificação:${_class}`); dentro de cada  condição if, e deu certo também, porem com a sua resposta vi que só precisa colocar no final de todos os if's que ela vai valer para todas as condições e deixa o código mais limpo, muito obrigado um grande abraço.


Which competitions have had the same person as the youngest and oldest winner?

Question: In December 2023, Ronnie O'Sullivan won the 2023 UK Championship in snooker, and in doing so he became both the youngest winner of the championship - in 1993 at 17y 358d - and the oldest winner at 47y 363d.
Are there any other instances of this across the wide world of sport, where a competitor is both the youngest and oldest winner of a competition at the same time?
To keep this from being too broad, I'll keep this to "major competitions" in their respective sports eg Champions League / World Cup in football, a Grand Slam event in Tennis, a Major event in Golf, Olympic events etc etc.
Comment: @GreenMatt - I think for the sake of this particular question they would need to be both at the same time - at least that's the situation with O'Sullivan which prompted the question initially.
Comment: Must the competitor remain the youngest champion when they become the oldest? For example, when he won his first Masters, Jack Nicklaus was the youngest to do so. When he won his last, he became the oldest to do so (and remains so). However, before Nicklaus became the oldest champion, Seve Ballesteros became the youngest (and others have since taken that distinction).
Comment: At least until next year, [Alberto Ginés López](https://en.wikipedia.org/wiki/Alberto_Gin%C3%A9s_L%C3%B3pez) is both the youngest and oldest winner of the men's Olympic sport climbing event.
Answer: Technically the answer is "everything", because the first time a major competition is run the winner is simultaneously the youngest and oldest person to ever win it!
But if we're going to rule out that there's still at least one additional case:
W Series - The all-female motorsport championship ran for a total of three seasons (2019-2022) and all three were won by Jamie Chadwick so she was the youngest winner in 2019 and the eldest in 2022
I think Birgit Fischer counts too - having won Olympic canoeing gold medals at 18 and 42
Answer: The 50 m freestyle has the youngest and oldest gold medalist - Anthony Ervin as a 19 year old in 2000 and a 35 year old in 2016.


How to change the image style used in a field in specific view results?

Question: In Drupal 7 I used hook_views_pre_render() to update the image style for specific results. I'm trying to do the same for a view in Drupal 8 but I don't have the same options available in the field.
An example of the code I used before:
$view->result[4]->field_field_image[0]['rendered']['#image_style'] = 'image_style_name';
There's no longer a 'rendered' array, just an ImageItem object with the target_id, title, width and height.
Answer: The bad news is that you can't use that approach anymore. Due to the performance improvements like this one, fields are all rendered via #pre_render callbacks, and run through the same build process as normal entity rendering.
The good news is that hook_entity_display_build_alter() will run, the very same hook that runs for displaying an entity.
Views doesn't pass any additional context to this hook. Depending on how you were deciding which one to alter, you may still be able to accomplish this.
Comment: Unfortunately I wasn't able to accomplish the thing I wanted because I needed more context from views but thanks for the detailed explanation :)


Filter views by current user taxonomy profile field

Question: Entity type: Book
I have entity type called "Book".
It has one field called "book_id".
Ex: science book(Book_name) -> 100(Bokk_id)
Maths -> 101
english -> 102

User:
I have user, he has one field attached with user profile called "book_name".
"Book_name" is a taxonomy reference field.
"Book_name" has one field called "book_id"
"Book_id" is free text field, it has more than one value by comma separator. Like 100,101,102.
Ex: user->book_name(taxonomy reference field)->book_id

Using views, I want to filter entity type "book" by current logged in user "book_name->book_id".
Answer: Because this is a comma separated text field, your best bet is with custom module that gives your view the ids in a 2+6+36+98 format.
https://drupal.stackexchange.com/a/222876/53677
In that answer, I described how to pass one value from a user field. For you, you'd need to load the taxonomy entity and work with that.
Then, to do multiple, you just need to add a bit of php to split your text field and turn it into the format above with +. You still only pass one argument and in your view, enable multiple values in the contextual filter's settings.
I can't give a longer answer until tomorrow. Btw, if that text field has node ids for books, you should use the entity reference module.
Answer: This can be done in views without creating a custom module.
Since you want to list entities that use the same term reference as the user account, its best to create a view of terms and add relationships to the user and book. For the user you need to add an extra relationship since its a level deeper to reach the term reference field.
Add the book fields that you want, using the book relationship.
Then add the term reference field two times, one with the user relationship and one with the book relationship. You may hide these fields.
Then add filter 'field comparison', selecting both similar term reference fields, and choose 'is equal to'.
Also add the filter user (with relationship) is 'currently logged in user'.
The result is a view showing books that have the same term reference (book_id) value as the currently logged in user.


How can I play C#/Db on a soprano recorder with single holes? I can't play that note

Question: I would like to play that note properly but I can not. I also would like to determine the make of my soprano recorder... it's green, solid and made from hard plastic, It has two stripes in the head and six stripes in the end. It says "Made in Germany" But it doesn't have the make printed anywhere. Is it too hard to tell the make of a recorder?
(edit: I know I can play it by covering half of the hole but it doesn't work)
Comment: You might be able to track down the manufacturer via Google Image Search.
Comment: Welcome to MusicSE.  A big reason your question can't be directly answered is that you haven't given us enough information.  Examples: can you produce this note on someone else's recorder, or the equivalent notes on an Alto?  This way we know a bit about your overall skill level.
Comment: Thank you for answering. I currently can play the flight of the bumblebee at normal speed, but that note sounds off... And I uploaded a picture of my recorder so you can see what I mean. What do you mean my skills? It's either covering half of the hole or if its double holed covering the first hole. It obviously  plays the right note on a double holed recorder. It's just I can't find the make. I have tried google image search but it doesn't recognize it properly.
Answer: It's likely that this note cannot be played cleanly on your recorder.
There are two fingering systems that may be found on modern recorders:

English (Baroque) - a reconstruction of the baroque recorder, based in large part on the work of Arnold Dolmetsch. This system can be identified by the 4th hole (counting from the lip) being smaller than the 5th hole.
German ("school") - Peter Harlan's simplified fingering, where the 5th hole is smaller than the 4th hole. This allows the ascending major scale to be played simply by consecutively lifting fingers - at the cost of making chromatic notes harder to play in tune.

Judging by your description, your instrument is the lowest tier of school recorder in German fingering, meaning that it is made to play cleanly in C major only. This is just about sufficient to play the kind of basic pieces one might encounter during general music lessons in school, but obviously insufficient for any kind of advanced performance.
You could possibly try to achieve a clean note through shading (partial covering of holes), breath control, or possibly even an alternative fingering - but it may be a better idea to get a quality baroque system recorder, if you wish to pursue the instrument more seriously.
I'm afraid there's nothing I can tell you about the make of your recorder.
Addendum to address the added image:
As I had guessed, the instrument in question is a very basic school recorder with German fingering. Trying to perform advanced material on it is likely to be an exercise in futility.
Buying recommendations are off-topic here, but any baroque-fingering recorder from a reputable manufacturer should be adequate.
Comment: Faza- sorry, but you did not answer the question at all.  While German fingering has its problems, especially with the F# on a soprano recorder, the question was about playing C#/Db.  For that, it doesn't matter if English/Baroque or German: if you don't have double holes for C#, you can't do it, except by half-holing, which, as the OP points out, is of limited utility.
Comment: Well if you buy another German fingering recorder you will just have exactly the same problem, only less money. The only way you are going to get a C# / Db on a German recorder is to half-hole the bottom note, and the only way you're going to get a decent note that way is by practicing until you can reliably get it right. Unless German recorders defy the fundamental physics of sounding tubes there will be a correct position for half-covering the bottom hole, you just haven't put enough practice into it yet.
Comment: Hi, thank you for answering my question. I edited the post to show you the size of each hole. Also the hole for the 8th finger is the smallest. I am learning the flight of the bumblebee and I need to play that note because its mostly chromatic scales. I can make sound out of it by covering half of the hole but it is not the right note. With the other notes I don't have a problem so far. What commercial recorder would you suggest for me to get?
Comment: @ScottWallace It was already established that on this recorder the normal technique of half-holing won't work. The instrument is inadequate to the task at hand. The only possible answer to the question is "get a better recorder". Baroque fingering is generally superior in terms of chromaticism and thus the only recommendation I can give within the scope of this site is to go with that fingering.
Comment: @faza Very useful comments. I don't know how but I played the note, but it's still hard to play, and when I hit it, it almost makes no sound at all. I hope I can buy a new recorder soon. I guess I am used now to german recorders, so I would buy a german anyways unless I can get to compare them before.
Comment: @Faza- sorry again, but that doesn't cut it.  The problem of fingering C#/Db is a problem of having or not having a double hole there.  Since some German fingering recorders have double holes for C#/Db, and not all Baroque recorders (especially original ones) have one, you are not addressing the issue at all.
Comment: @ScottWallace thank you for the note. Very informative.
Answer: You are meant to be able to play it by covering all the holes, except that with the bottom hole you only cover half of it.  You may need to experiment with the strength of blowing as well.  If that doesn't work you probably need to buy another instrument.
Mollenhauer Dream recorders have a single bottom hole, but if it is a Mollenhauer I am surprised it doesn't work.


Abusive post editing?

Question: Hi fellow Magento addicts.
So, from time to time, on the main question feed page, there seem to be a big load of questions (with accepted answers or not) that come back from the grave. After looking at the edition history, it looks like those questions were just edited to either add a tag, or just correct small typos.
So my question is, what's the point? Is it just to gain some reputation (which would be really lame)? is it you think you have to do the Community's job? is it you think it's important to add new tags to old posts? or is it you think it's important to bring up old unanswered questions so as the OP's acceptance rate rises? (but what about the answered questions being bumped then?)
I'm just curious that's all.
Answer: I think you are talking about me.
I'm certainly not doing it for the reputation.
I don't get any rep from editing posts anymore.
I just wanted to clean up this website a bit.
I've been doing this for a while (not just editing, but answering, voting, closing, re-tagging).
My reasons? See this: The quality of MageOverflow.
I'm looking through old questions, try to bump the ones without accepted answers, maybe someone can view them. There are a lot more members now than they were 9 or 12 months ago, maybe some of the new guys have an idea on old questions.
Also I'm trying to properly tag questions so they can be found easily by new-comers. A lot of them have only a single tag that state the magento version, or they are wrongly tagged.
Other have poorly formatted code, that hurts my eyes.
Others have signatures in the question or answer, that ..well...see this: https://meta.stackexchange.com/a/5038/224252
I'm sorry that this is received as abusive.
I will take your question as a first "thumbs down". If other users complain about this I promise to stop.

No good deed goes unpunished.

[EDIT]
And I don't know if you noticed, but I edit new posts also.
Comment: Imma buy you a broom when I come see you in Cluj.
Comment: @benmarks. You're coming to Cluj, just to see me? aww...that's nice.
Comment: I wasn't specifically refering to you, and I acknowledge you're doing a really good job in here, don't get me wrong, but I was just wondering the reasons behind this, thank you.
Comment: and I wasn't asserting it as being abusive, hence the question mark :p
Answer: adding new Tags can be a big help for others, who only use tags to finde Questions to answer.
In My Example, I mainly observe questions with the Tags Composer and phpunit, if the questions dont have the tag, I will not find them, so its a good thing to have some people wo regularly go trough older questions and add this tags, so other more specialized people can find and answer them.

Abusive post editing?


Registration with text files only insert the || between words

Question: I am trying to create a registration with text file as I cannot use databases, but in my registration only the || between the words are inserted and the words do not show. Also, my file does not open automatically and I did set the directory to wrx. I have been working with this for quite a long time.
Comment: Try using `print_r($_POST)` to view the contents of the `$_POST` array and see what information you're getting from the webpage.
Comment: Why are you using this line of code : `if(!strstr($file, "$string"))` ?
Comment: If I went onto your website and I typed in http://yourwebsite.com/loginDetails.txt, I could read all the usernames and passwords that can access your site.
Comment: @learnerNo1 max_ meant security issue, anyone can see your user details...
Comment: Can you see the username ||?
Comment: Can you try writing dummy data to file? Like `$string = "username||password||fullname||emailaddress ";`
Comment: The print_r($_POST) did not work. It prints this to the screen print_r($_POST['username']); print_r($_POST['password']); I will try to add "" and see.
Comment: It takes long to test as everytime I need to shut down the server and start again to see the effects in the file.
Comment: It does not work, it adds  || to the dile instead of $username || $password || $name || $email
Comment: What about security, what can I do to make my file invisible, however first I need to make it work. :-)
Answer: For one, this looks wrong:
<code>$name = $_POST['username'];
$email = $_POST['password'];
</code>
It should be:
<code>$username = $_POST['username'];
$password = $_POST['password'];
</code>
Comment: Fix it (and test it) and modify the code in the question so that people don't focus on that one.
Comment: This error it's fixed before. And with all of other suggestions only shows || $password instead of $username || $password || $name || $email
Comment: Ok. I will modify it now. :-)


How to whiten the data using principal component analysis?

Question: I want to transform my data $\mathbf X$ such that the variances will be one and the covariances will be zero (i.e I want to whiten the data). Furthermore the means should be zero.
I know I will get there by doing Z-standardization and PCA-transformation, but in which order should I do them?
I should add that the composed whitening transformation should have the form $\mathbf{x} \mapsto W\mathbf{x} + \mathbf{b}$.
Is there a method similar to PCA which does exactly both these transformations and gives me a formula of the form above?
Comment: (My first comment was based on misreading your question.) PCA gives you zero covariances; you can standardize the PCs afterwards if you wish. It sounds an odd thing to do, but you can do it.
Comment: @NickCox Maybe it seems odd because the transformed data is then spherical, which seems uninformative. However, it is the transformation I need to know, and not the end result.

Still I don't know what the transformation would look like. I'm still reading up on PCA, though.
Answer: First, you get the mean zero by subtracting the mean $\boldsymbol \mu = \frac{1}{N}\sum \mathbf{x}$.
Second, you get the covariances zero by doing PCA. If $\boldsymbol \Sigma$ is the covariance matrix of your data, then PCA amounts to performing an eigendecomposition $\boldsymbol \Sigma = \mathbf{U} \boldsymbol \Lambda \mathbf{U}^\top$, where $\mathbf{U}$ is an orthogonal rotation matrix composed of eigenvectors of $\boldsymbol \Sigma$, and $\boldsymbol \Lambda$ is a diagonal matrix with eigenvalues on the diagonal. Matrix $\mathbf{U}^\top$ gives a rotation needed to de-correlate the data (i.e. maps the original features to principal components).
Third, after the rotation each component will have variance given by a corresponding eigenvalue. So to make variances equal to $1$, you need to divide by the square root of $\boldsymbol \Lambda$.
All together, the whitening transformation is $\mathbf{x} \mapsto \boldsymbol \Lambda^{-1/2} \mathbf{U}^\top (\mathbf{x} - \boldsymbol \mu)$. You can open the brackets to get the form you are looking for.

Update. See also this later thread for more details: What is the difference between ZCA whitening and PCA whitening?
Comment: I think you need to divide by the square roots of the eigenvalues, as it is a matter of scaling by SD, not variance.
Comment: I have empirically verified the formula. Thanks for helping me!
Comment: @NickCox: yes, of course you are right. I corrected my answer. Thank you!