How to debug these internal server errors?

Question: I am not a server admin but do have some experience with Linux servers but mostly in Django and Nginx. Someone at our company has left suddenly for personal reasons and we have a site running on PHP with two pages that are showing internal server error messages that I need to fix.
I have done a fair bit of searching here and on Google and tried a few things already but still stuck, these are the urls to the pages (domain removed):
http://dev.mydomain.com/user/login/index.php
http://dev.mydomain.com/ew-admin/submit.php
I first did a grep search for the index.php url in the Apache error logs and found this:
<code>[Fri Mar 10 06:15:51.083887 2017] [core:error] [pid 24087]    [client 18.104.22.168:54740] AH00124: Request exceeded the    limit of 10 internal redirects due to probable configuration error.     Use 'LimitInternalRecursion' to increase the limit if necessary.     Use 'LogLevel debug' to get a backtrace., referer:        http://dev.mydomain.com/user/login/index.php
</code>
and then after Googling those errors I found this thread:
https://stackoverflow.com/questions/19071324/request-exceeded-the-limit-of-10-internal-redirects
this is my .htaccess file
<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>
and I tried adding the line that was suggested in the SO thread to the .htaccess file but that didnt seem to change anything.
So next I checked the file and folder permissions for where those files are stored, they weren't set to 755 so I changed them to that, still getting internal server error though.
I should all that the public_html/ directory has these two directories in them:
dev/
old_mydomain/dev
the dev/ directory is empty and old_mydomain/dev directory seems to have the files for these two urls that are showing errors so I tried moving all the files from old_mydomain/dev to the empty dev/ directory seeing as the url has the 'dev.' subdomain but that didnt work either so I moved the files back.
I found an error_log within the old_mydomain/dev directory too with the following in but this seems to have stopped logging errors in the summer of last year and I know that these two urls were working just a few months back:
<code>[21-Jul-2016 11:45:20 UTC] PHP Warning:  fsockopen(): unable to connect to toolbarqueries.google.com:80 (Network is unreachable) in /home/mydomain/public_html/dev/pagerank.php on line 85
[29-Jul-2016 06:03:09 UTC] PHP Warning:  mysql_connect(): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (111) in /home/mydomain/public_html/dev/hide/init.php on line 14
[30-Jul-2016 13:22:40 UTC] PHP Warning:  mysql_connect(): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (111) in /home/mydomain/public_html/dev/hide/init.php on line 14
[31-Jul-2016 10:38:20 UTC] PHP Warning:  mysql_connect(): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (111) in /home/mydomain/public_html/dev/hide/init.php on line 14
[07-Aug-2016 13:32:34 UTC] PHP Warning:  fsockopen(): unable to connect to toolbarqueries.google.com:80 (Network is unreachable) in /home/mydomain/public_html/dev/pagerank.php on line 85
[08-Aug-2016 20:37:55 UTC] PHP Warning:  mysql_connect(): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (111) in /home/mydomain/public_html/dev/hide/init.php on line 14
[09-Aug-2016 23:58:17 UTC] PHP Warning:  mysql_connect(): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (111) in /home/eatonweb/public_html/dev/hide/init.php on line 14
[11-Aug-2016 00:04:53 UTC] PHP Warning:  mysql_connect(): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (111) in /home/mydomain/public_html/dev/hide/init.php on line 14
[16-Aug-2016 22:27:06 UTC] PHP Warning:  mysql_connect(): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/mydomain/public_html/dev/hide/init.php on line 14
[17-Aug-2016 23:57:40 UTC] PHP Warning:  mysql_connect(): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/mydomain/public_html/dev/hide/init.php on line 14
</code>
Thats all I can think of for debugging and Im stumped right now, any help would be appreciated!
Comment: You need to find out which entity exactly is sending those redirects, and then fix the code. It is most likely the PHP script.
Comment: thanks for your feedback, I managed to figure this out and going to answer it myself now!
Answer: So found the problem with some assistance, it seems there was no .htaccess file in dev.mydomain.com so the .htaccess in root was being used which was configured differently and this caused the server errors.


What is the advantage of using a WCF service instead of a WCF library if I am going to host a WCF service in IIS?

