Is antisymmetric the same as reflexive?

Question: Note: The following definitions from my book, Discrete Mathematics and Its Applications [7th ed, 598].
This is my book's definition for a reflexive relation

This is my book's definition for a anti symmetric relation

Is a reflexive relation just the same as a anti symmetric relation?  From what I've, the only way to meet that antisymmetric requirement is to have the same ordered pair, say an element a from Set A, (a,a). If you have anything other than the same ordered pair, (1,2) and (2,1), it will not meet the antisymmetric requirement. But the overall definition of reflexive relation is that it's the same ordered pair. Are they just two ways of saying the same thing? Is it possible to have one and not the other?
Comment: @GitGud The question was about *anti*symmetric, not symmetric.  I'm preparing an answer now.
Comment: A nice, natural and somewhat commonly-encountered relation that is non-reflexive, and at the same time anti-symmetric in a non-vacuous way seems hard to come by.
Comment: @Arthur: A fairly natural example of a non-reflexive, anti-symmetric relation (on $\mathbb Z, \mathbb Q,$ or $\mathbb R$) is $a \ge |b|$.
Comment: On $\{1,2\}$, the relation $\{(1,1)\}$ isn't reflexive, but it is symmetric. On the same set, $\{(1,1),(1,2),(2,2)\}$ is reflexive, but not symmetric.
Comment: [Is there a relation that is irreflexive, anti-symmetric and not transitive?](http://math.stackexchange.com/questions/704457/is-there-a-relation-that-is-irreflexive-anti-symmetric-and-not-transitive)
Comment: OK. My first example still works.
Comment: @GitGud Would an empty relation be symmetric?
Comment: @committedandroider Yes, because $\forall x,y\left((x,y)\in \varnothing\implies (y,x)\in \varnothing\right)$ is a true statement.
Answer: No, antisymmetric is not the same as reflexive.
An example of a relation that is reflexive, but not antisymmetric is the relation
$$R={(1,1),(1,2),(2,2),(2,1)}$$ on $$A={1,2}.$$  It is reflexive because for all elements of $A$ (which are $1$ and $2$), $(1,1)\in R$ and $(2,2)\in R$.  The relation is not anti-symmetric because $(1,2)$ and $(2,1)$ are in $R$, but $1\not=2$.
An example of a relation that is not reflexive, but is antisymmetric is the empty relation $R=\emptyset$ on $A={1}$.  It doesn't have $(1,1)$ in it, but it is vacuously antisymmetric.
On a further note: reflexive is:
$$\forall a\in A, (a,a)\in R.$$
Anti-symmetric is
$$\forall (a,b),(b,a)\in R, a=b.$$
Note that the statements have different hypotheses and conclusions (even though they look similar).
Comment: Would your second example be vacuously transitive as well?
Comment: @committedandroider The second example is transitive, but not vacuously transitive because $(1,1)$ and $(1,1)$ are in $R$ and so is $(1,1)$.
Answer: No.
First, you can have a reflexive relation which is not antisymmetric. For example: an integer number $a$ is related to other integer $b$ if and only if $a$ and $b$ have the same parity. This is not antysymmetric, because $2R4$ and $4R2$, but $2\neq 4$. But it is reflexive, since every integer has the same parity than itself.
Second, you can have an antysymmetric relation that it is not reflexive. The empty relation on a non empty set, for example: that is, a non empty set in which no element is related to any element (not even to itself).
Comment: What would be an example of a non empty set in which no element is related to any element?
Answer: They are not the same thing. For example, on $\mathbb R$ the strict inequality is anti-symmetric but not reflexive.... If you want one which is not vacuous, change it to be $\leq $ if at least one of the numbers is negative.
On $\mathbb Z$, if we define $(x,y) \in R$ if and only if $x-y$ is even, then this is reflexive but not santi-ymmetric.
Comment: $<_{\Bbb R }$ is a familiar example, but unfortunately the anti-symmetric property is vacuous.
Comment: @MJD doesn't it has to be vacuous in some sense? By this there must exists an $x$ such that it is vacuous at for all pairs including $x$...
Comment: @N.S. What does the $\sim$ mean? I found it on here http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference but that doesn't explain what it means
Comment: @committedandroider I am used to write $a \sim b$ instead of $(a,b)$ for a relation... I will fix it.
Answer: Reflexivity requires all elements to be both way related with themselves.  However, this does not prohibit non-equal elements from being both way related with each other.
That is:  $\qquad\forall a\in A: (a,a)\in R$ from which we can prove: $$\forall a\in A\;\forall b\in A:\Big(a=b \;\to\; (a,b)\in R \wedge (b,a)\in R\Big)$$
Antisymetricality requires any two elements which are both way related with each other to be equal.  Which means it prohibits non-equal elements from being both-way related to each other; however, this does not require all elements to be both way related with themselves.
$$\forall a\in A, \forall b\in A:\Big((a,b)\in R \wedge (b,a)\in R \;\to\; a=b\Big)$$
Or via contraposition: $\qquad\forall a\in A, \forall b\in A:\Big(a\neq b \;\to\; (a,b)\notin R \vee (b,a)\notin R\Big)$
Thus they are not the same thing.

Examples are easy to generate.  From the set $A=\{0, 1\}$ The following relations are:
$$\begin{array}{c|c|c}
R & \text{Reflexive} & \text{Antisymmetric}
\\ \hline
\{(0,0), (1,1)\} & \text{Yes} & \text{Yes}
\\
\{(0,0), (0,1), (1,0), (1,1)\} & \text{Yes} & \text{No}
\\
\{(0,0), (0,1), (1,0)\} & \text{No} & \text{No}
\\
\{(0,0), (0,1)\} & \text{No} & \text{Yes}
\end{array}$$

Is antisymmetric the same as reflexive?


How to prove that the sum of two compact sets in a Banach space need not be compact

Question: Let $X$ be a Banach space and $K$ a compact subset of $X$ and consider for a given $\eta>0$ the closed ball $C(0,\eta)$ centered at $0$ of radius $\eta$.
How can I show that $K+C(0,\eta)=\{x+y: x\in K~\mbox{and }y\in C(0,\eta)~\}$ is not (sequentially) compact (except when $X$ has finite dimension or $K$ is empty)?
Comment: Your title doesn't seem to relate to your question.
Comment: You are asking if the sum of a compact set and a closed ball is compact in a Banach space. The closed balls need not be compact.
Answer: If $K$ is empty, the set is empty, and if it's not empty then take $x_0\in K$: we get $K+C(0,\eta)\supset x_0+C(0,\eta)=C(x_0,\eta)$. If it was compact, so would be the closed unit ball.
Comment: If $K$ is empty, then the sum is empty, hence compact.
Comment: @ChrisEagle Right. I should have note that.
Comment: ...and the closed unit ball is compact iff..
Comment: @kevin This says also how to construct a counter example: take $X$ a space where the closed unit ball is not compact and consider $K$ a compact subset of $X$


Integrating $\int dx \int dy (x-y)^2 xy \exp(-a(x-y)^2)$

Question: Any useful change of variable possible to make the integration easier ?
$$
\int dx \int dy (x-y)^2 xy \exp(-a(x-y)^2)
$$
Comment: This integral diverges
Answer: Use a rotation:
$$u = \frac{x-y}{\sqrt{2}}$$
$$v = \frac{x+y}{\sqrt{2}}$$
to get the integral
$$\iint_{\Bbb{R}^2} u^2(v^2-u^2)\exp(-2au^2)\:du\:dv$$
which diverges because of the $v$.


Dell Poweredge power management

Question: I have a Dell Poweredge 840 and the moment it boots up it's fans are roaring full bore regardless of how little usage there is on it - idle speed is 100%.  I am running windows server 2003 r2. The processor is a Intel(R) Celeron(R) D CPU 3.06GHz [x86 Family 15 Model 6 Stepping 5]. I have been digging through the documentation on power management, but this server doesn't seem to have any (aside from the monitor and the drives).    Does Dell have some power manager app for stepping this model (I can't find one)?  Can any of you give me any tips to save power on this thing?
I know business owners are not supposed to care about tree hugger things like power usage but I do.
Thanks in advance

Edit:
I messed around with powercfg and it appears that hard disk and processor throttle power management are not supported (only monitor turn off).  Can this be?  Forgive me but it seems like my windows 98 system had better power management than this.  I am wondering if there is a consumer version bios that is available for this board - even a hacked version.
Any help is greatly appreciated.
Answer: If you are concerned about the fan speed (and noise) consider this.  On my Poweredge 2500, the only way I've found to control the fan speed is to adjust the temperature thresholds.  If the maximum temperature is too close to the current reading, the fan spins faster trying to cool it off.  When you raise the maximum temperature, the fan relaxes.  So check to see if your thresholds are set too low.
Of course, if your thresholds aren't set too low, then you have a separate issue regarding cooling.
Comment: OK now that piques my interest.  Where did you adjust that?  My Bios has no power management section at all.
Comment: Marking this as the best answer since there really wasn't an answer for this one.
Answer: You may want to try updating the BIOS of the server.  I have had multiple Dell products have a very similar issue and a BIOS update has fixed it.
Comment: I thought I had done that, but double checked and ... doh, first rule in problem sloving make sure the drivers and bios are up to date.  Unfartunately it does not seem to give me any more options either in bios or windows power settings.  Any utilities you know of that might help?
Comment: At this point if you are not seeing any improvement you likely have some type of hardware issue.
Answer: PE's really go full speed (and others servers too) when they boot, but they go down after the OS boot up or, in the case of a a open chassi, several minutes.
If the fans aren't going down at all, it may be sign of a deeper problem with the OS or even hardware. Unfortunately I am not used to windows servers so I can't answer on that.
Answer: Assuming that the fan speed is directly related to the power consumption of the server as a whole is probably an incorrect assumption. That being said, most Dell servers I've worked with run the fans at full speed during post and reduce the speed once the post process has completed. They will increase in speed based on temperature and load. If the fans run at full speed constantly then you have a problem. If they don't then I think what you're seeing is normal.
Comment: Good point correlating the fan speed to power consumption.  And you are also right in that I exaggerated my fan speed.  It does not run at the 100% "post" speed all the time but does maintain a constant roar - especially compared to all my other computers. Any suggestions about managing the power?  Thanks
Answer: If you look at OMPC (Open Manage Power Center) that will give you a lot of data on your power and thermals from servers. its very handy

Dell Poweredge power management


Firefox doesn't open when run on Jenkins server

Question: I have the same problem,I'm using Firefox 57 and selenium 3.8.0,Jenkins on the linux ,windows 2008 R2。
It gives the following error log:
geckodriver INFO geckodriver 0.18.0

geckodriver INFO Listening on 127.0.0.1:54750

geckodriver::marionette INFO Starting browser C:\Program Files (x86)\Mozilla Firefox\firefox.exe with args ["-marionette", "-headless"] *** You are running in headless mode. Marionette INFO Enabled via --marionette

!!! [Parent][MessageChannel] Error: (msgtype=0x150063,name=PBrowser::Msg_ParentActivated) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x15008F,name=PBrowser::Msg_UpdateNativeWindowHandle) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x150083,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24003F,name=PContent::Msg_LoadProcessScript) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x150080,name=PBrowser::Msg_LoadRemoteScript) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24003F,name=PContent::Msg_LoadProcessScript) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24003F,name=PContent::Msg_LoadProcessScript) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x2400FA,name=PContent::Msg_AsyncMessage) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x150001,name=PBrowser::Msg_AsyncMessage) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][RunMessage] Error: Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x15008F,name=PBrowser::Msg_UpdateNativeWindowHandle) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x150083,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x15008F,name=PBrowser::Msg_UpdateNativeWindowHandle) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x150083,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv

l error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x150083,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x15008F,name=PBrowser::Msg_UpdateNativeWindowHandle) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x150083,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv

Channel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x15008F,name=PBrowser::Msg_UpdateNativeWindowHandle) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x150083,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv

0x150083,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv

type=0x15008F,name=PBrowser::Msg_UpdateNativeWindowHandle) Channel error: cannot send/recv

!!! [Parent][MessageChannel] Error: (msgtype=0x150083,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv

Comment: What are you doing? What's the problem? Do you try to run jasmine tests on jenkins?
Comment: I want to run the automated test case on Jenkins to use Firefox browsers,Here the error occurred,Please check the log for specific errors。
Answer: Found this solution when browsing through internet, hope this helps

Navigate to C:\Program Files\Mozilla Firefox\defaults\pref
Create a file local-settings.js
Add below code to the .js file

pref("general.config.filename", "mozilla.cfg");
 pref("general.config.obscure_value", 0);

Now create mozilla.cfg in  **C:\Program Files\Mozilla Firefox"
Add below code to .cfg file

//
pref("security.sandbox.content.level", 5);
(Don't forget the // at the beginning of the file )
Rerun the jenkins build
Source:  https://forum.katalon.com/discussion/4208/jenkins-new-katalon-studio-5-1-0-2-firefox-wont-work


Bounds for the expected value of the Kolmogorov-Smirnoff loss function

Question: Let
$$
\mathcal{F}=\{F:\mathbb{R}\longrightarrow\mathbb{R}: \text{$F$ is the CDF of some probability measure on $\mathbb{R}$}\}.
$$
Consider the loss function, $L:\mathcal F\times\mathcal F\to\mathbb R$, defined by
$$
L(F,G) = \sup_{x\in\mathbb R}|F(x) - G(x)|.
$$
(This is just the metric induced by the $L^\infty$-norm.)
Let $\Theta$ be a subset of $\mathcal{F}$.
For $\theta\in\Theta$ and a random sample $X_1,\ldots,X_n$ drawn from $\theta$, let $\hat{\theta}(X_1,\ldots,X_n)$ be the associated empirical distribution function:
$$
\hat\theta(X_1,\ldots,X_n)(x) = \frac 1 n\sum_{i=1}^n I(X_i\leq x)
$$
Are there "large" sets $\Theta$ for which one can one explicitly compute, or bound, the risk $R$ associated to the loss function $L$ in terms of $n$ and $\Theta$, where $R$ is defined by
$$
R(\theta,\hat{\theta}) = E_\theta[L(\theta,\hat\theta(X_1,\ldots,X_n))]?
$$
Answer: It is easy to get an upper bound for $\Theta = \mathcal{F}$ using the Dvoretzky-Kiefer-Wolfowitz (DKW) inequality and
$EL = \int_0^\infty\Pr(L>u)du$, see https://en.wikipedia.org/wiki/Dvoretzky–Kiefer–Wolfowitz_inequality#The_DKW_inequality
The DKW inequality gives us
$$R(\theta,\hat\theta) = \int_0^\infty \Pr\left(L(\theta,\hat\theta)>u\right)du \leq 2\int_0^\infty e^{-2nu^2}du.$$
I'm not sure if tighter bounds exist for $\Theta\subset\mathcal{F}$.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Author image in comments twig

Question: I succesfully get user name, surname and date to render in comment.html.twig like this
function MYTHEMENAME_preprocess_comment(&$variables) {
    $comment = $variables['comment'];
    $variables['user_name_comment'] = $comment->getOwner()->field_first_name->value;
    $variables['user_surname_comment'] = $comment->getOwner()->field_last_name->value;
    $variables['created'] = \Drupal::service('date.formatter')->format($variables['comment']->getCreatedTime(), 'conference_date');
}

In node template i got field_picture to render like this
$variables['author_picture'] = $node->getOwner()->field_picture->entity->url();

But i can't get my field_picture from user to render in comment twig file. I try to show the author's picture of every comment.
Any ideas?
Comment: Try: $variables['author_picture'] = file_create_url($node->getOwner()->field_picture->entity>getFileUri());
Comment: nope. This breaks the page.
Answer: When you want to display an entity field based on the "Manage Display" settings, you should go just {{ content.my_field }}. If you "kint" content (var dump it) you can see that each content field element has also "theme" key/property, which tells twig how to render that field
Comment: I have seen this but it doesn't seem to work. I tried also user_picture and this isn't rendering too. Btw, my settings looking grayed out in theme settings (User pictures in posts & User pictures in comments checkboxes. Both checked but i can't uncheck them).
Comment: have you tried to load user object in preprocessing and pass user picture URL in the variable?
Comment: that would bring me the image of the current user. Right? Not the owner of the comment.
Comment: every comment object having author id so you can load author and fetch author detail in a variable.
Comment: actually the comment object is loading. i am able to print author id with {{ comment.getOwnerId() }} without preprocess, but still i can't print the picture.. :(
Answer: Create Template Preprocess Comment in your Theme file
function template_preprocess_comment(&$variables) {
  $comment = $variables['elements']['#comment'];
  $account = $comment->getOwner();
  $variables['user_picture'] = file_create_url($account->user_picture->entity->getFileUri());
}

Author image in comments twig


Sketching Images of sets under a function in Complex Plane

Question: I want to know how I would be able to sketch the image of a function in the complex plane. Say I was considering the set A = {z = x + iy: x in (0,1) y in (0,1)} under the function f(z)=z^2. How would I sketch its image? The domain is clear and simple, but the issue with the image is I cannot work out how to sketch it, as I have, on an argand diagram, the real part in the x direction, and the imaginary part in the y direction, so where would the output value of f(z) be plotted?
Thanks in advance.
Comment: Sorry this hasn't posted properly: the set A = {z=x+iy:0<x<1, 0<y<1} under the function f(z)=z^2. How would I then sketch this, on what sort of diagram and where would I plot the output points of f(z)?
Comment: Why don't you edit your question?
Comment: Thanks, have done, didn't realise it was an option!
Answer: Note that $f(x+yi)=x^2-y^2+2xyi$. So, consider the line segments:

from $0$ to $1$;
from $1$ to $1+i$;
from $1+i$ to $i$;
from $i$ to $0$

and see whr $f$ maps them into. For instance, the second segment is $\bigl\{1+ti\,|\,t\in[0,1]\bigr\}$ and $f(1+ti)=1-t^2+2ti$. So, you get a parabolic arc.
Now, see what you get from the other three segmens. Doinf his will give you the boundary of $f(A)$.
Comment: My issue is, once I've found all the boundaries, how do I plot them. Because I have the real and imaginary parts, plus the output value of f(z)?
Comment: I don't understand your doubt. If you know both $\operatorname{Re}\bigl(f(z)\bigr)$ and $\operatorname{Im}\bigl(f(z)\bigr)$, then what else do you need to know $f(z)$?


How to configure Desktop Notification in Conkeror browser?

Question: How can I enable Desktop Notification for web apps (Slack, for example)?
I didn't find anything about this on Conkeror Wiki, Mailling List or Google :(
Thanks!
Answer: To add desktop notification for Conkeror, you need to use the XPCOM nsIPermissionManager interface, for example
<code>var permissionManager = Components.classes["@mozilla.org/permissionmanager;1"]
        .getService(Components.interfaces.nsIPermissionManager);

permissionManager.add(
    make_uri("http://www.messenger.com/"),
    "desktop-notification",
    Components.interfaces.nsIPermissionManager.ALLOW_ACTION
  );
</code>


decidability and countability

Question: The diagonolisation technique is utilized to prove that the halting problem is undecidable. However, I kind of sense that it is making the assumption that decidable sets should be countable. Is this true? If not, which part am I missing?
Comment: there are countably many algorithms
Answer: The original proof of the undecidability of the halting problem assumes that there exists a program that can determine whether any other program halts and then explicitly constructs a counterexample that the program will give the wrong answer for. No assumptions of countability are necessary for this. However, there are only countably many computable sets because there are only countably many programs of finite length.
Comment: Adding to this just a little bit. The countability aspect doesn't really come into play in the proof of the halting problem. The countability aspect follows from a few facts though. Strings of finite length are enumerable (for example, you can enumerate finite length binary strings). All Turing Machines can be represented as a finite length string, known as an encoding. It follows that there are countably many Turing Machines.

decidability and countability


When does it not require least square to solve $A × x=b$?

Question: Suppose I have a $n \times n$ independent matrix $A$, can I just take the inverse of $A$ directly and get $x = A^{-1}\times b$?
Is least square solution only for the matrix that is not in $N\times N$ form?
If I am wrong about the $N \times N$ part, can you give an example of such matrix $A$ that doesn't need least squares to solve?
Comment: Some $n$ by $n$ matrices do not have inverses.
Comment: I am saying  n by n independent matrix.    Can you think of any example that don't need least square to solve Ax=b ?
Answer: Not all matrices are invertible, meaning $A^{-1}$ doesn't always exist.
$A$ is invertible if and only if it is square and $\det(A)\neq 0$; in this case any equation $Ax=b$ has a solution given by $x=A^{-1}b$.

When $A$ is square $(n\times n)$ the following are equivalent:

$A$ is invertible
$A^{-1}$ exists
$A$ is surjective, meaning $\text{Codom}(A) = \text{Im}(A)$
$A$ is injective, meaning $\ker(A) = \{0\}$
$A$ is bijective, meaning it is both surjective and injective

It is a consequence of the rank-nullity theorem that nonsquare $A$ are never invertible.
Indeed, if $A$ is $m\times n$, then as a linear transformation it is a map $\mathbb R^n \longmapsto \mathbb R^m$.
The rank-nullity theorem then says that
$$\dim \text{Im}(A) +\dim\ker(A) = n$$
If $m>n$, then $\dim \text{Im}(A) \leq n < m = \dim \text{Codom}(A)$, so $A$ fails to be surjective.
If $m<n$, then $\dim\ker(A) = n - \dim \text{Im}(A)\geq  n - m > 0$, so $A$ fails to be injective.

Now, suppose $A$ is square and not invertible; there are two possibilities:
$\qquad (1)$: $b \in \text{Im}(A)$
In this case, there is some $x\in \text{Dom}(A)$ with $Ax=b$, so the equation has a solution.
The problem is since $A$ is not invertible, it is not injective and hence its kernel has $\dim \geq 1$.
Any $u \in \ker(A)\setminus\{0\}$ — and notice this set is nonempty because of our previous observation — will therefore be such that $x+u$ is also a solution.
Indeed:
$$A(x+u) = Ax + Au = b + 0 = b$$
In other words, we not only have a solution, we have infinitely many of them.
$\qquad (2)$: $b \not\in \text{Im}(A)$
In this case, of course there is no solution.

Least squares is a method for finding 'almost solutions' when none exist.
More specifically, when the equation $Ax = b \iff Ax - b = 0$ has no solution, least squares attempts to find an $x$ which minimizes $\lVert Ax - b \rVert$.
In other words, it finds some $x$ such that $Ax$ is closest (in the usual Euclidean norm sense) to $b$.
The value $u = Ax$ always exists and is unique, because $\text{Im}(A)$ is closed and $\{b\}$ is compact.
However, like in case $(1)$ above, there may be infinitely many $x$ that satisfy $Ax = u$.
I find it best to think in terms of projections:
if $u$ minimizes $\lVert u - b\rVert$ over $u\in \text{Im}(A)$, then $u$ is the projection of $b$ onto $\text{Im}(A)$, ie
$$ u = \text{Proj}_{\text{Im}(A)} b$$
Answer: Yes, you can solve $A × x=b$ directly using the inverse of $A$ if it exists.
Least squares (and pseudo-inverse of $A$) is needed, e.g. when (quoting wikipedia)

a vector $x$ that solves the system may not exist, or if one does
  exist, it may not be unique


How to check another user is logged in?

Question: There is a lot of questions how to check the current user is logged in, but I need to check another users (by uid for example).
Is there any easy way to do it?
Answer: There aren't any functions in Drupal that I am aware of. You'll need to query the database.
<code>$time_active = db_query("SELECT timestamp FROM {sessions} WHERE uid = :uid ORDER BY timestamp DESC LIMIT 1", array(":uid" => $uid))->fetchField();
</code>
That will fetch the last time that the user was active if they have a current session open.
Comment: A similar method is used by the core block "Who's online" (in http://example.com/modules/user/user.module)
Answer: Hope this will help you,
You can use sessions table. You can fetch a list of all logged in users by querying the sessions table
<code>
// Check if user $uid is online in the last 10 minutes
$online = db_query("SELECT uid FROM {sessions}
          WHERE uid = :uid
          AND timestamp >= :time", array(':uid' => $uid, ':time' => (REQUEST_TIME - 600))->fetchField();
</code>
Reference : Check if user is online

How to check another user is logged in?


R: Find duplicates that are within a certain value

Question: I have a data frame (df) that includes latitude and longitude coordinates (Lat, Long) as well as the depth (Depth) of a temperature measurement for each entry. Essentially, each entry has (x,y,z)=(Lat,Long,Depth) locational information for each temperature measurement.
I'm trying to clean the data by finding and removing duplicate measurement locations. The easy part is removing the exact duplicates, handled as such:
df = df[!(duplicated(df$Lat) & duplicated(df$Long) & duplicated(df$Depth)),]

However the problem is that the values of lat/long for some entries are just slightly off, meaning the above code won't catch them but they are still clearly duplicated (e.g. lat = 39.252880 & lat = 39.252887).
Is there a way to find duplicates that are within a certain absolute value or percentage of the first instance?
I appreciate any help, thanks!
Comment: You could round all the values to whatever tolerance you prefer and then look for duplicates. In your example, rounding to three decimal places would give latitude = 39.253 for both points. Or maybe it would make more sense to calculate the spatial distance between each of the measurements and find groups of points clustered within some critical distance of each other. Then, within those clusters, find rows with the same depth and average them. See [this SO answer](http://stackoverflow.com/a/21006437/496488) for how to find the spatial distances and identify clusters of points.
Comment: For the first method, you can shorten your code: `df.new = df[!duplicated(round(df[,c("lat","long","depth")], 3)), ]`.
Answer: Based on this post I was able to come up with a solution. I modified the function to have a tighter tolerance on "duplicates" to be 0.001, otherwise the function is unchanged. The application, however, changes slightly to:
output=data.frame(apply(dataDF,2,fun))

because I wanted to compare values within a single column instead of in a single row.
To continue, I then add artificial indices to my output data frame for later use:
output$ind = 1:nrow(output)

The main part is finding the row indices where the function returned TRUE for the three locational information fields (lat, long, depth). The following code finds the indices where all three were true, creates a temporary data frame with only those entries (still logicals), finds the indices of the duplicates, then reverses it to return the indices that will be removed from the full, original dataset (pardon the bad variable names):
ind = which(with(output,(Lat=='TRUE' & Long=='TRUE' & Depth=='TRUE')))
temp = dataDF[ind,]
temp$ind = ind
ind2 = duplicated(temp[,1:3])
rem = ind[ind2]

df.final = dataDF[-rem,]

Hopefully that helps! It's a bit complicated and the function is very slow for large datasets but it gets the job done.


An application of third isomorphism theorem in quotient rings.

Question: I am a graduate student.I am trying to solve this problem: How to show that an ideal is maximal.
In this problem I am given the ring $\mathbb Q[x,y]$ and the ideal $I=(x-1,y^2+2)$ and I am asked to find whether this ideal is maximal.One way to show maximality is that the quotient ring is a field.The solution given in the above link follows that,as expected.But then they claim that first we can quotient out by $(x-1)$ and then by $(y^2+2)$.This is the point which I do not get.Why is it true that $\mathbb Q[x,y]/(x-1,y^2+2)\simeq \frac{\mathbb Q[x,y]/(x-1)}{(y^2+2)}$.The rest of the solution is clear to me that $\mathbb Q[x,y]/(x-1)$ is equal to $\mathbb Q[y]$ and we are trying to calculate $\mathbb Q[y]/(y^2+2)$ which is essentially $\mathbb Q[i\sqrt 2]$ which is a field.Please help me resolve this doubt.Does it follow from any theorem?
Comment: What does the title have to do with your question!? perhaps it should be improved
Answer: This is the ideal correspondence theorem. That is, let $R$ be a ring and $I\subset R$ an ideal. Ideals of $R/I$ correspond to ideals $J\subset R$ with $I\subset J$. Moreover, if $J'=\{x+I|x\in J\}$ is the ideal of $R/I$ corresponding to $J$, then
$$(R/I)/J'\cong R/J$$
In this particular case, $R=\mathbb{Q}[x,y]$, $I=(x-1)$, $J=(x-1,y^2+2)$.
Comment: So,this is third isomorphism theorem.
Comment: Yes, that's right.


Jenkins and Behat profile

Question: Hi i got some problem with my behat and jenkins configuration.
I would like run Behat test in a jenkins build with this configuration :
/behat.yml
default:
    extensions:
        Behat\MinkExtension\Extension:
            base_url: 'http://symfony.localvm/app_dev.php'
            browser_name: 'firefox'
            javascript_session: 'selenium2'
            goutte: ~
            zombie: ~
            selenium2: ~

jenkins:
    formatter:
        name: progress,junit,html
        parameters:
            output_path: ,app/build/behat,app/build/behat.html
    extensions:
        Behat\MinkExtension\Extension:
            base_url: 'http://symfony.localvm/app_dev.php'
            javascript_session: selenium2

And in my build.xml
    <target name="behat" description="Run behat test">
        <exec executable="../bin/behat" failonerror="false" inputstring=""></exec>
    </target>

(My composer)
    "require-dev": {
        "behat/behat": "2.4.*@stable",
        "behat/mink-extension": "@dev",
        "behat/mink-goutte-driver": "@dev",
        "fabpot/goutte": "@dev",
        "behat/mink-sahi-driver": "@dev",
        "behat/mink-zombie-driver": "@dev",
        "behat/mink-selenium2-driver": "@dev"
    },

But Jenkins doesn't use the jenkins profile in behat.yml, how I tell to Jenkins : "Hey Jenkins, user the jenkins profile please!" in the configuratio ? Or Jenkins must do it alone?
If I push the formatter parameter in the default profile and use the command line the .xml files are well generated.
Thx for help
Answer: i think You should add profile parameter in your build.xml, it's looks like
behat  --profile ios

behat documentation
Comment: Yes But Jenkins said :

    Configuration for profile "jenkins" can not be found. but this command works fine in my terminal...
Comment: How you build your app? from git/svn and phing?
Comment: It works now, I use your command with --config behat.yml before --profile jenkins. Don't know if it's the good way but looks good. Thx

Jenkins and Behat profile


Memory leak in gdk_pixbuf_new_from_file()

Question: Valgrind reports a memory leak when I run this simple test program:
#include <gdk-pixbuf/gdk-pixbuf.h>
int main() {
    GdkPixbuf* buf;
    GError* err = NULL;
    buf = gdk_pixbuf_new_from_file("test.jpg", &err);
    g_assert_no_error(err);
    g_object_unref(buf);
    return 0;
}

I'm aware of the issues regarding Valgrind and GLib/GDK/GTK, and of the several StackOverflow answers (such as this one, this other one, and others) regarding this issue.
For GLib it's enough to prefix the valgrind command with G_DEBUG=gc-friendly G_SLICE=always-malloc (though I still have some "still reacheable" leaks, which I ignore if they come from GLib).
However, with this small program I get a lot of "possibly lost" leaks. I have also tried other prefixes, such as G_DEBUG=resident-modules (suggested here) and G_SLICE=debug-blocks (suggested here), but the "possibly lost" leaks remain. I also tried several of the GNOME suppressions, namely the GDK one, but to no avail.
My question is: is my only alternative to create a suppression file for this case or is something wrong with the code?
The program was compiled with:
gcc -Wall -std=c99 -g -pedantic `pkg-config --cflags glib-2.0 gdk-pixbuf-2.0` pixbuf.c -o pixbuf `pkg-config --libs glib-2.0 gdk-pixbuf-2.0`

I'm using GDK-Pixbuf 2.30.7 (Ubuntu 14.04).
Thanks in advance.
Answer: All of the "possibly lost" blocks I see are from when types are registered with GObject.  These are really still reachable, it's just that valgrind doesn't understand how to reach them (admittedly it is a bit weird, I don't blame valgrind for being confused), so it reports them as "possibly lost" instead of "still reachable".
There is nothing wrong with your code, and there isn't really a leak in glib.  You should use a suppression file.
Comment: More information on suppression files: https://wiki.gnome.org/Valgrind
Answer: If gdk_pixbuf_new_from_file() fails for some reason (for example, the file does not exist), "buf" will be assigned to NULL and the error will be returned via "err".
Then g_assert_no_error(err) will terminate the program, but it will not free the memory to which "err" points. You'd be better off if you manage the error yourself and free "err" with g_free_error(err).
After the call to "gdk_pixbuf_new_from_file" remove the rest of the code replacing it by the following and see what you get as a result from Valgrind:
if (!buf) {
    g_printerr("%s\n", err->message);
    g_free_error(err);
}
else {
    g_object_unref(buf);
}

By the way, I'm not very familiar with Valgrind, I'm just pointing out the possible memory leak. Although at that point your program would have terminated and the kernel might be smart enough to reclaim the memory block it allocated to the program.
Comment: I believe you're missing the point. This is simply a code example, it's not production code. And of course the error is not occurring (when it occurs, g_assert_no_error() prints an error message). Thus the memory should be freed, which Valgrind reports otherwise.


Explaining why $c_1e^{-\beta t}\sin(rt) + c_2e^{-\beta t}\cos(rt) = Ae^{-\beta t}\cos(rt+\phi)$

Question: Could someone kindly explain to me why these two expressions are equal?
$$\begin{align}
x(t)&=c_1e^{-\beta t}\sin(rt) + c_2e^{-\beta t}\cos(rt) \\[4pt]
&= Ae^{-\beta t}\cos(rt+\phi)
\end{align}$$
with $r := \sqrt{\omega_0^2-\beta^2 }$, where $c_1$, $c_2$ or $A$ and $\phi$ are the pair of arbitrary real constants, while $\beta$ and $\omega_0$ are the known quantities and $t$ represents the independent variable.
Comment: Welcome to MSE.  Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to format your posts.  You'l get a lot more help if your questions are easy to read.
Comment: See, for instance, ["Why does $A\sin k(x+c)=a\sin kx+b\cos kx$ imply that $A=\sqrt{a^2+b^2}$ and $\tan c=−b/a$?"](https://math.stackexchange.com/questions/856580/why-does-a-sinkxc-a-sinkxb-coskx-imply-that-a-sqrta2b2-and/856600#856600).
Answer: $x(t)$ is a linear combination (addition) of a $\sin$ and $\cos$ functions. Because a $\sin$ function can be expressed as a shifted $\cos$ function, we can express $x(t)$ as an addition of two $\cos$ functions (one is shifted, the other one is not shifted), which results in a (shifted) $\cos$ function. That's why $x(t) = a_1 \sin(bt) + a_2 \cos(bt)$ with $a_1 = c_1~e^{-βt}, a_2 = c_2~e^{-βt}$ and $b=\sqrt{ω_0^2-β^2 }$ is the same as $x(t) = A~e^{-βt}~\cos\left(b~t+ φ\right)$, if we choose/calibrate the right constants $A,c_1,c_2$ and $\varphi$ and we can express the amplitude $A$ and the shift angle $\varphi$ in terms of the amplitudes $c_1$ and $c_2$. Just set some values for $t$ like $t = 0$ and $t = \frac{\pi}{2b}$. Then we get $x(t=0)=c_2 =A\cos(\varphi) \Rightarrow c_2^2 = A^2\cos^2(\varphi)$ and $x(t=\frac{\pi}{2b})=c_1=A\cos(\frac{\pi}{2}+\varphi)=-A\sin(\varphi) \Rightarrow c_1^2 = A^2\sin^2(\varphi)$. Then add the two equations and use the identity $\sin^2(x)+\cos^2(x)=1$ to get $A = \sqrt{c_1^2+c_2^2}$. Divide the equations to get $\tan(\varphi)=\large{\frac{c_1}{c_2}}.$
This equation is a solution for some mechanical problem: Differential equation for describing the swing of a spring.
Comment: Thank you Mr Hossam for your clear answer.
Comment: It's not very clear, but you get the idea
Comment: I'm a new user and I still don't know how to use the forum well, but I'll try to explain my questions more clearly the next time. Thanks again.
Answer: $$\begin{align*}x(t) &= Ae^{-\beta t}\cos(rt+\phi) \\
\\
&=Ae^{-\beta t}\left[\cos(rt)\cos(\phi)-\sin(rt)\sin(\phi)\right]\\
\\
&=Ae^{-\beta t}\left[-\sin(\phi)\sin(rt)+\cos(\phi)\cos(rt)\right]\\
\\
&=-A\sin(\phi)e^{-\beta t}\sin(rt)+A\cos(\phi)e^{-\beta t}\cos(rt)\\
\\
&= c_1 e^{-\beta t}\sin(rt)+c_2e^{-\beta t}\cos(rt)\\
\end{align*}$$
If you need an explanation of the Ptolemy (cosine angle sum) formula used in the above derivation, this site provides one:
https://www2.clarku.edu/faculty/djoyce/trig/ptolemy.html


PHP comparing values with a for loop in arrays gives an offset error

Question: I have 2D arrays where I have to keep comparing the next value.
I am using a for loop to go through all values and I am getting an offset error because when it reaches the last array, it wants to check the next array, which does not exist. How can I prevent that? I know that ($items[$row][0]!=$items[$row+1][0]) is the issue. Should I not use a for loop? What I do not understand is that the code below does not give any error. If $items[$row+1][0] is the problem when it reaches the last array, shouldn't $items[$row-1][0] give an error as well when it is checking the first array in the arrays?
if ($row==0 || ($row>0 && $items[$row][0]!=$items[$row-1][0]) )

But this one is not ok.

Notice: Trying to access array offset on value of type null
  Notice: Undefined offset

        if (($row<$num_rows && ($items[$row][0]!=$items[$row+1][0]))||$num_rows==$is_odd)  {
        //$is_odd is the number of last array.
        //$num_rows is the total number of arrays.
        echo "

";

    }

Comment: Clearly, you should compare the array only up to the next-to-last element, and no further. Your first example explicitly checks that $row is *not* zero, so $row-1 always exists.
Comment: can you show your complete for-loop?
Comment: As a quick fix, you can use the null coalesce operator ?? - `$items[$row+1][0] ?? -1` (the -1 would be some dummy value which you can set to something appropriate for your case).
Comment: @NigelRen That's good to know. Thank you.
Answer: in your condition check next index is exist or not like
if ((!empty($items[$row + 1]) && $row < $num_rows && ($items[$row][0] != $items[$row + 1][0])) || $num_rows == $is_odd) {
    //$is_odd is the number of last array.
    //$num_rows is the total number of arrays.
    echo "

";
}

Comment: Thank you. I didn't know that empty can check the index. It worked. Can't believe I struggled for a couple of days for this...


Is there a convenient way to find $[G,G]$?

Question: I am concerned with finding the commutator subgroup $[G,G]$ of a finite group $G$. Recall that the commutator subgroup $[G,G]$ of a finite group $G$ is given by

$[G,G] = \langle\{g^{-1}h^{-1}gh: g,h \in G\}\rangle$

I wondered if there are any propositions or theorems that make finding the commutator subgroup easier than merely just testing every pair $g,h$ of elements from $G$. Clearly, if we have a group such as $S_5$, this process could take a long time since $|S_5| = 120$. Is there a quicker way to find $[G,G]$ than just doing this process manually?
Comment: The commutator subgroup is the smallest normal subgroup such that the quotient is abelian.
Comment: To address the case of $S_5$, the commutator subgroup of any group is normal, and the only normal subgroups of $S_5$ are the trivial group and $A_5$. So you just need to find a single nontrivial commutator to conclude that the commutator subgroup is $A_5$.
Comment: You gave a wrong definition of a commutator subgroup: You also need to take products of commutators.
Comment: Your definition does not define a subgroup, just as I wrote.
Comment: Actually you also need to rule out that the commutator subgroup of $S_5$ is itself! My bad. But it is easy to see that any commutator must be an even permutation...
Comment: @CheerfulParsnip alternatively, one can use the universal property of the abelianization $G/[G,G]$; in this case, since $S_{5}/A_{5} \cong \mathbb{Z}/2\mathbb{Z}$, $S_{5}/[S_{5},S_{5}]$ cannot be trivial.
Comment: @MoisheKohan Could you point out what's wrong with the definition? Maybe you could suggest an edit.
Comment: $[G,G]$ is not the set of commutators, it is the subgroup generated by the commutators. So a general element is not a commutator, but a product of them.
Comment: @Mark Oh okay. I see what you're saying. How would we write that? Maybe seeing it written would help clarify my confusion.
Comment: I have edited, now it is written correctly.
Comment: @Mark Thank you
Answer: Is there a convenient way to find find the commutator subgroup $[G,G]$?
The answer depends on what we find convenient. We can use group theory
to determine the commutator subgroup for many well known groups. These results are already known.
That's very convenient. For example we know that
$$
[S_n,S_n]=A_n, \; n\ge 2.
$$
Similarly we know that
$$
[GL_n(K),GL_n(K)]=SL_n(K), \; n\ge 2.
$$
Of course one has to prove this using group theory. But certainly this will be more convenient than "doing it manually", where you were afraid that "this process could take a long time since $|S_n|=n!$ is large".


How to force drupal 7 to load HTTPS assets?

Question: Environment:
apache + ssl + domain access
Our drupal 7 site uses domain access multiple sub domains
our server is SSL enabled
if I do not set $base_url in settings.php then all of our assets our loaded via HTTP and the user receives a mixed content error
If I DO set $base_url users are redirected to the default subdomain (e.g. foo.blah.com) instead of their current domain (e.g. bar.blah.com)
My question is, how do I force drupal to load all assets via HTTPS?
That way I can uncomment the #base_url
Answer: I updated settings.php with: $base_url = 'https://'.$_SERVER['SERVER_NAME'];
Comment: This is a great way to ensure all resources are requested over https if you are using the [domain access module](https://www.drupal.org/project/domain). In a project i work on this module kept trying to load css/js etc... over http instead of https, regardless of the activation of the https proto in the domain settings or the various ways of forcing https in the settings.php file.
Comment: Drupal 7 doesn't use $base_url so this setting does nothing, $base_url is a Drupal 6 artifact.
Answer: if everything(SERVER AND HOST SETTINGS)  is ok just $conf['https'] = TRUE; in your settings.php.
According to  Enabling HTTP Secure (HTTPS)

Drupal configuration :
If you want to support mixed-mode HTTPS and HTTP sessions open up sites/default/settings.php and add $conf['https'] = TRUE;. This
  enables you use the same session over HTTP and HTTPS both -- but with
  two cookies where the HTTPS cookie is sent over HTTPS only. You will
  need to use contributed modules like securepages to do anything useful
  with this mode, like submitting forms over HTTPS and so on. While your
  HTTP cookie is still vulnerable to all usual attacks, a hijacked
  insecure session cookie can only be used to gain authenticated access
  to the HTTP site. It will not be valid on the HTTPS site. Whether this
  is a problem or not depends on the needs of your site and the various
  module configurations. For example, if all forms are set to go through
  HTTPS and your visitors can see the same information as logged in
  users then this is not a problem.
For even better security, leave $conf['https'] at the default value (FALSE) and send all authenticated traffic through HTTPS and use
  HTTP for anonymous sessions. Once again contributed modules like
  Secure Login or 443 Session can help you here. Drupal 7 automatically
  enables the session.cookie_secure PHP configuration on HTTPS sites,
  which causes SSL-only secure session cookies to be issued to the
  browser.
  For best-possible security, set up your site to only use HTTPS, and respond to all HTTP requests with a redirect to your HTTPS site.
  $conf['https'] can be left at its default value (FALSE) on pure-HTTPS
  sites. Even then, HTTPS is vulnerable to man-in-the-middle attacks if
  the connection starts out as a HTTP connection before being redirected
  to HTTPS. Use the HSTS module or set the Strict-Transport-Security
  header in your webserver to help prevent users from accessing the site
  without HTTPS.

also you can use Secure Pages module
Description of module :

A small process which will redirect the required pages to a SSL version of the page.

Update
  also you can  in settings.php do: $base_url = 'https://'.$_SERVER['SERVER_NAME'];.
Comment: @noah also you can set auto redirect in your custom module in 'hook_init' and redirect every page to `https` ( but I think better way is achieve it in `.htacess` )
Comment: posting answer below
Comment: @noah Then what happened?
Comment: with the dynamic base_url,
https:// is always loaded, and domain access still has control over setting the subdomain

plus, in the drupal docs it says "or best-possible security, set up your site to only use HTTPS, and respond to all HTTP requests with a redirect to your HTTPS site. $conf['https'] can be left at its default value (FALSE) on pure-HTTPS sites. "

if setting conf[https] is for using mixed mode, we require an https only site. i think there is another issue involved with drupal loading our server assets over http,
Comment: Don't use hook_init. Use .htaccess.
Answer: The Secure Pages module does this.

A small process which will redirect the required pages to a SSL version of the page.


Why there is more `deconstructor` calls than `constructor` calls?

Question: I am trying to study C++ using stl, I noticed that there are more deconstruct calls than construct calls, I am wondering whether I missed anything.
Here is the code:
#include <vector>
#include <iostream>
using namespace std;

class Person {
  friend ostream &operator<<(ostream& os, const Person &p) {
    os << p.name << endl;
    return os;
  }
  string name;

public:
  Person() {
    cout << "created " << this->name << endl;
  };
  Person(string name):
    name{name} {
      cout << "created " << this->name << endl;
    }
  ~Person() {
    cout << "deconstructor " << this->name << endl;
  }
  bool operator<(const Person &rhs) const {
    return this->name < rhs.name;
  }

  bool operator==(const Person &rhs) const {
    return (this->name == rhs.name);
  }
};

int main(int argc, char** argv) {
    vector<Person> vec {{"test1"}, {"test2"}};
    Person p {"test2"};
    vector<Person>::iterator it = find(vec.begin(), vec.end(), p);
    Person p2 {"test3"};
    vec.insert(it, p2);
    for (auto &p : vec) {
      cout << p;
    }
}

And this is the output:
created test1
created test2
deconstructor test2
deconstructor test1
created test2
created test3
deconstructor test2
deconstructor test1
test1
test3
test2
deconstructor test3
deconstructor test2
deconstructor test2
deconstructor test3
deconstructor test1

test1 has been deconstructed three times, but only created once.
Any explanation?
Thanks.
Comment: See [this answer](https://stackoverflow.com/questions/56799469/why-is-emplace-back-behaving-like-this/56799500#56799500) and the corresponding question.
Answer: Don't forget to create a copy constructor.
Person(const Person &p): name{p.name} {
    cout << "created " << this->name << endl;
}

Comment: One should also implement the move constructor, see the answer it the merged to question


Existe a possibilidade de transformar uma aplicação construída com PHP em PWA?

Question: Tenho uma aplicação construída com o Code Igniter e desejo transformá-lo em um Progressive Web App, Quais arquivos eu deveria armazenar em cache? Qual seria a melhor estratégia?
Answer: Não, isto não faz sentido. PWA é uma aplicação de frontend, e PHP é usado no backend. Por outro lado, qualquer PWA feito corretamente se comunica com qualquer backend.


Multiple OR conditions are not working with Rules

Question: Multiple OR conditions are not working with the Rules module in Drupal 7.
I have profile2 module. And I want to notify user with an email if one of the fields from the user's profile is empty, I have written a rule but multiple OR conditions are not working.
Any help?
Comment: I'm voting to close this question as off-topic because it's a bug report to a third-party module and this bug should be reported in the mentioned module's issue queue on drupal.org not here.
Comment: can u please provide the rule event,conditions and actions elaborately or provide the rule export
Comment: event "After user has logged in"
Comment: Event : "After user has logged in" ,    Condition : "data value is empty OR data value is empty" , Action : "send html mail" if any of the profile field is empty.
Comment: use rules debugger to debug the execution of your rule..eg) to check whether the condition returns true,acion gets executec or not.you can enable debugger in /admin/config/workflow/rules/settings
Comment: It's not a bug report. Almost certainly this is configuration error. Without an export we can't be sure because a verbal description of the configuration is insufficient. But saying 'Condition : "data value is empty OR data value is empty"' implies that the condition was set up improperly - there should be an OR condition followed by (indented) data value is empty, followed by (indented) data value is empty. If the OR is between the two conditions, and if the OR is at the same level of indentation, then what you really have is an AND of THREE conditions, one of which is the empty OR.
Answer: I have tried it and found out that it is working fine for main profile but if you create any other profile it is not working. I debugged and found out that it is throwing exception unable to get the data property as the parent data structure is not set while executing the function value() in entity.wrapper.inc which is called from function rules_condition_data_is_empty($data). I will debug it further when I have time, but as of now I hope this helps.


Python dealing with repeated eigenvalues

Question: Consider A a real symmetric matrix and
import scipy
(s,u)=scipy.linalg.eigh(A)

If A has repeated eigenvalues then the columns of u are not necessarily orthonormal. What is the most efficient way to obtain a basis of orthonormal eigenvectors in python?
Comment: I agree, and I'm surprised that `scipy` does not do this by default... could you edit your post to add a small example where the vectors are indeed not orthonormal?
Comment: Seems more like a maths question than a programming question...
Answer: Use eigh() instead of eig(), since eigh() is specially designed to deal with complex hermitian and real symmetric matrices.
In [1]: import numpy as np
...: sigma = np.array([[ 7, -3, 2],
...:                  [ -3, -1, 6],
...:                  [  2,  6, 4]])

In [2]: val, vec = np.linalg.eig(sigma)

In [3]: val
Out[3]: array([ 8., -6.,  8.])

In [4]: vec
Out[4]:
array([[ 0.96362411, -0.26726124, -0.06680865],
       [-0.22237479, -0.80178373,  0.56878282],
       [ 0.14824986,  0.53452248,  0.81976991]])

Observe that vec.T @ vec is not an identity matrix:
In [5]: vec.T @ vec
Out[5]:
array([[ 1.00000000e+00,  0.00000000e+00, -6.93306162e-02],
       [ 0.00000000e+00,  1.00000000e+00,  1.11022302e-16],
       [-6.93306162e-02,  1.11022302e-16,  1.00000000e+00]])

Now let's use eigh():
In [6]: val, vec = np.linalg.eigh(sigma)

In [7]: val
Out[7]: array([-6.,  8.,  8.])

In [8]: vec
Out[8]:
array([[-0.26726124,  0.87287156, -0.40824829],
       [-0.80178373,  0.03357198,  0.59667058],
       [ 0.53452248,  0.48679376,  0.69088172]])

Observe that vec.T @ vec is an identity matrix:
In [9]: vec.T @ vec
Out[9]:
array([[1.00000000e+00, 5.78786501e-17, 5.56940743e-17],
       [5.78786501e-17, 1.00000000e+00, 4.61864879e-17],
       [5.56940743e-17, 4.61864879e-17, 1.00000000e+00]])


Adicionar input com JavaScript

Question: Olá, sou novo aqui. Gostaria de saber como fazer meus input's gerados por javascript herdar a formatação css que meu input html tem. Segue o código:

    <title>Pedidos</title>

    <form method="POST">
            Receita
            <input type="text" name="receita" placeholder="Ex: Pão de queijo">

Pedidos:

            Cód. Produto:
            <input type="text" name="codProduto[]" placeholder="Cód. Produto">

            Quantidade:
            <input type="text" name="razao[]" placeholder="Quantidade">

            Desconto:
            <input type="text" name="desconto[]" placeholder="Desconto">

  <button type="button" id="adicionar">Adicionar</button>
  <button type="submit">Cadastrar</button>

    </form>

Comment: vc quer adicionar uma nova linha igual a primeira?
Comment: Isso, quero seguir a tabela.
Answer: Para criar novas linhas no seu HTML, você pode utilizar insertRow e insertCell
No caso do seu código, ficaria:

const adicionar = document.getElementById("adicionar");

adicionar.addEventListener("click", function (event) {

var table = document.getElementById("tabela");
var row = table.insertRow(2);

row.insertCell(0).innerHTML = "Cód. Produto:";
row.insertCell(1).innerHTML = `<input type="text" name="codProduto[]" placeholder="CodProduto"> `;
row.insertCell(2).innerHTML = "Quantidade";
row.insertCell(3).innerHTML = `<input type="text" name="razao[]" placeholder="Quantidade">`;
row.insertCell(4).innerHTML = "Desconto";
row.insertCell(5).innerHTML = `<input type="text" name="desconto[]" placeholder="Desconto">`;

});

    <title>Pedidos</title>

    <form method="POST">
        Receita
        <input type="text" name="receita" placeholder="Ex: Pão de queijo">

                    Pedidos:

                Cód. Produto:

                    <input type="text" name="codProduto[]" placeholder="Cód. Produto">

                    Quantidade:

                    <input type="text" name="razao[]" placeholder="Quantidade">

                    Desconto:

                    <input type="text" name="desconto[]" placeholder="Desconto">

        <button type="button" id="adicionar">Adicionar</button>
        <button type="submit">Cadastrar</button>

    </form>

Comment: Victor Jordan não deu certo, mesmo assim obrigado. Não teria como esses novos inputs seguir minha tabela?
Comment: Deu certo, mas como eu faço para cada input ficar a baixo do outro?
Comment: Acho que a maneira mais simples de você fazer isso seria fazer o append em uma `div` e definir que esta div tera o estilo `display: block`. Com isto, esta sua `div` vai ocupar uma linha inteira! Estou fazendo um CodePen aqui para te exemplificar
Comment: Certo, obrigado.
Comment: Acho que o que você quer é isso aqui, não é? [CodePen](https://codepen.io/victorjordan95/pen/OZxeaG?editors=1010)
Comment: Isso mesmo. Entendi agora, muito obrigado.
Answer: O ideal é clonar a tr e adicionar na tabela, evitando esse monte de divs desnecessários e que ao meu ver fere a semântica da tabela, adicionando divs entre as linhas.
Pode fazer desta forma:

var tabela = document.body.querySelector("table tbody"); // seleciona o corpo da tabela
adicionar.addEventListener("click", function (event) {
   var clone = document.body.querySelectorAll("table tr")[1].cloneNode(true); // seleciona a segunda linha
   var els = clone.querySelectorAll("input"); // seleciona os inputs do clone

   for(var x=0; x<els.length; x++){
      els[x].value = ''; // limpa os campos do clone
   }

   tabela.appendChild(clone); // insere o conle na tabela
});
<form method="POST">
   Receita
   <input type="text" name="receita" placeholder="Ex: Pão de queijo">

Pedidos:

   Cód. Produto:
   <input type="text" name="codProduto[]" placeholder="Cód. Produto">

   Quantidade:
   <input type="text" name="razao[]" placeholder="Quantidade">

   Desconto:
   <input type="text" name="desconto[]" placeholder="Desconto">

   <button type="button" id="adicionar">Adicionar</button>
   <button type="submit">Cadastrar</button>
</form>
Comment: Deu certo!Muito bom, mas agora como faço pra coletar os dados de cada input?
Comment: pelo `name` vc consegue.
Comment: Se vc for enviar pelo form, o backend vc pega pela array de cada input... se quiser pegar pelo JavaScript, pelo `name` é fácil tb
Comment: Quero pegar pelo FORM backend, mas não estou conseguindo.

Adicionar input com JavaScript


What are the main drum elements used in beatmaking?

Question: What are the main types of drum samples used to create a hiphop beat? I've narrowed it down to three:

Kick
Snare
Hihat

Are there any more? I think there's also an 808 but I think it's a type of kick. Also I noticed there's an open-hihat too. But I'm wondering if that would be considered one of the main basic types. Are there any other types I'm missing?
Comment: I honestly didn't really get the gist of the question -  to me it's a bit like someone asking *"Are the main chords in rock music I, IV and V?"* in that the answer is *arguably* yes, but it would be dangerous for them to take that answer too literally. So I want to know what someone's actually going to *do* with the answer, so I know I'm not encouraging them to do something dangerous!
Answer: Beatmaking stems from the use of a regular acoustic drum kit in rock, pop, and perhaps especially R&B and funk. Early beats that were made with drum machines or samples were usually meant to re-create beats played on actual drum kits. The most commonly used pieces of the drum kit are just as you list:

Kick
Snare
Hi-hat (open and closed)

Many of the most famous sampled beats from funk and R&B that were used in early hip hop use just those three elements (including probably the most sampled beat of all time, the "Funky Drummer" beat). So today, those are the most used and usually the most important elements of a beat.
The other most popular pieces of a typical drum kit, that are commonly used in making beats, are:

Hi, mid, and low toms
Crash cymbal(s) (a rock kit normally has a higher crash and a lower crash)
A ride cymbal

In the late 70s and early 80s, synthesizer manufacturers started to create drum machines, and this really gave birth to beatmaking and the foundation of hip hop and rap. The different drum machines added additional percussion elements to make their devices more appealing to musicians and producers, including:

Side stick (a way to play the snare drum)
Cowbell
Hand claps
Tambourine
Claves
Shaker/cabasa

The different drum machine technologies gave each product its own sound. Many drum machines were expensive and mainly used by producers on high-budget tracks, but two drum machines, both by Roland, were more affordable and became the most popular drum machine for hip hop and rap acts. They were the Roland TR-808 and TR-909.
The TR-808 in particular had a unique sound that was based on analog synthesis, not digital samples (which many other drum machines used). The 808 is legendary for its kick sound, which had a deep and punchy sound that you couldn't really get anywhere else. The term "808" doesn't refer to a kick sound, per se - it could refer to any TR-808 style electronic drum sound - but the most popular 808-style sound is the kick sound from the 808, so you will often come across the concept of an "808 kick", or "let's add a little 808 in there".

Most drum beats serve two purposes in popular music: They add musical interest and they map out the rhythm for the song. One way to make a beat that serves both purposes is to start with a traditional basic map of the rhythm and then make some changes to make it interesting. The basic rhythm map can be made with only closed hi-hat, snare, and kick, and has these elements:

Hi-hat on every 8th note (8 hits per 4/4 measure)
Kick on the down beats (1st and 3rd beat in 4/4 time)
Snare on the up beats (2nd and 4th beat in 4/4 time)

From there, you can vary things in an infinite number of ways. Understanding the basic rhythm map (which no one ever uses as the beat for a song - it's just too boring) will help you hear and understand beats as well as program your own.
Also check out these classic 80s drum machines and their factory or famous beats:

The LinnDrum
The Oberheim DMX
The Roland TR-808
The Roland TR-909
Comment: You can't forget the two predecessors to the 808, the [CR-78](https://en.wikipedia.org/wiki/Roland_CR-78) & the [TR-606](https://en.wikipedia.org/wiki/Roland_TR-606) - and no history of the dum machine would be complete without the [Drumulator](https://en.wikipedia.org/wiki/E-mu_Drumulator)


Does the t statistic have uses unrelated to hypothesis testing?

Question: Are there non-hypothesis testing uses for Student's t statistic?
Comment: Are you interested in alternative uses of Student's t-distribution in and of itself, or are you only focused on the concrete object of the test statistic $\frac {{\bar {X}}-\mu }{S/{\sqrt {n}}}$ ?
Comment: Hmm, but the $\mu$ in the statistic is typically set in reference to some null hypothesis, right? I don't see how you can talk about "the statistic" without reference to the null hypothesis to which it is linked. Even setting $\mu=0$ is implicitly testing against the null $H_{0}: \mu = 0$.

The distribution in and of itself is interesting because it's symmetric and bell-shaped with fatter tails, so we can free it from the hypothesis testing land a bit by just using it to model extreme outcomes, but that's using a parametric form to fit data, and not physically calculating t-statistics.
Comment: @klumbard Amplify that into an answer! (And be sure to point out the implicit $\mu=0$ for $t= \frac{\theta}{\hat{\sigma}_{\theta}}$.)
Comment: When you're not testing hypotheses, $t$ is the same as $z.$  For its many uses search here (or the Web) for *standardization.*
Comment: The pivotal quantity arises also in construction of confidence intervals for $\mu$; does that count?
Comment: @whuber Permit me to say .
Comment: @klumbard I would be happy to entertain answers that bring in the distribution, but am more specifcally interested in the statistic.
Comment: @whuber I am not sure I understand: standardizing by a population versus sample SE should still differentiate $z$ from $t$?
Comment: In a $z$ test, the SD is also the (same) *estimate* of the SD used in a $t$ test.  The tests differ concerning which *distribution* to use for computing p-values.
Answer: A "hypothesis test" in the strictest sense always results in a binary outcome of either rejecting or failing to reject a null hypothesis. T-statistics are generally turned into p-values, which are then compared against some pre-defined threshold to make that binary determination. It is possible to use the t-statistic itself, however, as a general measure of "deviation from the null", without ever having to take the final step of testing whether the null hypothesis should be rejected or not. Using a t-statistic in this way is still derived from a hypothesis testing framework, but does not actually result in a test of whether the null should be rejected or not, so I'd argue this is not strictly a "hypothesis test".
As an example, the t-statistic can be used as a means of ranking features by significance, while accounting for the directionality of the differences. Gene set enrichment analysis, for example, searches for sets of consistently up- or down-regulated genes, so the directionality of differences is important for this method. Ranking features by their p-value will draw no distinction between up- and down-regulated genes, and simply put the most significant genes at the top of the list. Ranking by the t-statistic, on the other hand, will put the most significant up-regulated genes at one end of the list, and the most significant down-regulated genes at the other end. Although the magnitude of the t-statistic is directly related to the p-value, the sign of the t-statistic is lost when calculating a p-value for a hypothesis test. Ranking genes in this way respects the directionality and how incompatible with the null hypothesis each gene is, but does not actually make any determination if any gene is "significantly dysregulated" or not.
Comment: You more or less ignored the "non-hypothesis testing uses" which is the substance of my question.
Comment: Ranking by p-values is so controversial and so antithetical to the meaning of p-values that its meaning and applicability are often dismissed out of hand.
Comment: @Alexis I'd argue the analysis I'm describing isn't quite a hypothesis test, since there's no determination of statistical significance, no pre-defined probability threshold, and does not seek to reject or fail to reject a null hypothesis. Here, I'm using the t-statistic in a way that does not directly test the hypothesis of equal means. But I do see your point that the t-statistic itself comes from a hypothesis-testing framework of comparing two groups under a set of assumptions. I can't think of another way to get to the t-stat without that kind of comparison, though.
Comment: Contrast: "since there's no determination of statistical significance" with "a means of ranking features by significance"
Comment: @whuber Ranking genes by some measure of differential expression, whether that's the t-stat or p-value or effect size is a cornerstone of GSEA-style analysis and has been applied successfully many times over, with the original paper having been cited over 20,000 times. I too tend to view p-values as a continuous "measure of surprise" rather than the binary Neyman-Pearson "significant or not", as described at https://stats.stackexchange.com/questions/137702/are-smaller-p-values-more-convincing. But that's a whole other can of worms I'd rather not open here.
Comment: *p*-values are ***only*** a "measure of surprise" when situated against a specific null hypothesis. *p*-values measure the probability of observing some value (e.g., a $t$ statistic) **conditional on $\boldsymbol{H_{0}}$ being true**.
Comment: @Alexis Agree, the t-stats computed here implicitly require a null and alternative hypothesis, so it's not totally divorced from a hypothesis testing framework. But I do think it's a little different since we don't determine, or even care, whether or not to reject the null hypothesis. To me, a true hypothesis test always results in a binary outcome of rejecting or failing to reject the null, but that's not what the t-stat is used for here.
Comment: Color me mollified!
Answer: When you ask about "the t-statistic", I think about the concrete quantity $$\frac {{\bar {X}}-\mu }{S/{\sqrt {n}}}$$
To actually calculate this quantity, we have to specify $\mu$. This is typically chosen in reference to some given null hypothesis. So to me it seems awkward to try to disentangle "the statistic" from the null hypothesis to which it is implicitly linked by $\mu$. Setting $\mu$ to 0, for example, which you're implicitly doing when you type t.test(rnorm(10))$statistic into R, is implicitly related to the hypothesis test $H_0: \mu = 0$.
Where I think of Student's t-distribution as useful is as a parametric form for fitting to data. At the end of the day, it's just another symmetric, bell-shaped distribution. It just has fatter tails than a Gaussian. So it can be used to model things for which you'd like to preserve that symmetry and bell-shape, but give the extreme outcomes more probability mass than a Gaussian does. I know it's used in finance to model asset-returns (link 1, link 2) for example, but I can't speak to how successful or useful these kinds of models are because I don't use them myself.
I'd suspect them to be of particular use to hierarchical modelers who have some prior knowledge that points to fat tails. Gelman briefly discusses using the t instead of the the Gaussian in fat-tail situations in section 17.2 of Bayesian Data Analysis.
Comment: +1 Thank you! I will wait a bit to check "accepted," in case anyone else would like to weigh in.
Comment: +1 If the question is extended to the "t-distribution" from the "t-statistic," there are many [Bayesian uses](https://en.wikipedia.org/wiki/Student%27s_t-distribution#In_Bayesian_statistics) that certainly wouldn't be considered hypothesis tests.


Expected number of draws from an urn (without replacement) to get 2 different coloured balls

Question: An urn has $N=18$ black balls and $M=2$ white balls. What is the mean number of balls one must draw to get two different colours. My solution so far is extremely ugly (though effective):
$$\mathbb{E}_{N,M} = \sum_{k=1}^N{(k + 1)\left(\prod_{i=1}^k{\frac{N + 1 - i}{N + M + 1 - i}}\right)\frac{M}{N + M - k}} +
\sum_{k=1}^M{(k + 1)\left(\prod_{i=1}^k{\frac{M + 1 - i}{N + M + 1 - i}}\right)\frac{N}{N + M - k}}$$
I tried to map this problem to use a negative hypergeometric distribution, but had no luck. Can we use it? Is there a simpler solution to this problem?

Using Mathematica (and assuming $N$ and $M$ are positive integers), one can simplify the expression to:
$$1+\frac{N}{1+M}+\frac{M}{1+N}$$
Though I fail to grasp the intuition behind this.
Comment: See the answer at http://stats.stackexchange.com/a/110456
Answer: You can indeed use the negative hypergeometric distribution to solve that problem. When drawing from a population of $N$ elements without replacement where $K$ of them are successes, the mean number of successes you'll draw until you draw $R$ failures is given by:
$$
f(N,K,R) = E[x \sim NHG_{N,K,R}] = R ~ \frac{K}{N-K-1}
$$
Back to your problem. Consider two cases: one in which the first ball drawn is black (p = 18/20) and the other in which the first ball is white (p = 2/20). You can then calculate your average for each case and weigh them as follows:
$$
\frac{18}{20} ~ f(19, 17, 1) + \frac{2}{20} ~ f(19, 1, 1) + 2
$$
The last term refers to the first draw (which is considered separately) and the last "failure" draw, which is not counted by the negative hypergeometric distribution.


slow website load and high memory usage

Question: my site has been slowed down last couple of days ... some image doesn't show up ... i got
408 Request Time-out: Server timeout waiting for the HTTP request from the client

couple of times which never happened before .
i did a little performance checking , basically top command in ssh
this is the result
http://up.akstube.com/images/vdtebe9sr10si1eyycd.jpg
as you can see memory usage is very high ... or i think it is .
i've rebooted the server ... it wend down but after while  it goes up again ....
(this is about an hour after reboot  )
http://up.akstube.com/images/49xjeylxy0st7vwn4ojl.png
after half an hour =>
    top - 16:14:22 up  1:56,  2 users,  load average: 0.62, 0.90, 1.15
    Tasks: 303 total,   1 running, 302 sleeping,   0 stopped,   0 zombie
    Cpu(s):  8.0%us,  0.2%sy,  0.0%ni, 91.4%id,  0.0%wa,  0.0%hi,  0.3%si,  0.0%st
    Mem:  32840004k total, 21037648k used, 11802356k free,   430832k buffers
    Swap:  1050616k total,        0k used,  1050616k free, 16527108k cached

right now
[root@ns4008353 ~]# top
top - 16:33:25 up  2:15,  2 users,  load average: 0.88, 0.94, 0.98
Tasks: 303 total,   3 running, 300 sleeping,   0 stopped,   0 zombie
Cpu(s):  6.8%us,  0.2%sy,  0.0%ni, 92.8%id,  0.0%wa,  0.0%hi,  0.1%si,  0.0%st
Mem:  32840004k total, 22388160k used, 10451844k free,   434964k buffers
Swap:  1050616k total,        0k used,  1050616k free, 17324104k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 7532 mysql     20   0 3750m 492m 5556 S 18.0  1.5  49:53.58 mysqld
12903 apache    20   0  232m  40m 4864 S 16.3  0.1   0:56.74 httpd
 7748 apache    20   0  235m  43m 5256 S 11.6  0.1   1:33.36 httpd
 8010 apache    20   0  262m  70m 4856 R  6.7  0.2   1:32.05 httpd
 7747 apache    20   0  235m  43m 5220 S  1.3  0.1   1:06.37 httpd
 7749 apache    20   0  222m  30m 5164 S  1.3  0.1   1:58.53 httpd
 7996 apache    20   0  250m  59m 5476 S  1.3  0.2   1:37.37 httpd
   10 root      20   0     0    0    0 S  0.3  0.0   0:09.72 rcu_sched
 7714 apache    20   0  265m  73m 4972 S  0.3  0.2   1:34.53 httpd
 7905 named     20   0  669m  24m 3020 S  0.3  0.1   0:02.01 named
 7999 apache    20   0  232m  40m 4968 S  0.3  0.1   1:17.67 httpd
20865 root      20   0     0    0    0 S  0.3  0.0   0:01.05 kworker/2:2
21491 root      20   0 15212 1308  852 S  0.3  0.0   0:01.38 top
23810 root      20   0 15212 1340  852 R  0.3  0.0   0:00.07 top
    1 root      20   0 19404 1568 1268 S  0.0  0.0   0:00.58 init
    2 root      20   0     0    0    0 S  0.0  0.0   0:00.00 kthreadd

free m
[root@ns4008353 ~]# free -m
             total       used       free     shared    buffers     cached
Mem:         32070      21897      10173          0        424      16955
-/+ buffers/cache:       4516      27553
Swap:         1025          0       1025

do you think this the reason of slow response ? is there any comment to get more info about what is using the memory ?

i have  a dedicate server :
Processor Name  Intel(R) Xeon(R) CPU E3-1245 V2 @ 3.40GHz
Vendor ID   GenuineIntel
Processor Speed (MHz)   1600.000
Total Memory    32840004 kB
Free Memory 10416752 kB
Total Swap Memory   1050616 kB
Free Swap Memory    1050616 kB
System Uptime   0 Days, 2 Hours and 22 Minutes
Apache 2.2.24   Running
DirectAdmin 1.43.0  Running
Exim 4.76   Running
MySQL 5.5.31    Running
Named 9.8.2rc1  Running
ProFTPd 1.3.4d  Running
sshd    Running
dovecot 2.2.4   Running

    Php 5.3.26  Installed
after looking in my log files i've seen lots of this error
[Sat Sep 28 00:15:41 2013] [error] [client 18.104.22.168] Request exceeded the limit of 10 internal redirects due to probable co
nfiguration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace

Comment: Any other information of interest, like has your site gotten a lot more popular, or an uptick in HTTP requests per minute? Or any new code changes on the site? Are the images that are timing out hosted locally (hard disk) or externally (NFS mount or third party website)?
Comment: Also do some local requests for webpages (from the server) and from some various different sites other than your work or office to compare. Could be your provider is messing up routing or traffic intermittently, or your home ISP just really sucks. If a local request never times out, that's the case. If not, then you have server/code issues.
Comment: 'some image doesn't show up', is this a test you did or someone else said happened? What is your client timeout set to on the server?
Comment: @inetplumber , no it has about 100-150 thousand visits per day . no changes in the code , images are hosted internally
Comment: just viewed your edit, so now `grep 126.96.36.199` in your transfer log and see what page/code the request triggered. Could be a bug or a maliciously crafted request that's not being protected against (also a bug I guess).
Answer: it's usually .htaccess file that re-injecting a changed request URI , check that out and also you can reset your config files
Answer: Your problem description is slow HTTP requests but, as you showed, CPU and memory are not exhausted. So a couple of things to check:

Make sure that the requests really are slow. In httpd.conf, find this line:

LogFormat "%h %l %u %t \"%r\" %>s %b" common
And add %D after %b (but inside the ending quote). See http://httpd.apache.org/docs/2.2/mod/mod_log_config.html#formats
Then reload/restart httpd and your access_log file should now show the time each response takes in microseconds in the last column. Confirm these are slow. Maybe only some types of requests are slow? I notice that MySQL is using some CPU, so perhaps one type of request is hitting a slow database query?

If the responses above really are slow and there is no obvious pattern (e.g. particular pages), then you need to determine where they're slow. The %D time includes everything, from reading the request from the client, serving the file (which includes any application code or database queries), and writing the response, so it just tells you there is a slowdown, not necessarily where. So now you need to isolate where the slow down is. I would first check the application. Also check the MySQL slow log (enable it if it isn't enabled).
Check your error_log - maybe there are some application timeouts or other errors.
If you're not having any luck, you can also run pstack ${PID} periodically to try to understand what httpd is doing.
Finally, you can use tcpdump and something like Wireshark to isolate where the slowdown is, although that will be a bit tedious. I think there is also an httpd module that breaks down the time in a request, but I can't find it now and don't see it in the list of built-in modules.
Comment: thanks , why do every one says the memory  usage is not high ? haven't you seen the first image ? it consumes the whole 32g couple hours after reboot
Comment: As @sandeep.s85 mentions, your memory usage is not high. As he also mentions, you can look on the `-/+ buffers line` in `free -m`, or in `top`, you can add the `cached` amount to free.
Answer: Your memory usage is not high, you should skip that part from troubleshooting and try what Inforfinity has suggested.
The Linux kernel tends to occupy the available unused memory for disk caching. It makes the system faster. If any application need memory, it will take that from the cache itself. So basically you are not low on memory. Consider the output of free -m
-/+ buffers/cache:       4516      27553
4516MB of Actual RAM is being used, 27553 is the actual free memory. Close to 17G is cached.
Try to do performance testing on your web server. Use httperf to benchmark.
httperf --server yoursite.com --port 80 --num-conns 100 --rate 10

slow website load and high memory usage


Excel: how to count combinations that go both ways

Question: I need your help with Excel because I can't seem to find the answer anywhere.
So let's say I have column A and column B and in each column there are different colors. I've already created pivot table to count how many times a certain combination occurs, however, I don't know how to count the same combination of colors that occur in the reverse order as one. For examble combination 1 is red-green and combination 2 is green-red. Pivot table counts these as different entitites.
Thanks for your help in advance.
Comment: The problem is that I have 736 different combinations. With the above formula it would take me ages to look for duplicate calculated numbers. Thank you for your answer though!
Comment: I would just put each pair of items into alphabetical order, so red-green would become green-red
Comment: Yes in the end I did that and though it took some time, it is now solved. Thank you.
Answer: Two suggestions
(1) Keep it simple
Just set up a helper column containing each pair in alphabetical order
<code>=IF(A2<B2,A2&"-"&B2,B2&"-"&A2)
</code>
then run a pivot table on the result.
(2) Make it complicated
List the different pairs using a formula
<code>=IFERROR(INDEX(A$2:A$10&"-"&B$2:B$10,MATCH(1,INDEX((COUNTIF(G$1:G1,A$2:A$10&"-"&B$2:B$10)=0)*(COUNTIF(G$1:G1,B$2:B$10&"-"&A$2:A$10)=0)*(A$2:A$10&B$2:B$10<>""),0),0)),"")
</code>
Then count them
<code>=IF(G2="","",SUMPRODUCT(COUNTIF(G2,A$2:A$10&"-"&B$2:B$10)+COUNTIF(G2,B$2:B$10&"-"&A$2:A$10)))
</code>
The second way has the advantage that it is dynamic and doesn't need helper columns.
The first way is faster and puts the results in alphabetical order.


Example of a Subset of R X R that is not of the Form A X B

Question: What would be an example of a subset $\mathbb{R}\times\mathbb{R}$ that is not of the form $A\times B$, where $A\subseteq\mathbb{R}$ and $B\subseteq\mathbb{R}$.
Any guidance as to understanding what this question is asking, and an example of such a subset would be great.
Comment: Most curves will do, but I like small examples. This question admits examples consisting of just two points.
Comment: A circle .......
Comment: https://math.stackexchange.com/q/2544727 and https://math.stackexchange.com/q/3226526
Comment: It would help to know exactly what you don't understand. Do you know what $\bf R$ stands for? do you know what $A\times B$ means?
Comment: I do understand what all the terms mean. So would anything with a curve qualify, since the Cartesian product is always a rectangular region?
Answer: $F=\{(0,0),(1,1)\}$ is such an example.
Also the unit circle $\mathbb{S}^1=\{(x,y): x^2+y^2=1\}$ e.g.
If $F=A \times B$, then $(0,0),(1,1) \in F \to 0 \in A, 1 \in B \to (0,1) \in A \times B$, but $(0,1) \notin F$, etc. Similar arguments apply to the circle.


Regex named group empty

Question: This is my program:
 class Program
    {
        private static Regex _regex = new Regex("$ (?<amount>.*?)", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled);

        static void Main(string[] args)
        {

            string text = File.ReadAllText("file.txt");

            var match = _regex.Match(text);

            var group = match.Groups["amount"];

          //  Console.ReadKey();

        }
    }

The text does contain this text:
 $ 0.00

yet the named group is always empty. Any idea why would this happen?
Comment: your regex doesn't even match,
Answer: Escape the $, < and > by adding a backslash before it.
And I would actually suggest a different regex for the named group as well:
"\\\\$(?<amount>[^\\<]*)\\"

I'm pretty sure that >'s and <'s should only be escaped when in (parenthesis), but I rather escape stuff instead of remembering regex rules.
Answer: If you are processing html you can use help of Html agile pack
var doc = new HtmlDocument();
doc.Load("test.html");
var node = doc.DocumentNode.SelectSingleNode("//span[@id='TotalG']");
if (node != null)
{
    var temp = node.InnerText;
}

Regex named group empty


"-bash: telnet: command not found " error?

Question: I have the following services running:
sshd            0:off   1:off   2:on    3:on    4:on    5:on    6:off
syslog          0:off   1:off   2:on    3:on    4:on    5:on    6:off
tcsd            0:off   1:off   2:off   3:off   4:off   5:off   6:off
vsftpd          0:off   1:off   2:on    3:on    4:on    5:on    6:off
xinetd          0:off   1:off   2:off   3:on    4:on    5:on    6:off

xinetd based services:
        chargen-dgram:  off
        chargen-stream: off
        daytime-dgram:  off
        daytime-stream: off
        discard-dgram:  off
        discard-stream: off
        echo-dgram:     off
        echo-stream:    off
        tcpmux-server:  off
        telnet:         on
        time-dgram:     off
        time-stream:    off

why i still got "-bash: telnet: command not found " error?
Thanks
Comment: telnet is actually a client utility not a service, which is why it doesn't appear in the services list.
Answer: The RHEL/CentOS 5.4 telnet client is installed at /usr/kerberos/bin/telnet.  Your $PATH variable thus needs /usr/kerberos/bin listed.  (Preferably before /usr/bin)  If for some reason you don't have that file installed, it's part of the package krb5-workstation.  Installing that package manually or via YUM should give you what you need.
You can check quick with which telnet to see if it's found anywhere in your path.  echo $PATH to see what directories are being checked, and rpm -q krb5-workstation to see if you have the package installed.

--Christopher Karel
Comment: On Amazon Linux 2, I have installed krb5-workstation and still cannot find any references to telnet. The folder /usr/kerberos does not exists. I got it to work running "yum install telnet"
Comment: How about RHEL 6? I have same issue on RHEL 6 and there is no such package (krb5-workstation) nor is such a folder as /usr/kerberos/bin
Answer: Do you have a telnet client installed? Sounds like you only have the daemon installed currently... either that or your environment is setup wrong. Ie, the command telnet does not appear anywhere defined in $PATH
Comment: yum install telnet
or if your path is incorrect just run /usr/bin/telnet
Comment: i am on centos 5.4
Answer: In alpine docker image, to install telnet
apk update
apk add busybox-extras