Question: I understand what the differences are between a WCF Library and a WCF Service. I typically will build a WCF Library and reference it from a WCF Service. But if I am going to deploy to IIS, why not just deploy the WCF Library and forget about creating the WCF Service. Does it matter which one I deploy?
Comment: Possible duplicate of [What is the difference between a WCF Service Application and a WCF Service Library?](http://stackoverflow.com/questions/1204365/what-is-the-difference-between-a-wcf-service-application-and-a-wcf-service-libra)
Comment: No this question is not a duplicate. This question asks if there is any benefit in using one over the other in the context of an IIS host.
Comment: IIS tends to be more robust in terms of logging and error handling.  A service library gives you the advantage of hosting the service in IIS or other hosts (or even multiple hosts) and separation of code.  You can also very easily run WCFTestClient against a WCF service application.  If you are only going to host in IIS, then the service application is probably best.  Functionally, a WCF service application and a WCF service library are equivalent.
Comment: I normally would agree that hosting a service would be better than hosting a library, but I want to know for sure if that is true.
Comment: @user3366675 - You're asking a question that has multiple valid answers.  It really depends on the requirements of the project/application.  If you're only going to host it in IIS, the Service Application is prefectly fine.  If you think you might host the service in other ways (e.g., Windows Service), then you'll want to use a Library to avoid code duplication.  I've done it both ways, but I *generally* tend to go with Service Application.
Comment: Tim, I agree with you that a Service Application would work fine in IIS. But why not just use the library, since it is more versatile anyway, and then just forget that Microsoft ever developed a WCF Service project?  If the service project can't do anything more than the library, then what is the point of it.
Answer: Answering my own question: From what I have read it doesn't seem to matter much if you deploy a wcf library or a wcf service. If you deploy the library, make sure that you copy the contents of your app config file to the web config file. The wcf service does also provide an svc file, but you only need that if you are using an earlier version of .net framework other than 4.0 or later. If you deploy the service instead of the library, the App config file for the service will pass the content onto the Web.config file when it is deployed. I am pretty sure that these are the only differences. The two people that replied to my question didn't really take the time to read and understand the question. It got marked as a possible duplicate, which clearly it is not.


Central Limit Theorem with Bounded Sum of Variances?

Question: I have a sequence of bounded independent random variables $X_1,...,X_n,...$ satisfying $\sum_{i=1}^{\infty} \mathbb{E}[X_i] < \infty$, $\sum_{i=1}^{\infty} Var[X_i] < \infty$.  Most versions of the central limit theorem I've found online require $\sum_{i=1}^{\infty} Var[X_i] = +\infty$ in order to be applied. Is there some limit theorem which can give me the limiting distribution of
$$Pr[\frac{\sum_{i=1}^{N}{X_i}-\mathbb{E}[X_i]}{\sqrt{\sum_{i=1}^{N} Var[X_i]}}\leq y].$$
Is there a reason why the central limit theorem would not apply?
Answer: Heuristically, if the sum of the variances isn't infinite, there is some residual shape information in the sum about some of the individual variables. For example, if
$$\mathrm{var}[X_1]=\epsilon\sum_i \mathrm{var}[X_i]$$
then $X_1$ makes up $\epsilon>0$ of the limiting random variable and the shape of $X_i$ (tails, moments, etc) has $\epsilon$ effect on the shape of the limiting distribution.
One way to think about why there's a problem is the Levy-Cramér theorem, which says that if $Y_1$ and $Y_2$ are independent and not constant, and $Y_1+Y_2$ has a Normal distribution, then both $Y_1$ and $Y_2$ have Normal distributions.
Now take $Y_1$ to be $X_1$ and $Y_2$ to be the sum of the rest of the sequence. If $\sum_i \mathrm{var}[X_i]=S^2<\infty$, then $Y_1$ and $Y_2$ are non-constant independent random variables. Unless they are both Normal, their sum isn't Normal -- and so the sum of the series isn't Normal.  You can see this argument breaks down if $S^2$ is infinite, as then $Y_1/S$ is constant.
In special cases you can think about this in terms of moments. For example, suppose $Y_2$ is Normal but $Y_1$ has non-zero skewness. Then $Y_1+Y_2$ will have non-zero skewness. The Levy-Cramér argument does the same sort of thing, only a lot more general.
[If only finitely many $\mathrm{var}[X_i]$ are non-zero, the Levy-Cramér argument is much more direct, since the ones with non-zero variance immediately have to be Normal, but that's a special case]


Mean value of $\Omega(n)$ is $\log\log n$

Question: This question is from my number theory assignment and I was unable to solve it. I have been following Dekonick and Luca.

Let $\Omega(n)$ be the number of prime divisors of n, counted with multiplicity ie the number of prime powers dividing n, for instance $\Omega(12) = 3$. Show that mean value of $\Omega(n)$ is $\log\log n$: $\frac{1}{N}\sum_{n\leq N} \Omega(n) = \log\log N+O(1)$.

Attempt: I thought of using Abel's Identity : $\sum_{n\leq N} f(n) = f(N)[N]- \int_{1}^x [t] f'(t)\,dt$.
Here $f(n) = f(p_1^{x_1} \cdots p_r^{x_r}) = x_1 + \dots + x_r$
So, I got $\sum_{n\leq N} f(n) = (x_1 + \dots + x_r)[N]- \int_{1}^{x} [t] (x_1+\dots+x_r) \log t\,dt$. Dividing by $N$, $((x_1 + \dots + x_r)[N])/N =O(1)$, and the other term after simplifying I got as $$(x_1+\dots+x_r)(\log N -1-(N\log N)/2+N/4+1/N(3/4))$$ which is not equal to what has to be proved.
So, please help.
Comment: partial summation is for removing continuous functions, not for removing the sequence.  here you (i think) just need to write in the explicit definition of $\Omega $.  for example, if the question was about $\omega $ (which is a very similar function) then your sum would be $\sum _{n\leq x}\sum _{p|n}1$ which you can then rearrange and get a result.
Answer: Using a collection of useful results (left as a home exercise to polish the details) ... let's note by:
$$d(n,k)=\left\{\begin{matrix}
1, & k\mid n \\
0, & k \nmid n
\end{matrix}\right.$$
Then, where $p_i$ is the $i$-th prime:
$$\Omega(n)=\sum\limits_{p^\alpha \mid n}1=
\sum\limits_{i=1}\sum\limits_{\alpha=1}d(n, p_i^\alpha)$$
And
$$\sum\limits_{n=1}^N\Omega(n)=
\sum\limits_{n=1}^N \left(\sum\limits_{i=1}\sum\limits_{\alpha=1}d(n, p_i^\alpha)\right)=
\sum\limits_{i=1} \left(\sum\limits_{n=1}^N\sum\limits_{\alpha=1}d(n, p_i^\alpha)\right)=\\
\sum\limits_{i=1} \left(\sum\limits_{\alpha=1}\sum\limits_{n=1}^N d(n, p_i^\alpha)\right)=
\sum\limits_{i=1} \left(\sum\limits_{\alpha=1}\left\lfloor \frac{N}{p_i^{\alpha}} \right\rfloor\right)=...$$
which is
$$...=\sum\limits_{i=1} \nu_{p_i}(N!)=...$$
in fact
$$...=\sum\limits_{i=1}^{\pi(N)} \nu_{p_i}(N!)$$
Given
$$\frac{n}{p-1}-\log_2(n+1)<\frac{n}{p-1}-\log_p(n+1)\le\nu_p(n!)\le\frac{n}{p-1}$$
we have
$$\sum\limits_{p\leq N}\frac{1}{p-1} - \frac{\pi(N)\log_2(N+1)}{N}<\frac{\sum\limits_{i=1}^{\pi(N)} \nu_{p_i}(N!)}{N}<\sum\limits_{p\leq N}\frac{1}{p-1}$$
Or
$$\sum\limits_{p\leq N}\frac{1}{p} - \frac{\pi(N)\log_2(N+1)}{N}<\frac{\sum\limits_{i=1}^{\pi(N)} \nu_{p_i}(N!)}{N}<\sum\limits_{p\leq N}\frac{1}{p} + \sum\limits_{p\leq N}\frac{1}{p(p-1)}$$
The final result follows from the Prime Number Theorem and the summation of the reciprocals of the primes.
Comment: Prime number theorem is not needed to deduce this asymptotic formula. See my answer
Comment: @TravorLZH I need it in my answer, to deal with $\frac{\pi(N)\log_2(N+1)}{N}$ in LHS.
Comment: You can use the weaker Chebyshev upper bound
Comment: @TravorLZH yep, that will work as well.
Comment: @rtybase Can you please tell how you wrote $\sum_{i=1} v_{p_i}(N!)= \sum_{i=1}^{\pi(N)} v_{p_i}(N!)$? I was not able to deduce them using the link given. Kindly elaborate on it.
Comment: @evan, that is because $$p_{\pi (N)} \leq N < p_{\pi (N)+1}$$ and for any $p> N$ ($p$-prime) we have $\nu_p(N!)=0$.
Answer: By definition, we know
\begin{aligned}
0\le\sum_{n\le N}[\Omega(n)-\omega(n)]
&=\sum_{n\le N}\sum_{p^a\|n,a>1}a\le\sum_{a\ge2}a\sum_{p\le N}\sum_{\substack{n\le N\\p^a|n}}1 \\
&\le\sum_{a\ge2}a\sum_{p\le N}{N\over p^a}\le N\sum_{p\le N}\sum_{a\ge2}{a\over p^a}
\end{aligned}
To evaluate the rightmost sum, we recall the properties of geometric series. That is, for $|z|<1$ there is
$$
{1\over1-z}=1+z+\sum_{r\ge2}z^r
$$
Differentiating on both side, we have
$$
{1\over(1-z)^2}=1+\sum_{r\ge2}rz^{r-1}
$$
Multiplying $z$ on both side gives
$$
\sum_{r\ge2}rz^r={z-z(z^2-2z+1)\over(1-z)^2}={z^2(2-z)\over(1-z)^2}
$$
This indicates that
$$
\sum_{p\le N}\sum_{a\ge2}{a\over p^a}=\sum_{p\le N}{p^{-2}(2-p^{-1})\over(1-p^{-1})^2}\le\sum_{p\le N}{2\over(p-1)^2}
$$
Since the right most sum is convergent, we conclude
$$
\sum_{n\le N}[\Omega(n)-\omega(n)]=\mathcal O(N)
$$
which indicates that
$$
\sum_{n\le N}\Omega(n)=\sum_{n\le N}\omega(n)+\mathcal O(N)\tag1
$$
which converts our problem into a much more convenient one:
\begin{aligned}
\sum_{n\le N}\omega(n)
&=\sum_{n\le N}\sum_{p|n}1=\sum_{p\le N}\sum_{\substack{n\le N\\p|n}}1 \\
&=\sum_{p\le N}\left\lfloor\frac Np\right\rfloor=N\sum_{p\le N}\frac1p+\mathcal O(N)
\end{aligned}
To continue, we summon Mertens' formula (a superior version is presented as Theorem 427 in Hardy & Wright):
$$
\sum_{p\le N}\frac1p=\log\log N+\mathcal O(1)
$$
so that
$$
\sum_{n\le N}\omega(n)=N\log\log N+\mathcal O(N)\tag2
$$
Combining (1) and (2) gives the desired result.
Comment: The symbol means that $p^a$ divides $n$ and $p^{a+1}$ does not.
Comment: It should be $O(n)$, not $\mathcal{O}(n)$. Customarily, $\mathcal{O}$ stands for the sheaf of holomorphic functions, which deeply studied by Oka.
Comment: @Landau I've seen many uses of $\mathcal O$ in literature, and I don't think the use of $\mathcal O$ here would lead to ambiguity.
Comment: @TravorLZH I am not able to understand 1st line of your answer. Can you please tell how did you wrote :$0\leq sum_{n\leq N} [|Omega(n)- \omega(n)|] \leq \sum_{n\leq N} \sum_{p^a |n , a >1 a$ . Kindly elaborate.
Comment: $\Omega(n)=\sum_{p^a\|n}a$ and $\omega(n)=\sum_{p|n}1$, so that's why the difference looks like what's stated.
Comment: @TravorLZH What is the meaning of the symbol $p^a$  2 times divide n ? Can u please tell?
Comment: @TravorLZH I think $\Omega (n) $ should be equal to $\sum_{p^a || n} 1$ not the one you wrote in your previous comment. What do you think?
Comment: Normally, we only sum each $p$ once, so to ensure $\Omega(n)$ counts the $p$ with multiplicities we have to make sure the summand is $a$ when we sum over each $p^a\|n$.


How to override node add template for custom content type?

Question: I have a custom content type named called "circular". For Admin user the "circular" node add form is opening using administration theme (i.e. Seven). But for Authenticated user the node add form is opening using my custom theme. I want to override template of the node add/edit form the custom theme.
I created page--node--add.html.twig in the template folder of the custom theme and used {{ form }} to render the form. But blank page is coming.
How do I fix this?
Comment: I think this is a duplicate of https://drupal.stackexchange.com/questions/231192/what-is-the-twig-template-name-for-a-node-edit-form/308548#308548. See https://drupal.stackexchange.com/a/308548/69482
Answer: This template will be used when a node edit form specifies 'node_edit_form' as its #theme callback. Otherwise, by default, node add/edit forms will be themed by form.html.twig.
Try this on your theme:
<code>use Drupal\Core\Form\FormStateInterface;

function YOURTHEME_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $form['#theme'] = ['node_edit_form'];
}
</code>
After this your theme can read template node-edit-form.html.twig.
https://api.drupal.org/api/drupal/core%21themes%21classy%21templates%21content-edit%21node-edit-form.html.twig/8.2.x
Answer: Great tip, and what about the same but but a specific content type ? I don't want all content types node forms templates to be overwritten. (I'm on Drupal 9)
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://drupal.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://drupal.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/133798)


Difference between scp and sftp

Question: What is the difference between sftp and scp?
Answer: SCP is the abbreviation of 'secure copy', while SFTP stands for 'secure FTP'.
The first is used to copy one or more files, often with known names, from host A to host B, whereas the second is mostly used interactively, analogue to an FTP client. SCP will always work out of the box and has little in the field of tweakable options. SFTP can be used with different backends to present the SFTP service to the user. It would even possible to turn it off, though I haven't tried this.
That's the difference in use.
As far as performance goes: ErikA below links to a wikipedia page which mentions SCP is generally faster than SFTP because of a more efficient algorithm in SCP.
Comment: I think his point was that SFTP is not simply a secured version of the FTP protocol but a different protocol entirely.
Comment: SFTP is not secure FTP, but SSH File Transfer Protocol. Google/Wiki it
Comment: I quote from Wikipedia.org's SFTP entry "In computing, the SSH File Transfer Protocol (**sometimes called Secure File Transfer Protocol or SFTP**)". Emphasis mine. kthxbai.
Answer: sftp is an interactive program used by human in a shell session
scp is mostly an one-liner used in scripts to transfer/copy files
Answer: That's like asking the difference between cp and ftp.
scp lets you remotely copy a file to or from an SSH server. Generally, people only use scp if they are going to recusively upload a folder or upload just one file. There's also the fact that since scp is a one-liner,
sftp is an interactive program that let's you upload files to/from an SSH server. The advantage of using sftp over scp is that if you need to do multiple uploads from or to different directories, you can do it in one session.
Comment: Those are properties of the client programs, not the protocols
Answer: Here's a bit of information on the subject.
Comment: Wikipedia removed the section as inaccurate, in case anyone is still interested in this topic.
Answer: Security:
Both SFTP and SCP provide same security features for they are based on the secure shell protocol.
such as Secure Remote Logins, Secure File Transfer, Secure Remote Command Execution, Keys and Agents,
Access Control and  Port Forwarding
Functionality:
SCP can tranfer files and non-interactive. Therefore, SCP transfer cannot be canceled without terminating the
session. SFTP is interactive. SFTP capabilties includes directory listings, remote directories and files removal,
creates directories and files and etc. SFTP can be used in batch process. SFTP can be used for multiple uploads
from or to different directories in one session.
Speed:
SCP is faster for it confirms recieved packets whilst SFTP has to acknowledge every packet.
Resume file transfer:
SCP can not resume an interrupted file transfer whereas SFTP can with -a of the get command to resume
partial transfers of existing files
Comment: I disagree. On my home network SFTP is about 35x faster.

Difference between scp and sftp


Get contents of div up to a certain point

Question: I'm grabbing all the paragraph tags using the PHP Simple HTML DOM Parser with the following code:
// Product Description
$html = file_get_html('http://domain.local/index.html');
$contents = strip_tags($html->find('div[class=product-details] p'));

How can I say grab X amount of paragraphs until it hits the first ul?

  Paragraph 1

  Paragraph 2

  Paragraph 3

    List item 1

    List item 2

  Quote 1

  Quote 2

  Quote 3

  Paragraph 4

  Paragraph 5

Comment: how about using `substr()` and `strpos()` on the content?
Comment: @nandal How so? Just to note the amount of paragraphs is variable.
Comment: can you paste the url?
Comment: @nandal It's a local site sorry, I would otherwise
Comment: http://php.net/manual/en/function.strip-tags.php
Answer: You can use the following code as per requirements mentioned:-
<?php

$html = file_get_html('http://domain.local/index.html');
$detailTags =  $html->find('div[class=product-details] *');
$contents = "";
foreach ($detailTags as $detailTag){
    // these condition will check if tag is not
 or it's
 to break the loop.
    if (strpos($detailTag, '
') === 0 && strpos($detailTag, '
') !== 0) {
        break;
    }
    $contents .= strip_tags($detailTag);
}
// contents will contain the output required.
echo $contents;

?>

OUTPUT:-
  Paragraph 1    Paragraph 2    Paragraph 3

Comment: As another fallback, can I break it if it hits a `` as well like this `if (strpos($detailTag, '') === 0 && strpos($detailTag, '') !== 0 && strpos($detailTag, '') === 0) {`
Answer: EDIT: Nandal's code will work for you because it will not force you to change the library.
If you don't want to be dependent upon 3rd party library then you can use PHP's DOM Document feature for which you would need to enable the extension.
You can look into the below code which prints the paragraphs until you hit any other tag:
<?php

$html = new DOMDocument();
$html->loadHTML("
Paragraph 1

  Paragraph 2

  Paragraph 3

    List item 1

    List item 2

  Quote 1

  Quote 2

  Quote 3

 Paragraph 4

  Paragraph 5
");

$xpath = new DOMXPath($html);
$nodes = $xpath->query('/html/body//*');

foreach($nodes as $node) {
    if($node->nodeName != "p") {
        break;
    }
    print $node -> nodeValue . "\n";
}


Trouble With Proving a Remark of Hatcher's Regarding Characteristic Maps of CW Complexes

Question: In the third paragraph on pg. 7 of Hatcher's Algebraic Topology there is the definition of characteristic maps of a CW complex (the definition of a CW complex can be found on pg. 5.)
Just after defining a characteristic maps, Hatcher writes:

The restriction of a characteristic map $\Phi_{\alpha}:D^n_\alpha\to X$ to the interior of $D^n_\alpha$ is a homeomorphism onto $e^n_\alpha$ (where $e^n_\alpha$ is the image of $\text{Int}(D^n_\alpha)$ under $\Phi_\alpha$).

In, other words, the restriction of $\Phi_\alpha$ to the interior of $D^n_\alpha$ is an embedding.
I was able to prove this by assuming additionally that $X$ is Hausdorff.
Here is the argument I have:

Lemma. Let $B^n$ be the open unit ball in $\mathbf R^n$.
  Let $X$ be a Hausdorff topological space and $f:D^n\to X$ be a continuous map such that
  i) $f$ is injective on $B^n$, and
  ii) $f(S^{n-1})\cap f(B^n)$ is empty.
  Then $f|_{B^n}:B^n\to X$ is a topological embedding.

Proof. Without loss of generality we may assume that $f$ is surjective.
We have the following diagram:

where by $D^n/f$ we mean the quotient space of $D^n$ formed by the fibres of $f$.
We need to show that $f|_{B^n}:B^n\to X$ is an embedding.
Since $f$ is a surjective continuous map from a compact space to a Hausdorff space, we know that $f$ is a quotient map.
Therefore $\bar f$ is a homeomorphism.
In the light of this, it suffices to prove that $\pi|_{B^n}:B^n\to \pi(B^n)$ is a homeomorphism.
To this end, note that since $f$ is injective on $B^n$, we have $\pi|_{B^n}:B^n\to \pi(B^n)$ is bijective.
So all that remains to show is that $\pi|_{B^n}$ is an open map.
To this end, let $U$ be open in $B^n$.
We claim that $\pi^{-1}(\pi(U))=U$.
One containment is obvious.
For the reverse containment let $x\in \pi^{-1}(\pi(U))$.
Then $\pi(x)\in \pi(U)$, and thus $\bar f\circ \pi\in \bar f\circ \pi(B^n)$, giving $f(x)\in f(B^n)$.
Using (ii) here leads to the conclusion that $x\in B^n$.
But since $f$ is injective on $B^n$, we further deduce that $x\in U$.
So we have $U=\pi^{-1}(\pi(U))$.
From this we infer that $\pi(U)$ is open in $D^n/f$ and is therefore open in $\pi(B^n)$ too.
Remark. The condition (ii) is necessary in the hypothesis of the above proposition for result to hold.
For otherwise we have the figure-eight curve is would serve as a counterexample.
It is clear that a characteristic map satisfies the hypothesis of the above lemma and thus given an embedding when restricted to the interior of the disc.

Question. How do we prove that the restriction of a characteristic map to the interior of the disc is an embedding without assuming that $X$ is a Hausdorff space.
Comment: CW complexes are Hausdorff. I don't know a reference, but here's how I would go about writing down a proof. First, find a proof that a CW complex $X$ is locally contractible: every $x \in X$ has a neighborhood basis of contractible open subsets. It's a pretty concrete construction, building each neighborhood up inductively as the union of its intersections with the skeleta. Adapt that proof: using the details of the construction, check that if $x \ne y$ then there exist disjoint members $U_x,U_y$ of their neighborhood bases. I
Answer: We have the following general fact
Assume $X$ is space, and $f:A\to Y$ is a map from the subspace $A$ of $X$ to a space $Y$. We have the following pushout square.

Then if $A$ is closed (open) in $X$, the restriction $g:X\setminus A \to Z$ of $F$ is a closed (open) embedding.
You already gave a proof for the case that $A$ is closed (by replacing the pair ($D^n,S^{n-1})$  in your proof with a general $(X,A)$), and for the case of an open $A$ simply switch the terms open and closed in the proof.
Now the $n$-skeleton $X^n$ is constructed as a pushout

where $\varphi$ is the union of all attaching maps $\varphi_\alpha$. Since $\coprod S_\alpha^{n-1}$ is closed in $\coprod D_\alpha^n$, it follows that $\Phi$ restricts on each open ball $B_\alpha^n$ to an embedding.


How to bind children of ItemsControl on a custom user control to a 2D array WPF C#?

Question: I have a custom user control in XAML that creates a ItemsControl which ItemsPanel is a 15 * 15 uniform grid. The ItemsControl is then populated with Cells on startup.
<UserControl x:Class="Words.GameBoard"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:Words="clr-namespace:Words"
         xmlns:Cell="Words.CellCollection"
         xmlns:CellTile="Words.Cell"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
    <Words:CellCollection x:Key="CellCollectionData">
    </Words:CellCollection>

</UserControl.Resources>
<ItemsControl Name="BoardControl">
</ItemsControl>

The control is added to the MainWindow like this
            <clr:GameBoard>
            </clr:GameBoard>

How do i bind the Items of a ItemsControl to a Array? I don't need Observables and stuff, I just want the Items to refresh when I click a button. Is this possible? I've very new to both C# and XAML
Thanks
Answer: You need to set the ItemsSource on your ItemsControl to bind the array like this:
<ItemsControl Name="BoardControl" ItemsSource={DynamicResource CellCollectionData} />

I am assuming you wanted the CellCollectionData bound.  Typically, however, I would expect the data to be in the DataContext, in which case you would use:
<ItemsControl Name="BoardControl" ItemsSource={Binding} />

(if the UserControl's DataContext was set to the array)
or
<ItemsControl Name="BoardControl" ItemsSource={Binding MyArray} />

(if the UserControl's DataContext was a class that contained a property that returned the array)
While you are learning and testing, I would suggest converting the ItemsControl to a ListBox, so you can see that items are actually added (by clicking on a selectable item).  Once you get the look right, you can change it back to an ItemsControl (which doesn't allow selecting an item).
Answer: You can bind it to array, set the property ItemsSource="{Binding Path=ArrayProperty}"
I suppose you have a model with an array connected to this view.


Transferring duplicates in column to another page using a collection

Question: I am trying to move items within a column onto another page if a duplicate with specific criteria.
My code stops at my second if statement and I can't figure out how to search the collection with my new rows value. I feel like I almost got it but don't know how to fix it.
Sub duplicates ()

Dim tasks as collection
Set tasks = new collection

Dim row, m as long
Dim task as variant

Row = 9
M= 3

 Do until trim(sheets("itemreport").range("k" & row).value) =""

 If trim(sheets("itemreport").range("f" & row).value) = "credited"     then

  If trim(sheets("itemreport").range("k" & row).value = tasks(item)      then 'Part I am having trouble on
       Sheets("credited").range("r" & m) =  trim(sheets("itemreport").range("k" & row).value)
       M = m +1

       Else: tasks.add (trim(sheets("itemreport").range("k" & row).value)
End if
End if

Row = row + 1

Loop

Comment: It's hard to imagine that you've posted compiled code here. If it had compiled, your function, property and variables would have auto-corrected to the correct case - `trim` would become `Trim`, `M = m +1` would become `m = m + 1`, etc. I'm not convinced by those inverted commas either. If you've pasted this from web code then try compiling it first. Also, use `Option Explicit` at the top of your module and it will throw some compile errors - eg (what is `item`). If you could fix that, then we can probably help with the code. I'd also look up error handling if a collection item does not exist.
Comment: Completely agree with @Ambie's suggestions..there are multiple efficient ways to achieve what may be your goal. However posting answer by modifying your code  to working condition (you are basically missing a 2nd loop for testing all the values of the collection)
Comment: @ambie you are right, it does autocorrect itself - the reason mine wasn't is because I had typed it up on my phone while referencing my computer.  So I always get typos for stuff like that and have to continuously go back and make sure there's four spaces on each line.  Item it what I was having problems with - which is why I posted.
Answer: May Try
Sub duplicates()
Dim Tasks As Collection
Set Tasks = New Collection
Dim Rw, m As Long, i As Long
Dim Task As Variant
Dim WsSrc As Worksheet, WsTrg As Worksheet
Dim DupFound As Boolean
Set WsSrc = ThisWorkbook.Sheets("itemreport")
Set WsTrg = ThisWorkbook.Sheets("credited")

Rw = 9
m = 3
With WsSrc
Do Until Trim(.Range("k" & Rw).Value) = ""
    If Trim(.Range("f" & Rw).Value) = "credited" Then
        DupFound = False
            For i = 1 To Tasks.Count
                If Trim(.Range("k" & Rw).Value) = Tasks(i) Then  'Part I am having trouble on
                WsTrg.Range("r" & m) = Trim(.Range("k" & Rw).Value)
                m = m + 1
                DupFound = True
                Exit For
                End If
            Next i
            If DupFound = False Then
            Tasks.Add Trim(.Range("k" & Rw).Value)
            End If
     End If
Rw = Rw + 1
Loop
End With
End Sub


Getting average of selected rows for each column pandas

Question: I want to be able to get the average of the last 4 rows that are in 'Stage' 2, for each column.
Sample Data

Currently I am using av = df.loc[df['Stage'] == 2, 'Vout'].mean() but this gives me the average for the entire column. So for the column vout I am getting the entire columns average value, when I just want the columns average value to be the average of the last 4 rows that are in stage 2.
Comment: `df.loc[df['Stage'].eq(2),'Vout'].tail(4).mean()`?
Answer: @not_speshal has kindly answered my question in the comments.
The solution is to use tail to select the last 4 rows after loc:
df.loc[df['Stage'].eq(2), 'Vout'].tail(4).mean()


Agent Side checkout reverting to Server Side Checkout for Perforce Stream Depot

Question: Running 2020.1.1 (build 78657)
I have a VCS root for a Perforce Stream Depot (with the option to Enable feature branches support).
I also have several builds with Version Control Settings having VCS checkoutmode set to Prefer to checkout files on agent.
However, I am seeing these messages in the build logs:
[Updating sources] Will use server side checkout: Checkout rules are not supported for vcs root 'StreamRoot'. Details: Perforce stream checkout on agent supports only one single include rule like . => sub/directory, requested rule: +:area/functions/functionsA => .
This message is confusing to me, because I only have a single checkout rule (as shown in the log):
+:area/functions/functionsA => .
I would appreciate any insight from the community.
Answer: I think the issue here is the message isn't so descriptive. I've also come across this problem, and seems it only works when specifying a single rule that applies to the whole stream, e.g. +:. => some/path


Using jQuery, how do I pinpoint the specific class out of several

Question: Thought this would be an easy script, but I am stumbling on something
Reference attached image.
See #panels-ipe-paneid-1436 {#1} from there
I want to add a class to {#2}, the ".panel-separator" and ONLY that "panel-separator"
Then I will do a .css({"font-family":"AGaramondPro-Bold","font-size": "25px","padding-bottom": "20px;"}); on the combined classes
When I do get to add a class to next occurrence of "panel-separator" it adds the new class to several, if not to all, of the occurrences of "panel-separator".
I have used next() and prev() and parent().find() and closest(), there is something, obviously, that I am missing.
This to me, should work, but no go:
jQuery('#panels-ipe-paneid-1436').closest('.panel-separator').addClass( "newClsHere" );

Could someone assist with ->Using jQuery, how  do I pinpoint the specific "panel-separator" that occurs after #panels-ipe-paneid-1436
Comment: You repeatedly mention ".parent-separator" but I don't see it in your image. What about `$('#panels-ipe-paneid-1436 > div.panel-separator').css({"font-family":"AGaramondPro-Bold","font-size": "25px","padding-bottom": "20px;"})`?
Comment: please show your code, how you are trying to do so.
Comment: so sorry j08691 - i meant "panel-separator", that is the #2 shown in the image.
Comment: Umer Hayyat : here are some of the scripts i tried:
jQuery('#panels-ipe-paneid-1436').parent().find( '.panel-separator' ).addClass( "newClsHere" );

 jQuery('#panels-ipe-paneid-1436').parent().find( '.panel-separator' ).css('margin-bottom', '100px !important');

 jQuery('#panels-ipe-paneid-1436').next( '.panel-separator' ).addClass( "newClsHere" );

jQuery('#panels-ipe-paneid-1436').parent().next( '.panel-separator' ).addClass( "newClsHere" );
Comment: Did you try my suggestion? Also, `.closest()` looks UP the DOM, not down.
Comment: HI j08691 - I did try your, but that did not work.  I could see in the DOM, that something happened, but the css was not applied to the panel-separator class div
Answer: Finally, got this thing to work.  See code below.
jQuery('#panels-ipe-paneid-1436').next('.panel-separator').addClass( "new-get-info-cls-here" );
jQuery('.panel-separator.new-get-info-cls-here').css('height', '1px');

I guess it was just better to do it in two steps


Including random effects in prediction with Linear Mixed Model

Question: I have a question regarding Linear Mixed Modeling using statsmodels.
The first picture below shows the mixed model I fitted. My dummy dataset only contains one variable, and multiple groups. I would like to predict using not only the fixed intercept and coefficient (see results Intercept and A), but also the random effects of the groups. It seems like it is possible in R, but not using Python (https://www.rdocumentation.org/packages/lme4/versions/1.1-23/topics/predict.merMod)
The second picture shows the predict functionality and some dummy data. As you can see, the prediction is a result of the a combination of only the fixed effects.
Or would it be weird to fit a linear mixed model and also use the random effects in prediction?
Thanks in advance!
Answer: There are situations where it would make sense to include the predicted random effects (BLUPs) in a prediction.  If you have observations on a group (e.g. a person) and you want to make predictions about additional responses from the same group, then you would generally want to include the BLUP.
This is possible in statsmodels, as illustrated below.  We should add an option to make this easier.  For now, you have to do it manually, as shown below.
import pandas as pd
import statsmodels.api as sm
import numpy as np

# Simulate data for illustration
group_size = 5
n_groups = 100
x1 = np.random.normal(size=group_size*n_groups)
x2 = np.random.normal(size=group_size*n_groups)
u = np.kron(np.random.normal(size=n_groups), np.ones(group_size))
g = np.kron(np.arange(n_groups), np.ones(group_size))
e = np.random.normal(size=group_size*n_groups)
y = x1 - x2 + u + e

# Fit a multilevel model
df = pd.DataFrame({"y":y, "x1":x1, "x2":x2, "g":g})
model = sm.MixedLM.from_formula("y ~ x1 + x2", groups="g", data=df)
result = model.fit()

# The BLUPs
re = result.random_effects

# Multiply each BLUP by the random effects design matrix for one group
rex = [np.dot(model.exog_re_li[j], re[k]) for (j, k) in enumerate(model.group_labels)]

# Add the fixed and random terms to get the overall prediction
rex = np.concatenate(rex)
yp = result.fittedvalues + rex

Comment: Thank you! We have implemented this approach. However, we cannot figure out what exog_re_li exactly does. Do you have any source on this? Also, we noticed that the current approach shows in sample predictions. Would it be possible to use this for out of sample prediction also, in case you predict for a group that was available during training? And would it still make sense to include this?
Comment: exog_re_li is a list containing the design matrices for the random effects.  The responses for group `i` have an additive term of the form dot(exog_re_li[i], u), where u is distributed according to the random effects distribution.  I think exog_re_li[i] is often called Z_i in the literature.
Comment: The only reason you can predict the random effect for one block is because you have partial information about that block.  If you don't have any data at all from a block, then you should predict its values using the fixed effects only.  A typical example would be if you were predicting current blood pressure based on each subject's age, and also blood pressure values recorded in the past.  If you want to use age and past blood pressure values for prediction, you should use the fixed effects and the BLUP.  If you only want to use age, you should predict based on fixed effects only.
Comment: It is true that marginally, the random effects only relate to the variance and covariance of your responses, not to the mean values.  However if you have access to some data on each block, then using the covariance implied by the random effects allows you to do a better job by predicting conditionally on the partially-observed data, compared to what you would by predicting using the fixed effects alone.  If you don't want to use this partial information when making predictions, then most of the advantages of using mixed models are lost.
Comment: How would I get the prediction for the random effect but in R if may I ask ?
Answer: To make predictions purely on fixed effects, you can do
md.predict(mdf.fe_params, exog=random_df)

To make predictions on random effects, you can just change the parameters with specifying the particular group name (e.g. "1.5")
md.predict(mdf.random_effects["1.5"], exog=random_df).

I assume the order of features in the test data should follow the same order as what you give as the model's parameters. You can add them together to get the prediction specifically for a group.
Answer: I think the simple answer is "yes it would be weird to use random effects for prediction." Random effects in a linear model only effect the variance of your model, not the coefficients. So random effects will change the size of your confidence intervals etc, but not predictions. So if you include random effects in your model, it may change the significance of certain variables, among other things, but it won't change the prediction values.


Is it properly to include a third-party php library via composer without creating drupal module for it?

Question: I want to ask a theoretical question.
For example, there is a project on Drupal 8. Working on the project, developers find a php library on the GitHub, include it via Composer and use it in their modules.
They don't create drupal 8 module which would present the library and contain files of the library, copied from GitHub before. And to use the library it would be necessary to install the module.
Is it the correct way to attach an external php library via composer and afterwards use it without creating a module for Drupal 8 for this library ?
Comment: yes, that's how composer works.
Answer: Sure, you can do that on a project.
But you're probably going to write code somewhere to actually integrate that into Drupal and expose it somehow, and that will be in a module (or theme). But especially if that's a custom module that is just used for that site, you kind of have to add it to the project composer.json as composer doesn't include composer.json of moules that aren't actually added themself with composer (excluding solutions like merge plugin)
Comment: No, working on Drupal 8 project I have found a php-library, which can solve my tasks. And I wrote it in the composer.json as "required" and atter it updated the composer.
Now I use classes from the library in my project. I'm interested, is this way correct ?
Comment: As you said, you use those classes somewhere, which has to be in a module or theme. Which, as I said, is perfectly fine


Difference between expect and expect_any_instance_of

Question: I have method in my controller that looks like this:
def resend_confirmation
  @current_user.send_confirmation_instructions

  render json: nil, status: 200
end

I've written following spec for that method:
require 'rails_helper'

describe 'POST /api/v1/users/:id/resend_confirmation' do
  let!(:current_user) { create(:user) }

  before do
    expect(current_user).to receive(:send_confirmation_instructions)

    post resend_confirmation_api_v1_user_path(current_user),
         headers: http_authorization_header(current_user)
  end

  describe 'response' do
    it 'is empty' do
      expect(response.body).to eq 'null'
    end
  end

  it 'returns 200 http status code' do
    expect(response.status).to eq 200
  end
end

But the problem is that this spec is not passing. This line is failing:
expect(current_user).to receive(:send_confirmation_instructions)

when I change that to
expect_any_instance_of(User).to receive(:send_confirmation_instructions)

everything works pretty well. Could someone explain me why spec with expect syntax is not passing?
EDIT:
This how error looks:
Failures:

  1) POST /api/v1/users/:id/resend_confirmation returns 200 http status code
     Failure/Error: expect(current_user).to receive(:send_confirmation_instructions)

       (#<User id: 4175, email: "email@example.com", date_of_birth: "1990-01-01", created_at: "2016-07-18 06:56:52", updated_at: "2016-07-18 06:56:52", sex: "male", touch_id_enabled: false, first_name: "Test", last_name: "User", athena_health_patient_id: nil, photo_url: nil, admin: false, one_signal_player_id: "1", phone_number: nil, state: nil, address: nil, city: nil, zip_code: nil, phone_number_confirmed: false>).send_confirmation_instructions(*(any args))
           expected: 1 time with any arguments
           received: 0 times with any arguments
     # ./spec/requests/api/v1/user/resend_confirmation_spec.rb:7:in `block (2 levels) in <top (required)>'

  2) POST /api/v1/users/:id/resend_confirmation response is empty
     Failure/Error: expect(current_user).to receive(:send_confirmation_instructions)

       (#<User id: 4176, email: "email@example.com", date_of_birth: "1990-01-01", created_at: "2016-07-18 06:56:53", updated_at: "2016-07-18 06:56:53", sex: "male", touch_id_enabled: false, first_name: "Test", last_name: "User", athena_health_patient_id: nil, photo_url: nil, admin: false, one_signal_player_id: "2", phone_number: nil, state: nil, address: nil, city: nil, zip_code: nil, phone_number_confirmed: false>).send_confirmation_instructions(*(any args))
           expected: 1 time with any arguments
           received: 0 times with any arguments
     # ./spec/requests/api/v1/user/resend_confirmation_spec.rb:7:in `block (2 levels) in <top (required)>'

Comment: I've updated my post.
Comment: can you try expect(User.find(current_user.id)).to receive(:send_confirmation_instructions)?
Answer: expects(...) sets the expectation on a particular instance. When the POST request is executed, your app will try to identify the user referenced in your request information, and will create an instance that represents it.
However, that instance is not the same you prepared in your test. It indeed references the same user object, but it's not the same Ruby object.
Therefore, inside your tests, the current_user that is used is not the one you set the expectations on.
Using expect_any_instance_of instead affects every instance of user created, hence also the one that will be created to satisfy the request.
Comment: Thank you. This is exactly what was happening to me. Verified it by testing `foo.object_id` in the spec and also within the countroller.


Find graph links given random groups of node pairs

Question: I have a large dataset where each item contains a small set of random pairs of connected nodes (say 3), however I do not know the links. For example, you might be given ABC & XYZ, but you don't know if A connects to X, Y, or Z, etc. But you do know that there are three pairs, each with distinct nodes. The correct links in this case might be A->X, B->Z, C->Y.
Now if each node can only form one link, finding the links becomes trivial, by simply finding the highest correlation between nodes over time. My problem is that each node can form links with multiple nodes.
Is there any algorithm for finding the adjacency matrix given data in this way? Or does anyone have any suggestions for how to solve this?
Comment: +1 for the question, seems like its impossible to solve this exactly, since a complete graph is going to match any observations. So probably just assume a link between points with high correlations?
Comment: I have tried simply looking for high correlations, but that can yield incorrect edges in certain cases. I have improved it a bit by penalising edge probabilities when neighbours report high probabilities themselves. If I get a solid solution working, i'll post more details.
Answer: You might try expectation maximization to solve this problem. I am not totaly sure about the details but I am confident that is does capture the specifics of the problem. It can deal with the idea that only one connection between the possible pairs of connected nodes (e.g. AX, AY or AZ) explains the data.
The maximization step calculates the parameters of the model (probabilistic adjacency matrix) that best explain the data. You could model the data as $X_{ijk}$ where $X_{ijk} = 1$ if and only if the $k$'th pair possibly connects $i$ and $j$. The adjacency matrix should then maximize the probability that each $i$ in pair $k$ is at connected to a $j$ (marginalize over $j$).
The expectation step calculates the likelihood of the data given the model. It something like:
$$
p(X | A) = \prod_k \prod_i \sum_j p(X_{ijk} | A)
$$
Probably you need to do a lot of thinking to get this to work.
Comment: I was going to write my attempt should no answers arrive, but I essentially ended up doing exactly what you have written above. My attempt raises the probability of correlated edges while penalising edges whose neighbours have higher probabilities. The devil is still in the details, but I'll mark this as correct. Thanks.


Projetos com APIs síncronas e assíncronas

Question: Estou desenvolvendo um pequeno projeto e possuo, por enquanto, duas entidades:

Produto e Cliente

A API de produto está assíncrona (com Task e async) e a API de cliente é síncrona.
Gostaria de saber se existe algum problema em utilizar essas duas abordagens no mesmo projeto? Quais os problemas, se existirem?
Outra dúvida também é quando é realmente recomendado utilizar APIs assíncronas nos projetos?
Comment: Acredito que não, você tem o código pra verificar .
Answer: Em princípio nenhum problema. Claro que no momento que elas se inter-relacionem o síncrono sempre prevalecerá e a parte síncrona causará espera naquele ponto, mas se estiver dentro de algo sendo chamado assincronamente essa parte ainda manterá concorrência. Se você chamar sincronamente um código em um método assíncrono esta chamada será síncrona, e só uma chamada a este método chamador será assíncrono, oque pode não ser relevante.
Lembre-se que async é útil para IO, então o último caso que citei não deve ter vantagem em condições normais. A operação de IO tem que ser originalmente assíncrona para ter ganhos. Se a execução for muito rápida não compensa usar um mecanismo tão pesado. Estabelece-se o mínimo de 50ms de tempo de execução (não é receita de bolo), o que é relativamente raro ter operações assim. Somente com grandes volumes ou algum IO muito lento é que dará ganho.
Em processamento ganha-se concorrência ou até paralelismo com thread e não com async.
Respondi com mais detalhes em outras perguntas:

Quando usar método assíncronos ou síncronos?
É sempre garantido que uma aplicação com múltiplas threads rode mais rápido que usando uma única thread?
O que são métodos Async?
Em C#, para que serve a palavra chave await?
Existem diferenças entre os termos Thread, Multithread, Async e Await?
Qual a diferença entre os async, multithreading, paralelismo e concorrência?
A palavra-chave "async" realmente faz o método assíncrono?
Diferença entre Task e Thread

Coloquei no GitHub para referência futura.
Comment: A resposta é interessante porque está correcta para .NET Core mas nao necessáriamente para .Net Framewrok (estou a falar dos deadlocks que podem ocorrer devido aos contextos de sincronizacao...). https://stackoverflow.com/q/15021304 https://stackoverflow.com/q/48606313
Comment: @BrunoCosta No geral não vejo diferença, em código específico pode ser, mas a pergunta não é específica. É possível ficar ruim em qualquer um deles, esse mecanismo é bem capcioso.


Collect remote logfiles and make them available via Webinterface

Question: I got several windows servers which run multiple instances of a software that produces logfiles. We are talking about 5-10MB per hour per server.
I want to collect these logs at a central server (in nearly realtime) and present them to other users via a web interface after authentication.
I have looked at Splunk but that seems be overkill and also is not free for multiple user accounts.
So I'd need a sync mechanism (perferably running as client on all servers) which pushes the log changes to a central server which collects these logs and makes them available via web interface.
Answer: In my environment, I just set up Graylog2 as an aggregation point/browser interface, and nxlog as a forwarding agent to read in from log files and the system event log and forward them in GELF format to the Graylog2 server. nxlog can be a little finicky, but generally works pretty well. It's also available for Linux. Graylog2 does some nifty things like indexing logs into streams based on configurable search criteria and providing basic alerting on certain kinds of log messages.
You might also consider logstash. If you go this route, Kibana is a much better web interface than the one Logstash ships with.
Comment: From my experience, logstash is an awesome tool on it's own. I haven't used Kibana, but it looks to improve the interface considerably.
Answer: This is verging on a shopping question, so I'll keep the response vague
syslog-ng has a myriad of web interfaces - you'll need to evaluate which suit your needs best.


o que significa o "string" no CSS?

Question: Olá gostaria de saber exatamente o que significa o termo string no CSS e de que maneira ele é usado o CSS?
Comment: Em qualquer linguagem, uma string é um texto (pelo menos nunca ouvi falar de uma que tivesse um significado diferente), geralmente delimitado por `'` ou `"`. Se quer um exemplo: `background: url('caminho/minha imagem.png');` ou `content: ' uma string'`
Comment: Poderia [edit] e dar o contexto de onde viu o termo sendo usado? Seria melhor para garantir que as respostas se apliquem ao que originou de fato a dúvida.
Comment: olá @GuilhermeCostamilam então pelo que eu entendi  string é a palavra que fika entre as " aspas"  'tô certo ? '
Comment: Sim, pelo menos na maioria das linguagens. Algumas tem outras opções, por exemplo, no javascript `"Isso é uma string"`, `'isso também'` `\`e isso também\``, essa última permitindo interpolação
Comment: Essa é uma explicação simples, além de um texto, uma String é tipo de variável, que na verdade é uma classe. Mas isso não se aplica no CSS eu acredito
Comment: obrigado cara ! @GuilhermeCostamilam
Comment: O tipo de dados  é composto de qualquer número de caracteres cercados por aspas duplas ( " ) ou simples ( ' ).
Comment: @Bacco como vocÊ sugere ? sobre a  dição da pergunta ?
Comment: Talvez por um trecho e um link do tipo "Li no site tal (linkado para o site, se for o caso) essa frase: ......(insira aqui).... Nesse contexto, o que significa a expresão _string_?" -
Answer: O tipo de dados CSS string representa uma sequência de caracteres. As cadeias de caracteres são usadas em várias propriedades CSS, como content, font-family, e quotes.
Sintaxe:
O tipo de dados  é composto de qualquer número de caracteres Unicode cercados por aspas duplas (") ou simples (').
Exemplos:
/ * Strings simples * /
"Esta string é marcada com aspas duplas."
'Esta cadeia é marcada por aspas simples.'

/ * Escapando caracteres * /
"Esta é uma string com \" uma aspa dupla com escape. "
"Esta string também tem \ 22 uma aspa dupla escapada."
'Esta é uma string com \' uma aspas simples com escape. '
'Esta cadeia também tem \ 27 uma cota simples de escape.'
"Esta é uma string com \\ uma barra invertida com escape."

/ * Nova linha em uma string * /
"Esta string tem uma quebra de \ Aline."

/ * String abrangendo duas linhas de código (essas duas seqüências terão saída idêntica) * /
"Um muito longo \
corda impressionante "
"Uma string realmente longa e impressionante"

Exemplo de uso com a propriedade <content>:
/* Valores <string> com caracteres especiais devem ser escritos */
/* com escape Unicode, por exemplo \00A0 para   */
content: "prefixo";

/* Valores <url> */
content: url("http://www.example.com/test.png");

A propriedade CSS content é usada com os pseudoelementos ::before e ::after para gerar conteúdo em um elemento. Objetos inseridos usando a propriedade content são elementos substituídos anônimos.

o que significa o "string" no CSS?


Show that if $X\sim\text{Pois}(\theta)$, then $I(\theta;X) = 1/\theta$.

Question: The Fisher information matrix $I(\theta;X)$ about $\theta$ based on $X$ is defined as the matrix with elements $$I_{i,j}(\theta;X) = \operatorname{Cov}_\theta\bigg(\frac{\partial}{\partial \theta_i}\log f_X(X\mid\theta), \frac{\partial}{\partial\theta_i}\log f_X(X\mid \theta) \bigg).$$
Exercise: Let $X\sim \text{Pois}(\theta)$. Show that $I(\theta;X) = 1/\theta$.
What I've tried: If I'm not mistaken then $\dfrac{\partial}{\partial \theta_i} \log f_X(X \mid \theta) = \dfrac{x_i}{\theta} + \log e$. The Fisher information matrix (a $1\times 1$ matrix in this example) would be given by $\operatorname{Cov}_\theta\left(\dfrac{x_i} \theta + \log e, \dfrac{x_i} \theta + \log e\right)$. We know that $\operatorname{Cov}_\theta\left(\dfrac{x_i} \theta + \log e, \dfrac{x_i}{\theta} + \log e\right) = \operatorname{Var}_\theta\left(\dfrac{x_i}\theta + \log e\right) = \operatorname{Var}_\theta \left(\dfrac{x_i}{\theta}\right) = x_i^2 \operatorname{Var}_\theta \left(\dfrac 1 \theta \right).$ Obviously I'm doing something wrong as the $x_i^2$ before the variance is a problem. Besides that, I'm not sure if I can calculate $\operatorname{Var}_\theta\left(\dfrac 1
 \theta \right)$.
Question: How do I show that $I(\theta;X) = 1/\theta$?
Thanks in advance!
Comment: $\operatorname{Var}_\theta \left(\dfrac{x_i}{\theta}\right) = x_i^2 \operatorname{Var}_\theta \left(\dfrac 1 \theta \right)$ doesn't make sense. You need $\operatorname{Var}_\theta \left(\dfrac{x_i}{\theta}\right) = \dfrac 1 {\theta^2} \operatorname{Var}_\theta (x_i). \qquad$
Comment: @MichaelHardy Why is that so? It's the variance w.r.t. $\theta$ right? Don't we use $\text{Var}_X$ so show that the variance is to be taken w.r.t. $X$?
Comment: $\theta$ is a parameter and so it is just a constant. The notation $E_\theta$ or $\operatorname{Var}_\theta$ just lists the relevant parameter(s) in the subscript. The random quantities are still $X$ and all things derived from it.
Comment: @KimJongUn What would relevant mean in this sense? I'd say it's rather confusing. When taking the expectation $\operatorname{E}_X$ we mean that we take the expectation wrt $X$ right?
Comment: @titusAdam : No. I don't take expected values or variances "with respect to" anything. Rather $\operatorname{Var}_\theta$ means the variance given that the value of the parameter is $\theta. \qquad$
Comment: @MichaelHardy Well it's clear now, so thank you! I do find this part of the notation quite clumsy though. It doesn't seem to be uncommon to take expected values or variances "with respect to" something: https://stats.stackexchange.com/questions/72613/subscript-notation-in-expectations
Comment: @titusAdam : I see that from time to time and I've seen it in Wikipedia articles, but it's a mistake. One _could_ speak of expected values or variances "with respect to" particular probability distributions, but that's another matter: $\displaystyle \operatorname E(X) = \int_\Omega X(\omega)\, P(d\omega). \qquad$
Comment: @titusAdam : Notice what the _answer_ says, to the question you linked to.
Comment: @MichaelHardy I did!
Answer: The mistake is in the last step:
$$
\operatorname{Var}(x_i/\theta) {{}\color{red}={}} x_i^2\operatorname{Var}(1/\theta).
$$
Instead, it should be
$$
\operatorname{Var}(x_i/\theta)=\operatorname{Var}(x_i)/\theta^2=\theta/\theta^2=1/\theta.
$$
Comment: When you used \text{Var} instead of \operatorname{Var} then you don't get proper spacing in things like $3\operatorname{Var}(X)$ or $3\operatorname{Var} X.$ Instead you see $3\text{Var}(X)$ or $3\text{Var} X.$ I edited accordingly. $\qquad$
Comment: @MichaelHardy Thanks Mike. Glad to learn something new.


10GBASE-T shielded cable switch-to-server connection

Question: I'm venturing for the first time into the 10 gigabit (over copper) realm. Likewise, I have never worked with shielded CAT-5/6 cables previously. From my own research, I understand the types and benefits of shielding when it comes to long runs of network cable, such as between a patch panel and a wall jack in an office.
I'm less clear about the use of shielded patch cables (<15ft), particularly when the cable is connected directly from a server to a switch with no patch panel in between (i.e. nothing to ground the cable). This will be my situation when we purchase a few Dell PowerConnect 8164 switches, install them at the top of our server racks (facing the rear), and install Intel X540-T2 NICs in the servers.
Here's what I'm trying to figure out:

Is there any benefit in using Cat-6A over regular Cat-6 stranded patch cables?
Is there any benefit in using shielded (e.g. S/FTP) cables? I know this is related to EMI and some other environmental factors, but I have no way of measuring this.
When a shielded cable is connected directly from the server to the switch, are there some additional electrical requirements that one or both sides must support?

Thanks!
Answer: A shielded cable main purposes are:

To make sure that any electrical discharge (even one from a wool blouse would produce) doesn't get accidentally sent into your TX or RX wires and burn some chip/board/system but redirected instead through the shield into the closest ground.
To lower error rates due to signal noise.

If none of your gear has a grounded plug avoid using shielded cables or connect some grounding alligator clamps at the ends.
Using shielded wires over short distances might be overkill but it should provide peace of mind when buying expensive network gear!
UPDATE:
Model 'PowerConnect 8164' is a grounded network gear with grounded sockets.
You'll recognize a grounded socket if it's also encased in a metallic sheet.
If the switch's chassis is connected by a grounding wire to the rack, means the switch itself can be grounded. (if it would have only plastic RJ45 sockets that would't protect it's insides by some discharge travelling over the wire, not your case)
A grounded plug has a metal casing over the normal plastic plug (you connect the 9th wire aka. 'ground' to it by bending it over the jacket).
Comment: updated my answer to include your questions
Comment: Eh, the wires in copper Ethernet are connected by transformer to the NIC, you'd have to send one heck of a ESD through them to damage (the first one I looked up has a 2kV continuous rating). The shielding is pretty exclusively for noise, specifically in the MHz and a multiple of the symbol baud.
Comment: Every rackmount switch I've seen has grounded ports for use with STP. Most also have a separate grounding lug; this is used for creating a common ground for all associated equipment. If it does have a grounding lug it should be attached (if you don't have a single point grounding system then attaching it to the rack or UPS's ground is sufficient). Most small/medium office buildings have a single ground system so it's not necessary to consider the point of ground attachment.
Comment: The "grounded plug" is precisely what I'm trying to understand. I've yet to see any switch specs that mention grounding of the network ports. Wouldn't any port be grounded if the switch chassis is connected by a grounding wire to the rack? Or does the actual port design need to change to support shielded cables?
Answer: To answer you questions....

Cat6A is required for 10GbE connections. Cat6 is an old spec and only runs at 1GbE speeds. There's plenty of history there, but Cat5e = 1GbE, Cat6a = 10GbE, Cat7a = 40GbE (and 100GbE over very short runs).
Shielded cables block more EMI than just the twists in the pairs. The twists are great for low frequency interference, but don't work well against MHz level EMI. This sort of interference is pretty rare, but happens in certain industrial situations and more commonly around large radio equipment.
There's no special requirements of the switch or NIC. Any business grade equipment should have a metallic shield at the port so the metal shield on the cord has an open-drain. It's not necessary for proper operation, but does make the shielding more effective.

Unless you've got some odd equipment in your rack (like high powered radios or similar) that shielded cables are not necessary and would be of no benefit. The rack is likely already surrounded by grounded metal, there's unlikely to be a source of significant EMI in the first place, and the short run all reduce any potential gains from using shielded cables.
Comment: +1 for the cabinet rack info, I was thinking about open racks without a back metal sheet and maybe a front glass door


How to limit country list for address form drop-down?

Question: In my store I defined list of supported billing and shipping countries at store settings. This list is respected during checkout process - limited list of countries is shown when customer is entering the address. But when user is on "Address book" tab of user profile page and wants to add new address list is not limited, but all countries are allowed there.
How can I limit list of displayed countries when editing address at address book user profile tab?
I tried using hook_form_alter() but I don't see country drop-down there?
Also tried hook_preprocess_input() and I see other fields, but not country drop-down.
theme_preprocess_field() didn't help either.
And of course, I didn't find that option in back-end.
Comment: That's really a bug, address book entry should respect those too. There is [an issue](https://www.drupal.org/project/commerce/issues/3125801) about this.
Comment: I fount that patch my self and tried it, but for some reason it didn't work for me.
Answer: Found solution here:
https://docs.drupalcommerce.org/commerce2/developer-guide/customers/addresses/countries-and-subdivisions
Created new module "country_limit" added event subsriber like explained there:
<?php

namespace Drupal\country_limit;

use Drupal\address\Event\AddressEvents;
use Drupal\address\Event\AvailableCountriesEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class LimitCountriesEventSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events[AddressEvents::AVAILABLE_COUNTRIES][] = ['onAvailableCountries'];
    return $events;
  }

  public function onAvailableCountries(AvailableCountriesEvent $event) {
    $countries = ['AT' => 'AT', 'DE' => 'DE', 'CH' => 'CH'];
    $event->setAvailableCountries($countries);
  }

}

and registered it like:
services:
  # Name of this service.
  my_config_events_subscriber:
    # Event subscriber class that will listen for the events.
    class: '\Drupal\country_limit\LimitCountriesEventSubscriber'
    # Tagged as an event_subscriber to register this subscriber with the event_dispatch service.
    tags:
      - { name: 'event_subscriber' }

Event subsriber class is directly inside "src" dir, since I don't have other functionalities in this module.


Copy filefield image to different filefield field

Question: I am upgrading an older D6 site to D7. Way back we made the mistake of creating separate image fields for different content types. So instead of just creating a field field-image and reusing it, we have a field-event-image, a field-testimonial-image and so on (and a field-image). Well, besides the excess clutter, we need to create a view that shows a flexslide that sources nodes from multiple content types and it only allows one image field. So I would like to move all the images into the field-image field. I have seen a number of potential ways to achieve this result but no luck so far. Using migrate module is probably the most elegant, but seems over my head. VBO with Rules seems good and I have seen some examples but I get stuck creating the rule.
Any suggestions to my dilemma? Thanks
Answer: I fixed it by running SQL on the database directly through phpmyadmin.
First I added the destination field to the content type.
Then, I went into phpmyadmin and ran this: (change your field names as appropriate.
INSERT field_data_field_image SELECT * FROM field_data_field_event_image;

and
INSERT field_revision_field_image SELECT * FROM field_revision_field_event_image;

After it ran successfully, I went in and checked the content. All good. Then I was able to delete the old field. Problem solved! Thanks.
Comment: Be careful here. If the file was used only on one field - Deleting the field would cause deleting the image as well. This is because with your db update you would not update the file_usage table.
Comment: Good bit of information. This issue is far behind me now. I might have run into this but I would have just restored the file from the backup if it was missing...


What is Eulerian?

Question: I encountered an interesting function which is called "Eulerian" by the Wolfram's MathWorld:
$$\phi(q)=\prod_{k=1}^{\infty} (1-q^{k})$$
It is interesting because it seems that roots of any polynomial can be expressed in this function and elementary functions.
I want to know more about the properties of this function, where can I find the information?
Comment: http://en.wikipedia.org/wiki/Euler_function some sparse info
Comment: Btw, I found that in Mathematica it can be represented as $\operatorname{QPochhammer}[q^n]$
Answer: One notable property of this function is Euler's Pentagonal Number Theorem:
$$\prod_{k=1}^\infty (1-x^k) = \sum_{k=-\infty}^\infty (-1)^k x^{k(3k-1)/2}.$$
Here is a very interesting paper on the Pentagonal Number Theorem by Jordan Bell.
Answer: You may want to look up Weierstrass factorization theorem which plays a crucial role in complex analysis for writing functions as infinite products. It is a simple but powerful idea. Euler's famous proof of the Basel's problem exploited this infinite product for $\sin(x)$.

What is Eulerian?


Double mapping cone of coprime maps between circles.

Question: Suppose we have two maps $f,g: S^1 \to S^1$ with $f(z) = z^p$, and $g(z) = z^q$ for two primes $p \neq q$. Consider the space $M$ formed by gluing together two copies of $D^2$ to a single $S^1$ along its boundary, according to the maps $f,g$. Here's a crude picture of what I mean:

I want to show that $M$ is homotopy equivalent to the sphere $S^2$. How can I go about doing it?
Intuitively I can sort of see what's happening. On the left side, we're identifying points along a $p$-gon around the border of the disk, and on the right, we're doing the same for a $q$-gon. When we're gluing them together, since $(p,q) = 1$, I can see how everything gets identified to itself, and results in a $pq$-times folded circle $S^1$. But this is not at all a formal solution, and I don't even know if it's correct (because it's not a formal solution).
Comment: I have no idea how to title this post. Please suggest/edit a helpful title.
Comment: Note: you need a more delicate argument since with gluing maps of degrees $(p, q) = (2, 1)$, you get the projective plane $\mathbb{R}P^2$. It's not clear how you are using the fact that $p$ and $q$ are coprime.
Comment: @SammyBlack I'm considering $p$ and $q$ primes. Also, I totally agree that I can be horribly wrong.
Answer: van Kampen implies that $\pi_1 \text{Cone}(f,g) = \Bbb Z/(p, q)$, where $(p,q)$ denotes the ideal generated by these (equivalently, the ideal generated by their greatest common denominator). In your case, this is the trivial group. I disagree with the commenter that the result is $\Bbb{RP}^2$ for $q = 1$ (in fact, in that case the result is homotopy equivalent to $S^2$ simply by collapsing the right-hand disc).
Now the cellular chain complex is $$\Bbb Z^2 \xrightarrow{\begin{pmatrix} p & q \end{pmatrix}} \Bbb Z \xrightarrow{0} \Bbb Z.$$ So long as one of $p, q$ is nonzero, the kernel of the first map is abstractly isomorphic to $\Bbb Z$, so $H_2 \text{Cone}(p, q) = \Bbb Z$.
The desired claim follows immediately from Hatcher 4C.1.
Comment: Welcome to MSE. Are we all suppose to know what "Hatcher 4C.1" is?


Pearson correlation between age and test score

Question: I want to know the correlation between age and test exam. I want to know if there is a linear relationship exists between the 2 variables, but the scatter plot is confusing and I can't read it. Can someone help me?
Comment: I would think of age as the predictor, so I'd put it on the horizontal axis. Your plot may make more sense if you do that.
Comment: Have you coded the age as categorical variables? Can you share the structure of the variables?
Comment: @Mohanasundaram  hi Mohana, the age and exam test coded as scale. does this answer your question? sorry I'm new in statistics
Comment: @Dave  hi Dave , I've tried to put the age in the axis it become more confuser –
Comment: @nora Hi Nora, From the plot I could infer that, the x axis is limited by the range (0, 200) and the y axis is limited by the range (7,9). BTW, which application are you using? If possible, try extending the range of y axis (for example, (0, 60)).
Comment: @Mohanasundaram  I use SPSS , I've tried to do what u suggested, can u see picture above ? many thanks
Comment: @Mohanasundaram May I ask if u see if there is a linear relationship that exists ?
Comment: @nora I don't see any linear relationship between the age and test score. In SPSS, you can add the trendline and see that the line will be flat. Even if it shows trend, it will not be significant.
Comment: Only the first version of the scatter plot is any use, in my view. I agree with @Dave: although the correlation is the same either way age would be better on the x axis.
Comment: I wouldn't rule out significance at conventional levels. We can't be confident about the sample size given the possibility of overplotting.
Answer: In the data the correlation that you are looking for is very weak. It is so weak that it's impossible to be sure about it from those plots: it seems that the students who are 9 did somehow better than the others, but the difference is very little.
In conclusion, your data doesn't really support the hypothesis of the existence of a correlation between age and test results.
Comment: can I ask another question, I did an eta (η) correlation between 3 games ( categorical data) and participant age, and I got .128 does this a positive correlation? thanks for your help
Comment: coefficient [eta squared](https://en.wikiversity.org/wiki/Eta-squared) can't be negative, and .128 is actually a very little value. to assess if that association stands as a general rule, you may want to estimate its confidence intervals. If your sample is of the same size as the one you plotted above, I can already tell that that association is not significant.
Comment: I think this is a rather stronger claim than the scatter plot warrants. The issue is that with this kind of data there could be a great deal of overplotting. Naturally it does not help that the ages are rounded. A simple question remains unanswered:  what is the calculated Pearson correlation? Other displays would be better e.g. side by side histograms or dot plots. Can you post the data?
Comment: @NickCox hi Nick, I agree with you, the sample is n=36 so It might be the data is small. I've run the person correlation between age and test exam and it gives me  Pearson Correlation=   0.000406 . I assume there is no correlation here?
Comment: Yes, I think that is practically zero. The question of research interest is now why it's not a bit stronger, even given all the variables presumably at work.


How can I copy a file with a BATCH script from a folder on one drive to a folder of the same name on another drive?

Question: I'd like to make a Batch script to copy hundreds of files to their proper directories. Having to do this several times I figured a script would be helpful in the future. The only problem is I don't know the filenames or the directories they're in, ok I mean I do, but there's hundreds of them so it's not going to help.
Basically, I have the images for the movies in c:\movies in their own folders, but the movies are all in f:\movies in folders of the same name for each movie. I want to get the images and the movies all together again.
Example:
copy c:\movies\%dir%\%img%.png F:\Movies\%dir%\%img%.png

Thanks in advance for your help!
Answer: It can be made more dynamic, but your requirement is pretty simple.
@echo off
for /f %%a in ('dir /b /a:d "c:\movies"') do (
 copy /Y "C:\movies\%%a\*.png" "F:\movies\%%a"
)


An adjunction $F\dashv G$ gives rise to an adjunction $G^\ast \dashv F^\ast$

Question: I'm working on this exercise (source):

The hint refers to this theorem:

But I don't see how exactly to use it. I'm interpreting the hint in the following way. Since $F\dashv G$, there are natural transformations $\eta, \epsilon$ as in the theorem, and they satisfy the triangle identities. Our job is to modify those triangular diagrams somehow (possibly, by applying some functors) to get the triangular identities for the adjunction $G^\ast \dashv F^\ast$. But first of all, I don't see how to modify the original triangular diagrams, and secondly, we still need to prove that the functors $N:1_{[\mathscr A,\mathscr C]}\to F^\ast\circ G^\ast$ and $E: G^\ast\circ F^\ast\to 1_{[\mathscr B,\mathscr C]}$ (the functors that should satisfy the triangular identities) exist, which needs to be proven separately.
Comment: It's the hom-(2-)functor $[-,\mathcal S]:F\mapsto F^*$ that should be applied here on the commuting triangles.
Comment: @Berci I'm not sure I exactly understand what functor this is. Which categories are its domain and codomain? Is $F\mapsto F^\ast$ its definition on objects? What about morphisms?
Answer: By Theorem 2.2.5, the adjuction $F \dashv G$ is equivalent to a unit $\eta: 1_\mathscr A \implies GF$ and a counit $\epsilon: FG \implies 1_\mathscr B$ satisfying the triangle identities
(1):  and
(2): .
Define $\eta^* : 1_{\mathscr S^\mathscr A} \implies F^*G^*$ with $\eta^*_X = X\eta$ for any functor $X \in \mathscr S^\mathscr A$. Define $\epsilon^*:G^*F^* \implies 1_{\mathscr S^\mathscr B}$ with $\epsilon^*_Y= Y\epsilon$ for any functor $Y \in \mathscr S^\mathscr B$.
By the naturality of $\eta$ and the functoriality of any functor $X \in \mathscr S^\mathscr A$, $\eta^*$ is a natural transformation. Similarly, $\epsilon^*$ is also a natural transformation. Therefore, it remains to show that $\eta^*$ and $\epsilon^*$ satisfy the triangle identities.
Let $X$ be a functor in $\mathscr S^\mathscr A$. Whiskering (2) with $X$, we obtain the following commutative diagram due to the functoriality of $X$

Since $X \circ GFG = G^*(XGF) = G^*F^*(XG) = G^*F^*G^*X$, $X\eta G = G^*(X\eta) = G^*\eta^*_X$ and $(XG)\epsilon = \epsilon^*_{G^*X}$, the above commutative diagram can be rewritten as
(3): .
Now let $Y$ be a functor in $\mathscr S^\mathscr B$. Whiskering (1) with $Y$, we obtain the following commutative diagram due to the functoriality of $Y$

Since $Y \circ FGF = F^*(YFG) = F^*G^*(YF) = F^*G^*F^*Y$, $YF\eta = \eta^*_{F^*Y}$ and $Y\epsilon F = F^*(Y\epsilon) = F^*\epsilon^*_Y$, the above commutative diagram can be rewritten as
(4): .
Assembling (3) for all $X \in \mathscr S^\mathscr A$ and (4) for all $Y \in \mathscr S^\mathscr B$ shows that $\eta^*$ and $\epsilon^*$ satisfy the triangle identities. By Theorem 2.2.5, this gives an adjunction $G^* \dashv F^*$.


nginx deny access to JS and CSS

Question: I have a webpage set up using node.js set up behind nginx. Everythings work fine, but I would like to block direct public access to my css and js files
In my nginx config I have something like this:
location /style/ {
        deny all;
    }

location /js/ {
        deny all;
    }

It does correctly block access - when I view source on my webpage and try to navigate directly to the css or linked js files I get a 403 error. However, this also prevents node/nginx from being able to correctly use those files to style/add functionality to the page
What is the correct way to prevent people from directly accessing those files, while still being able to use them to display the page itself?
Answer: There isn't a way.
Either the browser can access the file and use it in the page, or it can't access the file at all.
You could try using the referer request header, but you'll get false negatives and people who have downloaded the page will have access to the JS anyway (either from the cache or from the Script tab in their browser's Developer Tools).
Comment: thats a shame, I seem to remember there was a way to do this with htaccess on apache. nothing comparable?
Comment: There isn't a way to do this with htaccess on apache. HTTP doesn't work that way.
Answer: You should use standard ngx_http_referer_module to prevent hot-linking of your files:
valid_referers none blocked server_names;
location /style/ {
    if ($invalid_referer) {
        return 403;
    }
    root /path/to/files;
}

Look for details in docs - http://nginx.org/en/docs/http/ngx_http_referer_module.html

nginx deny access to JS and CSS


server socket reads object from one client and writes on other socket in java

Question: I want to develop a sever which do following tasks.
1)Accepts request from client1 reads objet and write another object
2)Accepts request from client2 reads objet and write another object
3)Client1 enters info of client2,server has to get the client2 based on info and write an object on client2
Server java
<code>public class Server{
ServerSocket serverSocket ;
Socket socket;
@SuppressWarnings("rawtypes")
public static List<Map> clientList = new ArrayList<Map>();//creating list to store map objects of all clients

// Server socket instantiating
Server(int port) {
    try{
        serverSocket = new ServerSocket(port);
    }catch(Exception e){
        e.printStackTrace();
    }
}

//server is waiting on listen mode for accepting clients
void serverConnect() {
    while (true) {
        try {
            System.out.println("Server is Waiting for client to connect ");
            socket = serverSocket.accept();
            socket.setKeepAlive(true);
            System.out.println("connected to: "+ socket.getRemoteSocketAddress());
            new Thread(new ClientSession(socket)).start();//creating a new thread for every client
        } catch (Exception e) {
            e.printStackTrace();
            break;
        }
    }
}

public static void main(String args[]) throws IOException {
    Server server = new Server(5050);
    try {
        server.serverConnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>
}
ClientSession.java
<code>`public class ClientSession implements Runnable {

Socket clientsocket;
String emailId;
String msg;
String ipaddress;
String phoneNumber;
String sessionId;
String socketAddress;
String calleeInfo;
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Server";
ObjectOutputStream oos;
  @SuppressWarnings("rawtypes")
  Map globalmap = new HashMap();//creating a hashmap object to store sockets,objectoutputstreamobjects of clients

ClientSession(Socket socket) {
    // TODO Auto-generated constructor stub
    globalmap.put("clientsockets", socket);
    this.clientsocket = socket;
    System.out.println("socket--"+socket);
     try {
        oos = new ObjectOutputStream(clientsocket.getOutputStream());
        globalmap.put("oos", oos);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@SuppressWarnings("unchecked")
public void run() {
    // TODO Auto-generated method stub
    System.out.println("A new Thread started");
    try {
        System.out.println("IN SERVER READ METHOD");
        ObjectInputStream ois = new ObjectInputStream(clientsocket.getInputStream());
        Map<String, String> map = (Map<String, String>) ois.readObject();
        System.out.println("map in servereread"+map);
        System.out.println("IN SERVER DECODE METHOD");
        msg =  map.get("msg");
        System.out.println(msg);
        emailId =  map.get("email");
        phoneNumber =  map.get("phoneno");
        globalmap.put("phoneno", phoneNumber);
        globalmap.put("email",emailId);
        Server.clientList.add(globalmap);
        if (msg.equals("REGISTER")) {
            System.out.println("IN DECODE REGISTER");
            ipaddress =  map.get("ipaddr");
        } else if (msg.equals("INVITE")) {
            System.out.println("IN DECODE INVITE");
            sessionId =  map.get("sessionId");
            calleeInfo =  map.get("calleeInfo");
        }
        analyze(map);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

private void analyze(Map<String, String> map) {
    // TODO Auto-generated method stub
    try {
        String SQL = null;
        System.out.println(msg);
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Connecting to database...");
        Connection conn = DriverManager.getConnection(DB_URL,"username","pwd");
        Statement st = conn.createStatement();
        SocketAddress socketAddr = clientsocket.getRemoteSocketAddress();
        socketAddress = socketAddr.toString();
        if (msg.equals("REGISTER")) {
            SQL = "INSERT INTO Register (email,phoneNumber,ipaddress,socketaddress) VALUES ('"+ emailId+ "','"+ phoneNumber+ "','"+ ipaddress+ "','" + socketAddress + "')";
            System.out.println("SQL statement..." + SQL);
            serverWrite();
        } else if (msg.equals("INVITE")) {
            System.out.println("Connecting to database for invite...");
            SQL = "INSERT INTO Invite (sessionid,calleremail,callerphoneNo,calleeInfo) VALUES ('"+ sessionId+ "','"+ emailId+ "','"+ phoneNumber+ "','" + calleeInfo + "')";
            System.out.println("SQL statement--" + SQL);
            System.out.println("CalleeInfo--" + calleeInfo);
            // Retrieve the socket of the destination
            String query = "SELECT * FROM Register WHERE email='"+ calleeInfo + "' OR phoneNumber = '" + calleeInfo+ "'";
            ResultSet rs = st.executeQuery(query);
            System.out.println("ResultSet--" + rs);
            if (rs.next()) {
                String socketaddr = rs.getString("socketaddress");
                String email= rs.getString("email");
                String phoneNo= rs.getString("phoneNumber");
                String ipadd= rs.getString("ipaddress");
            }
                for(int i=0;i<Server.clientList.size();i++){
                    String emailid= (String) Server.clientList.get(i).get("email");
                    String phone = (String) Server.clientList.get(i).get("phoneno");
                    if(calleeInfo.equals(emailid) || calleeInfo.equals(phone)){
                        ObjectOutputStream out1= (ObjectOutputStream) Server.clientList.get(i).get("oos");
                        System.out.println("ObjectOutputStream----"+out1);
                        System.out.println("writing on"+Server.clientList.get(i).get("clientsockets"));
                        System.out.println("map before writing on to client2--"+map);
                        out1.reset();
                        out1.writeObject(map);
                        out1.flush();
                        break;
                    }

                }
            // retrieve socket info from register table based on calleeInfo
            // as primary key
        }
        st.executeUpdate(SQL);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void serverWrite() {
    // TODO Auto-generated method stub
    try {
        // Using ObjectOutputStream class to write object
          HashMap<String, String> map = new HashMap<String, String>();// Creating an object for HashMap class
          if (msg.equals("REGISTER")) {
            System.out.println("ObjectOutputStream storing--"+oos);
            map.put("msg", "REGISTERED"); // setting a message in HashMap object
            System.out.println("sending registered");
            oos.writeObject(map);// writing an object on socket
        }
    /*  else if (msg.equals("INVITE")) {
            map.put("msg", "CALLING");
            System.out.println("sending calling");
        }*/

    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>
}
It is going to the client1 socket but its not writing on the client2..Its writing on client1..
Thanks in advance.
Answer: The problem is with the client not in the server in this case..but one suggestion is don't create map object as Map map= new Map;.It will take only Strings. just create as Map map=new Map();It will take Strings,arrays and all datatypes.


Calculate $\int_{\gamma}(z^2-4)^{-1}dz$ if $\gamma$ is the unit circle traversed positively once.

Question: This function is defined on $\mathbb{C}-\{-2,2\}$. My problem is whether it is analytic on this set or not. If yes, then the integral is zero since $\gamma$ is a closed curve. If no, I have to calculate anyway. I could not solve the Cauchy Riemann equations. Yet, I know that $\frac{1}{z^2}$ is analytic on $\mathbb{C}- \{0\}$. At this point can I say that, in general,
$f(z)$ is analytic implies $f(z-a)$ is analytic with a proper domain (of course this statement is very intuitive but this is all I have).
I did the following for this statement:
Let $\phi(x,y)=x-4+iy$
Then, $f(z-4)=f(\phi(x,y))=u(x-4,y)+iv(x-4,y)=u(\phi(x,y))+v(\phi(x,y))$
Since $f(x+iy)=u(x,y)+iv(x,y)$ is analytic we have
$u_x=v_y$ and $u_y=-v_x$.
Since $\phi_x = 1$ and $\phi_y = 1$, by the chain rule, we have
$u(\phi(x,y))_x = v(\phi(x,y))_y $ and $v(\phi(x,y))_x = -u(\phi(x,y))_y $
Therefore, $f(z-4)$ is also analytic.
Is this a good argument? What are the technical issues I have to consider? Is there a general theorem or idea that I do not know? Can you help me with these issues? Thanks in advance.
Answer: All that matters is whether the function is analytic within the region whose boundary you are integrating over. As $\frac{1}{z^2-4}$ has no points of singularity in the disc $|z|\le 1$, the function is analytic here. Thus, the integral $= 0$


SQL Creating a cumulative sum column in a table by a specific order

Question: I apologize for the confusing title. I am dealing with an issue this morning that I thought I solved with everyone's help here but I can't do what I originally had hoped with just the master_line_num. Once again, below is a small subset of the data I am working with:
ID  Proj_Id    Year   Quarter  Value  **Cumu_Value**      Master_Line_Num
1   "C102"     2017      1    200.00    **200.00**           1
2   "C102"     2017      2    200.00    **400.00**           2
3   "C102"     2017      3    200.00    **600.00**           3
4   "C102"     2017      4    200.00    **800.00**           4
5   "C102"     2018      1    400.00    **1200.00**          5
6   "C102"     2018      2    400.00    **1600.00**          6
7   "C102"     2018      3    400.00    **2000.00**          7
8   "C102"     2018      4    400.00    **2400.00**          8
9   "B123"     2017      1    100.00    **100.00**           1
10  "B123"     2017      2    100.00    **200.00**           2
11  "B123"     2017      3    100.00    **300.00**           3
12  "B123"     2017      4    100.00    **400.00**           4
13  "B123"     2018      1    200.00    **600.00**           5
14  "B123"     2018      2    200.00    **800.00**           6
15  "B123"     2018      3    200.00    **1000.00**          7
16  "B123"     2018      4    200.00    **1200.00**          8

The desired values I am trying to get is the "Cumu_Value" column. I am trying to get those values by adding up the "value" column by year, by quarter for a specific "Proj_Id". I originally just tried to multiply the "value" column by the master_line_num column after getting that but then realized that it doesn't work due to the "value" column changing between years.
Is it possible to calculate this with T-SQL or do I need to do something more extravagant?
Comment: Try analytic functions.
Answer: SQL supports the cumulative sum as a window function, so this is easy to express:
select . . . ,
      sum(value) over (partition by proj_id order by year, quarter) as cumulative_sum

Answer: You need a Windowed Aggregate, this will return a Cumulative Sum:
sum(value)
over (partition by proj_id
      order by Year, Quarter
      rows unbounded preceding)

Caution, don't use (partition by proj_id order by Year, Quarter) without the ROWS as it defaults to RANGE which might return a different result and has much more overhead. RANGE includes all rows with the same value as the current. In your case it would return:
 800
 800
 800
 800
2400
2400
2400
2400

Edit:
After checking your other question I noticed that you don't have a Master_Line_Num in your data, so you better use ORDER BY Year, Quarter instead.
Comment: @user3494110: When it works, you should *accept* this answer
Answer: You can try something like this:
 select t1.id, t1.proj_ID, t1.Year, t1.Value, SUM(t2.Value) as Cumu_sum, Master_Line_Num
    from @tablename t1
    inner join @tablename t2 on t1.id >= t2.id
    group by t1.id, t1.Value
    order by t1.id


Construction of a triangle given 4 concyclic points

Question: 4 concyclic points $S_1$, $S_2$, $T_1$ and $T_2$ are given. Construct a triangle $ABC$ so that its inscribed circle intersects the angle bisector from vertex $A$ at points $S_1$ and $S_2$, and the median from vertex $A$ at points $T_1$ and $T_2$.
I found point A as the intersection point of $S_1S_2$ and $T_1T_2$. Then I found midpoint $J$ of $S_1S_2$ and constructed a circle of radius $|JS_1|$ and center $J$. Finally, I constructed tangents to the circle at point $A$. How do I construct the missing side of $ABC$? I was thinking it would be great if I could just construct the centroid of $ABC$ using its incenter $J$ but I don't know how.
Comment: Note that $S_1 S_2$ needs to be a diameter of the circle, and not just any 2 points.
Comment: Can you construct a line $ \ell$ so that the lines $g_1, f_1, b$ cut it into 2 equal parts? Then, translate $\ell$ to pass through $J$, and translate again by radius in the perpendicular direction so that it's tangential to the circle. This gives you side $BC$.
Comment: @CalvinLin "Can you construct a line $ℓ$ so that the lines $g_1$,$f_1$,$b$
 cut it into 2 equal parts?" Yeah, this is what I'm having trouble with. How do I do that?
Comment: @CalvinLin Nevermind, I got it, I guess I'm just slow today. Thank you sir!!
Answer: Hint: Suppose tangent points are E and F. Connect E to F. EF intersect $T_1T_2$ at G. Connect G to J. Draw a perpendicular like $l$ on GJ at G. $l$ intersects extensions of AE and AF at point B' and C'. It can be shown that G is mid point of B'C'. Hence BC which is parallel with B'C' and tangent on the circle can be the side you are trying to find. To find that, extend GO from O to meet th circle at H. Draw a perpendicular on OH at H, it intersect AD and AE at B and C, BC is parallel we B'C' and tangent on circle centered at J.


Convergent $x_n,y_n$ and $x_n^{y_n}$ diverges

Question: Let $x_n, y_n > 0$.
I need an example of convergent sequences $x_n,y_n$ such that $x_n^{y_n}$ diverges. Could you help me?
Answer: Let $x_n$ be any positive sequence converging to $0$. Let $y_n$ be $1/|\ln x_n|$ if $n$ is even and let $y_n$ be $2/|\ln x_n|$ if $n$ is odd. Note that $y_n$ converges to $0$. Then $x_n^{y_n}=e^{y_n\cdot \ln x_n}$ which is $e^{-1}$ or $e^{-2}$, alternating with $n$, thus not converging.
Comment: Brilliant! How did you come up with it?
Answer: $$x_n=\frac{1}{n!}\\y_n=\frac{(-1)^n}{n}\\x_n^{y_n}=\left\{\begin{matrix}
 \frac{1}{n!}^{\frac{-1}{n}}&  \space\space n=2k+1\\
 \frac{1}{n!}^{\frac{+1}{n}}& \space\space  n=2k
\end{matrix}\right.$$
$$\left\{\begin{matrix}
 \sqrt[n]{n!} \rightarrow \frac{1}{e} & \space\space  n=2k+1\\
 \sqrt[n]{\frac{1}{n!}} \rightarrow  e & \space\space n=2k
\end{matrix}\right. $$
Comment: To dispel any illusion that the sought counterexample is hard it should be noted that one can construct trivial counterexamples easily. While this example is pretty, it somewhat misses the point of the exercise.
Comment: You missed the fact that you are supposed to have $y_n>0$......
Comment: oh ,yes .I miss $y_n>0$
Answer: You can show easily that $x_n^{y_n}$ converges to $l_x^{l_y}$, with $l_x$ the limit of $x_n$ and $l_y$ the limit of $y_n$...
Just by using the right $\epsilon_{x,y}$ and $N_{x,y}$ in the definition of convergence.
Comment: the problem is that the quantity $0^0$ is not well-defined. The book is fine.
Comment: Why? Are you saying that $x_n^{y_n}$ cannot diverge?
Comment: @nikolai Yes, it can't diverge.
Comment: strange, then it must be a mistake in my book.
Comment: @IttayWeiss Right you are. I assumed limits were $>0$, but only $x_n,y_n>0$... My bad.