Iterating through a beautiful soup array in python

Question: I just started learning webscraping in python using beautiful soup. I'm trying to access a certain value in an array given from find_all(). I can print out all of the array easily, but I'm having trouble just printing out one element of it. When I loop through it, it's all stored in the 0th element, and any value greater than 0 will result in an index out of range exception.
The loop works fine and shows that i is 0 through every iteration. the print above it that tries to access an element doesn't work and I need help trying to access one of the td's returned by the find_all. If there isn't a way to do it, then I guess I need help refining my search to the game mode and rank.
Thanks!
Here's the code:
import requests
from bs4 import BeautifulSoup
#python -m pip install lxml
result  = requests.get("https://rocketleague.tracker.network/profile/steam/teicho")

src = result.content
soup = BeautifulSoup(src, 'html.parser')
links = soup.find(id = "season-13")
rank = links.find_all('tr')
bound = len(rank)

data = []
for i in range(bound):
  print("")
  tds = [rank[i].find_all('td')]
  print(tds[1]) #where the error occurs
  for i in range(0,len(tds)):
    print (i)
    print(tds[i])
    print("")

Here's part of the output from the loop that shows what's in tds, because if i post the whole thing I can't get past stack overflow's spam filter:
0
[]

0[	, Reward Level
Silver
	,
0

(Top 40%)

	]

0
[]

0
[

Un-Ranked

Unranked
Division I

2,190

 (Top 1%)

n/a

	,
Un-Ranked

Unranked
Division I

	,
	,
2,190

 (Top 1%)

	,
	,
n/a
	]

0
[

Ranked Duel 1v1

Diamond I
Division III

846

 (Top 8%)

4

	,
Ranked Duel 1v1

Diamond I
Division III

	,
	,
846

 (Top 8%)

	,
	,
4
	]

0
[

Ranked Doubles 2v2

Champion II
Division I

~8

1,303

 (Top 7%)

~9

31

Win Streak: 2

	,
Ranked Doubles 2v2

Champion II
Division I

	,
~8
	,
1,303

 (Top 7%)

	,
~9
	,
31

Win Streak: 2

	]

0
[

Ranked Solo Standard 3v3

Unranked
Division I

892

(Top 10%)

0

Losing Streak: 9

	,
Ranked Solo Standard 3v3

Unranked
Division I

	,
	,
892

(Top 10%)

	,
	,
0

Losing Streak: 9

	]

0
[

Ranked Standard 3v3

Champion I
Division III

~20

1,257

 (Top 9%)

~10

10

Win Streak: 2

	,
Ranked Standard 3v3

Champion I
Division III

	,
~20
	,
1,257

 (Top 9%)

	,
~10
	,
10

Win Streak: 2

	]

Comment: what do you get when you print `len(tds)`
Comment: what is the length when you get the error
Comment: what is your issue?
Comment: when i go to print (tds[1]) I get a list index out of range error
Comment: I get 12 when I print out the length
Answer: tds[1] will always be wrong because on the line before, you put the returned list into another list, by adding the block parentheses around the function.
tds = [rank[i].find_all('td')] # Wrong
tds = rank[i].find_all('td') # Correct

Comment: I removed the brackets and got the same list index out of range error :(
Answer: I traversed through the source code differently and put all of it into a list. I had to strip a bunch of \n's that were in the source code for some reason. But it's how the people made their website. Here's my code:
import requests
from bs4 import BeautifulSoup
#python -m pip install lxml
result  = requests.get("https://rocketleague.tracker.network/profile/steam/teicho")
src = result.content
soup = BeautifulSoup(src, 'lxml')
tbl = soup.find(id = "season-13")
rank = tbl.find_all("table", class_ = "card-table items")

ranks = [rank[1].find("tbody").text]
for i in range(len(ranks)):
  print(ranks[i].replace('\n',''))

Answer: The range error is because you are using the variable i twice in the for loops, try using j or any other variable
Comment: While using the same iteration variable in nested loops *is* a BAD Idea, I don't think there's a connection to the run time error reported.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.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/30814841)


Is it worth to switch to InnoDB?

Question: Is it worth to switch from MyIsam to InnoDB for a Drupal 7 site that has 2000 visits per day? Would it be worth if it has 10000 visits in the future?
How much faster can a site become with InnoDB if it has mostly reads and not writes? And how much if it has a lot of writes in the database?
I'm asking all this because some articles I have read are negative about InnoDB, and opinions are split.
So, does the generally spoken statement "InnoDB is better always" reflect reality?
Comment: Imho, Innodb is nomore an option nowadays..
Comment: What do you mean it's not an option anymore?
Comment: Read the answer here http://drupal.stackexchange.com/questions/183/real-world-experience-in-scaling-and-tuning-performance/209#209  to another question that contains some InnoDB stuff. If you installed this site as d7 rather than upgraded it should have installed as innodb as that is now the default.
Comment: Drupal 7 uses innodb in default.
Comment: This what I have also read in the past, but as I mention drupal 7 installed all my sites using myisam! Did they regret having innodb as default? But even if they have something as default, my question remains what is the best. The default options do not always mean they are they best.
Comment: is InnoDB enabled on the server where Drupal 7 installed using MyIsam? that could be one of the reasons it did.
Comment: hmm. I did not mention that. Maybe that's the reason it used by default myisam. So by default it installs all in innodb? Does it worth to switch now?
Answer: The general rule of thumb was to use InnoDB to write intensive tables (due to its row locking nature) and MyISAM for the read-heavy loads. I have seen a few very busy sites fully on InnoDB running without any hiccups or drop in performance too.
Drupal 7 defaults to InnoDB as the database abstraction layer has been rewritten and immensely improved.
You could look into MariaDB which is a drop-in replacement for MySQL, faster and has extra engines. There is also Percona, another high performance replacement. They both address some of the downsides of InnoDB.
The reason I am listing the alternatives is that Oracle made a few very suspicious moves and it may be that pretty soon we won't be able to use MySQL for free. (see http://arstechnica.com/business/news/2011/09/oracle-may-fork-itself-with-recent-mysql-moves.ars)
If bigger changes are not viable/possible, I'd recommend making a clone of the site using InnoDB and load test it using tools like Apache Benchmark, siege, New Relic
Comment: On http://drupal.org/requirements#database MariaDB is one of the requirements. Also, http://drupal.org/node/861192#comment-3261836 has a pretty nice write-up of MariaDB. Haven't heard of any problems with Percona, but I'd do a bit more research. If it is all good, it will give you some boost which combined with apc, varnish can make your site fly (http://rbayliss.net/linode-drupal)
Comment: Is mariadb and percona fully compatible with drupal? Do any of these need that I change the way that I work etc> Are they compatible with all modules? Are there any web config tools like phpmyadmin? Will drush backup work? Thanks for your nice answer
Comment: I don't think that mixing the table types is a great idea. To make MySQL fast you need to dedicate RAM to the buffer pools and having to give RAM to both InnoDB and MyISAM won't let either one have the run of the park.
Comment: I tend to agree with that, Stewart. Which is why I wrote "the rule of thumb *was*" - imho, people learnt these things the hard way, but luckily we are getting somewhere now :)

Is it worth to switch to InnoDB?


Significance of individual coefficients vs Significance of both

Question: This was a question I read from google quantitative analyst interview on glassdoor: If each of the two coefficient estimates in a regression model is statistically significant, do you expect the test of both together is still significant?
I thought it was an interesting question, and I was wondering if there are counterexamples or there is a way to prove that it's always the case?
Any suggestion or hint would be greatly appreciated.
Comment: How many variables are in the model in total? Are you just interested in the significance of the nested model test that drops both, or do you care about anything else (whether the model as a whole is significant)? @ChristophHanck, I think that is a different case.
Comment: "each of the two" sounds like two in total to me.
Answer: Consider the Wald statistic, which resembles the familiar F-statistic $F$ (we use the default version that is not robust to heteroskedasticity):
\begin{align*}
W&=n(Rb-u)'\left[R\left[n\cdot s^2\cdot(X'X)^{-1}\right]R'\right]^{-1}(Rb-u)\notag\\
&=(Rb-u)'\left[R(X'X)^{-1}R'\right]^{-1}(Rb-u)/s^2\\
&=J\cdot F\notag,
\end{align*}
where $J$ gives the number of restrictions tested, with $H_0: R\beta=u$. If you want to test if neither of the variables enters the model, you simply take $R=I$, the identity matrix, and $u=(0,0)^T$.
Let us now find the non-rejection region of the Wald test as a function of the parameter vector $\beta$ (so the set of hypotheses you would not reject given a certain statistic computed from the data). $H_{0}$ is to be rejected at level $\alpha$ if $$W>\chi^{2}(J,1-\alpha),$$ the $1-\alpha$-quantile the $\chi^{2}$-distribution with $J$ degrees of freedom. The acceptance region thus corresponds to the values $$\theta=R\beta$$ for which $H_0$ would not have been rejected at level $\alpha$,
$$
\{\theta:W\leq\chi^{2}(J,1-\alpha)\}
$$
To visualize, consider the case $J=2$. Then,
$\chi^{2}(2,0.95)=5.99$ for $\alpha=0.05$ and $\chi^{2}(2,0.99)=9.21$ for $\alpha=0.01$. Write
$T=Rb$ (with $b$ the OLS estimator for the two coefficients) and $z=\theta-T$. Further, to abbreviate the algebra, summarize the inverse matrix as
$$
R\left[n\cdot s^2\cdot(X'X)^{-1}\right]R'=:V:=\left(
\begin{array}{cc}
1 & r \\
r & a \\
\end{array}
\right),
$$
where $|r|<\sqrt{a}$ to ensure invertibility of $V$. We further have
$$
V^{-1}=\frac{1}{a-r^2}\cdot\left( \begin{array}{cc}
a & -r \\
-r & 1 \\
\end{array}
\right),
$$
and $W=z'V^{-1}z$ or
$$
W=(az_1^2+z_2^2-2\,r\,z_1 z_2)/(a-r^2)\qquad\qquad(*)
$$
We hence now consider $W$ as a function of the hypothesized coefficients $\theta$.
The result for $T=0$ (so an OLS estimate of $(0,0)^T$), $r=0.6,\,a=1$ (see below for the code):

The dashed lines indicate the acceptance regions $[-1.96,1.96]$ that you get if you test each coefficient separately. The rectangle formed by the two intervals gives you the region where neither t-test rejects. The ellipses give you the regions of pairs of parameter values for which you would not have rejected the null at either 5 or 1%.
So, here is the answer: you see that there is small lightblue region outside the rectangle but inside the 5%-acceptance region of the Wald test, i.e., a region where both individual t-tests would have rejected but the joint test would not. So, yes, there are counterexamples, which as indicated by the example are however not expected to occur frequently.
EDIT: To follow up on the point made by @whuber here is the corresponding figure for the case $r=0$, i.e. no correlation.

r <- 0.6 # set to zero for uncorrelated case
a <- 1
W <- function(beta1,beta2,a,r) (a*beta1^2+beta2^2−2*r*beta1*beta2)/(1−r^2)

alpha <- 0.05
beta1 <- beta2 <- seq(-3,3,0.01)
z <- outer(beta1,beta2,W,a=a,r=r)

normcv <- qnorm(1-alpha/2)
contour(beta1,beta2,z,levels=qchisq(1-alpha,2))
abline(h=-normcv,lty=2)
abline(h=normcv,lty=2)
abline(v=-normcv,lty=2)
abline(v=normcv,lty=2)

z.nonrej <- z<=qchisq(1-alpha,2)
beta1.nw <- beta1 >= normcv
beta2.nw <- beta2 >= normcv
beta.nw <- outer(beta1.nw,beta2.nw,"+")==2
nw.nonrejection.Wald <- (z.nonrej + beta.nw)==2

ind.nw <- which(nw.nonrejection.Wald==T, arr.ind = T)
points(beta1[ind.nw[,1]],beta2[ind.nw[,2]], col="lightblue", cex=.1)

beta1.se <- beta1 <= -normcv
beta2.se <- beta2 <= -normcv
beta.se <- outer(beta1.se,beta2.se,"+")==2
se.nonrejection.Wald <- (z.nonrej + beta.se)==2

ind.se <- which(se.nonrejection.Wald==T, arr.ind = T)
points(beta1[ind.se[,1]],beta2[ind.se[,2]], col="lightblue", pch='.')

The figure shows that producing the counterexample indeed required allowing for correlation among the estimates.
EDIT 2:
In response to Kevin Kim's question in the comments:
Interestingly, the fact that it is possible that neither individual test rejects but that the Wald test does when there is no correlation is not a general result for any significance level $\alpha$. When choosing a sufficiently high significance level $\alpha$ of beyond roughly $\alpha\approx0.2151$, the ball covers the entire rectangle.
Basically, consider the function of the circle of the acceptance border of the Wald test, i.e. $(*)$ for $a=1$ and $r=0$ set equal to $\chi^{2}(2,1-\alpha)$ and solving for $z_2$ (focusing on the positive quadrant w.l.o.g.):
$$
z_2(z_1)=\sqrt{\chi^{2}(2,1-\alpha)-z_1^2}
$$
We now seek the value for $\alpha$ for which the function evaluated at the normal quantile is just the normal quantile, or
$$
\sqrt{\chi^{2}(2,1-\alpha)-\Phi^{-1}(1-\alpha/2)^2}=\Phi^{-1}(1-\alpha/2),$$
i.e., where the curve is equal to the corner of the rectangle.
Doing this numerically in R gives
rootfunc <- function(alpha) sqrt(qchisq(1-alpha,2) - qnorm(1-alpha/2)^2) - qnorm(1-alpha/2)
uniroot(rootfunc,interval = c(0.00001,0.9999))

with solution
$root
[1] 0.2151346

So indeed, the ball seems to shrink more slowly than the rectangle.
Comment: @Glen_b, actually, thank you for the pointer. I now highlight in colour the region I was referring to in my answer, which hopefully makes it clearer. And if someone feels like suggesting a smarter way of coding this, please feel free - I have the impression that my approach is rather clumsy.
Comment: +1 very nicely done! There appear to be two effects here. First, any correlation among coefficient estimates indicates that certain combinations of relatively small individual variations are unlikely, such as a low value for one and a high value for another as shown in the figure. Second, even in the absence of correlation the F test is contemplating spherical combinations of estimates while the individual tests are looking only at individual estimates. The resulting geometric discrepancy between spheres and boxes can produce counterexamples.
Comment: @ChristophHanck If we change the significant level but keep $r=0$, i.e., no correlation, then both the oval and the rectangle will change accordingly. I wonder if one could actually show that the "lightblue" region will never appear in the case of $r=0$? Is it possible that if you increase $\alpha$, then the rectangle shrinks at a faster rate than the oval, so that the "lightblue" region will show up again?
Comment: @KevinKim, interestingly, the answer is indeed yes, see my edit for the cutoff $\alpha\approx0.215$.


Remote administration in datacenters

Question: Given that running a data center presumably requires BIOS level access to each server, which protocols (hardware & software) are most commonly used?
I understand that KVM switches are fairly standard, but does this mean that each server requires VGA/inputs cabling to the switch, or is this accomplished over ethernet connections?
Are servers managed in batches corresponding to the number of ports on the KVM switches, or are individual KVM switches "virtualized" into some form of datacenter-wide administration?
Answer: Most server-based hardware, or server motherboards now a days have some sort of on-board network based KVM systems that allows remote administration of a machine, most of the time it's called IPMI.  It allows you, with the correct license, the ability to pull the console (screen) and send keyboard and mouse entries directly to the server, and also mount local ISO or drives as local media on the server.  Most even allow you to control power, such as turn a machine on, off or hard resetting it.
All of the servers that I run have one form of IPMI or another, on our HP's we have iLO, Dells have DRAC and IBM's have something else, but basically all the same.  We no longer use KVM switches in our data center and racks, as using the IPMI interfaces means we can reuse existing network switches etc and reduce cabling.
And on machines, such as desktops that we must run, and we try to keep it at a minimum, we also too have IPMI PCIe cards installed that provide the same functionality.
Gone are the days where you needed a dedicated KVM switch or KVM-over-IP switch.  With IPMI, I can manage any servers or rebuild any servers from anywhere in the world without the need or assistance of anyone physically at the server.  So that's how we do it at our data center and business.
Comment: Ah, so this would be (one) of the reasons for the cost disparity between desktop and server motherboards- server motherboards will have IPMI (e.g. Intel's AMT or AMD's DASH) baked in.
Answer: The solution depends on the size of the datacenter and the hardware of the servers.
I manage a small datacenter. We use KVM switches with one vga connection per server. They are stackable, 10 servers per switch, allowing a total of about 100 servers.
There are also KVM switches that pass the signal over ethernet to the terminal.
Many servers provide built-in ethernet based remote management. HP offers iLO ( integrated Lights Out ) which is proprietary and quite expensive. On IBM servers there is a system that allows taking control from any browser.
Comment: ibm-server use IPMI too

Remote administration in datacenters


What are the gamma-Pareto convolutions and how have they been used?

Question: The Pareto distributions, i.e., density functions (pdf), are types I through IV and the type II variant; the Lomax distribution. This makes for a number of possible gamma-Pareto convolutions (GPC; also density functions). Of these the GPC type I and GPC Lomax have been used in the literature, at least in so far as I know. Let us start by defining the parameterizations used for GPC type I.
The gamma distribution (GD) can be given as
\begin{equation}\label{eq:GD}
 \text{GD}(a,b;t) =
 \,\dfrac{1}{t}\;\dfrac{e^{-b \, t}(b \, t)^{\,a} }{\Gamma (a)} \;\theta(t)\;,
\end{equation}
where the gamma function satisfies $\Gamma (a)=\int _0^{\infty } e^{-t} t^{a-1}\,dt$, and $\theta(t)$ is the unit step function, i.e., 0 for $t<0$ and 1 for $t\geq0$. The GD rate parameter is $b$, whereas $\frac{1}{b}$ is the scale parameter. The shape parameter for the GD is $a$. The shape parameter aids in fitting data and data shapes. There is no location parameter.
Next, we define a type I Pareto distribution ($\text{PD}_{\text{I}}$ a pdf),
\begin{equation}
\text{PD}_{\text{I}}(\alpha, \beta;t)=
 \dfrac{\alpha}{t}  \left(\dfrac{\beta}{t}\right) ^{\alpha }  \;\theta(t-\beta)\;.
\end{equation}
Note the shift to the right of the unit step function; $\theta(t-\beta)$, i.e., the PD function is zero for $t<\beta$. $\beta$ is the scale parameter. The shape parameter is $\alpha$. There is no location parameter.
The PD type II pdf is
$$\text{PD}_{\text{II}}(\alpha ,\beta ,\mu;t)=\frac{\beta  }{\alpha }\left(\frac{\alpha -\mu +t}{\alpha }\right)^{-\beta -1}\theta (t-\mu ). $$
The PD type II Lomax pdf is
$$\text{PD}_{\text{Lomax}}(\alpha ,\beta ,0;t)=\frac{\beta  }{\alpha }\left(\frac{\alpha +t}{\alpha }\right)^{-\beta -1}\theta (t ) .$$
The PD type III pdf is
$$\text{PD}_{\text{III}}(\alpha ,1,\gamma ,\mu;t)=\frac{\alpha ^{-1/\gamma } (t-\mu )^{\frac{1}{\gamma }-1}}{\gamma  \left[\left(\frac{\alpha }{t-\mu }\right)^{-1/\gamma }+1\right]^2}\theta (t-\mu ) .$$
The PD type IV pdf is
$$\text{PD}_{\text{IV}}(\alpha ,\beta,\gamma ,\mu;t)=\frac{\beta}{\gamma }  \alpha ^{-1/\gamma } (t-\mu )^{\frac{1}{\gamma }-1} \left[\left(\frac{\alpha }{t-\mu }\right)^{-1/\gamma }+1\right]^{-\beta -1}\theta (t-\mu ) .$$
The infinite series describing the GPC type I convolution is given in the answer below. There is no closed form solution. Such functions are computer implemented as truncated infinite series.
I will award a bounty to anyone who shows a solution$^\star$ for a GPC distribution type whose solution is not referenced here, i.e., GPC type II (non-Lomax), GPC type III or GPC type IV.
$^\star$EDIT: Any exact and calculable reformatting of any convolution integral of the form: $$\begin{align}\text{GPC}_j\left(\begin{array}{cc}
a & b \\
\alpha &\beta
\end{array} \Big|\,t\right)&=\text{GD}(a,b;x)\ast\text{PD}_j(\alpha,\beta;x)\,(t)\\&=\int_{-\infty}^{\infty} \text{GD}(a,b;x-t)\,\text{PD}_{j}(\alpha,\beta,\,,\,;t) \;dt,\end{align}$$
where  $j=\text{II, III, or IV}$. I do not consider limiting discrete convolutions for $\Delta t\to0$, i.e., a limiting or Riemann sum of the convolution integral, to be exact solutions unless the limits sign can be removed in such a fashion as to provide a calculation of any desired accuracy.
Comment: I cannot speak to the downvote, Carl, because I did not apply it, so please do not insinuate I did.  (I would be happy to prove I did not by applying one :-)  In general, please do not complain about downvotes: it's not constructive and can only antagonize people.  Returning to my previous comment: please explain what you mean by "documenting a solution to" one of these distributions.
Comment: For starters, I have yet to see any convolution operators in this thread!  I truly do not understand what you are going after in this question.  Are you trying to obtain formulas for densities (or CDFs or CFs or CGs or something) of sums of Gamma and Pareto variables?  And if so, what kind of formulas are wanted?  I notice the one in your answer is an infinite sum, which is less than convenient and in many ways less useful than the original convolution integral.
Comment: Could you explain what you mean by "documents those ... types"?  What would constitute a "documentation" (listing of mathematical propertiess? potential applications? references?) and what specifically are the "types not listed here"?
Comment: @whuber I can, and did. Surprised I am that it was not clear from the context.
Comment: @whuber I knew you did not do the downvote, I know you fairly well. I did not insunuate anything but wrote to you as a moderator saying that I do not like downvoting on well-formatted questions or even on poorly formatted ones, I do not think they serve any purpose that is not better accomplished else-wise. I removed the comment so no-one else can misinterpret it either. I do not understand your comment as to "what do I mean?" I am asking for convolutions written as formulas not containing a convolution operator. What is unclear to you?
Comment: @whuber I start with density functions, AKA distributions, and the convolution of two density functions is a density function. The convolution operator $\ast$ is standard notation and appears in the answer below. One cannot use the convolution alone with any good speed. My implementation of the infinite sum in Mathematica has a run time of 0.025 s. I do not see how this can be done else-wise, so I do not understand your criticism. Even a sine function is implemented as an infinite series, accelerated no doubt, but a series executed by software none-the-less.
Comment: @whuber There are no closed form expressions for any GPC of which I am aware. A computer program is listed in the [Computer Networks](https://www.sciencedirect.com/science/article/abs/pii/S1389128607000837) paper referenced for the Lomax GPC,; it is a double infinite series, and the GPC type I listed is less complicated than that.
Comment: You don't seem to be asking about computer implementations.  There are alternative mathematical definitions of sine, for instance, as the inverse of an integral or as an infinite product, that may lend themselves to effective computation; and often an integral is an excellent analytical tool. This takes us right back to the beginning: what exactly constitutes a "solution"?
Comment: @whuber Convolution is defined as an integral. A solution to a convolution integral has a format similar to invoking the Mathematica command [convolve](https://reference.wolfram.com/language/ref/Convolve.html). In this case, the Mathematica routine cannot be directly applied to the problem as it is beyond the range of complexity that Mathematica can handle. A solution to a convolution is an exact restatement of its integral.  A recursion solution to a convolution would be a solution, a restatement into closed forms would be a solution. Still not seeing what your objection is.
Comment: A *mathematical* "solution" to a convolution would be *any* way of expressing the resulting function. Your question appears focus on *a certain family of distributions.* A "solution" in that context could mean anything from explaining how the distribution arises in nature or mathematics to formulas for its moments, its CDF, it CG, etc. I'm not objecting to anything, but after requesting clarification from you four times I'm not getting much closer to understanding what would constitute a good or complete answer. I therefore feel it would not be worth any time or effort to contribute to one.
Comment: @whuber You state, "A "solution" in that context could mean anything..." Indeed, with the restriction that it be 1) exact and 2) calculable. From [dictionary.com](https://www.dictionary.com/browse/solution) 4. Mathematics: (a) The process of determining the answer to a problem. (b) The answer itself.
Comment: @whuber Yes, solutions can take many forms, and I do not care which is given as long as it is exact and calculable. I have provided the exact and calculable criteria for what constitutes a solution explicitly in the Q/A.
Comment: @whuber I have addressed your concerns. I note that the extent of clarity you demanded exceeds that in the peer reviewed publications cited.
Answer: The GPC type I has been open access published recently and used to model metformin drug serum concentrations following intravenous bolus injection. Derived from series expansion of the GD exponential above, followed by convolution with a PD, as above and summation of the expanded parts. The GPC type I model inherits two shape parameters, $a$ and $\alpha$, and two scale related parameters, $b\; (T^{-1})$ and $\beta\;(T)$ from its convolved pdf's,
\begin{equation}
\begin{split}
\text{GPC}_{\text{I}}(t;a,b,\alpha,\beta)
 &=\text{GD}( x;a,b)\ast \text{PD}_{\text{I}}(x;\alpha , \beta) \;(t)\\
&=\theta (t-\beta) \frac{\alpha b^a\beta^\alpha}{\Gamma (a)}t^{a-\alpha-1}\sum _{n=0}^{\infty } \frac{(-b\,t)^n}{n!}   B_{1-\frac{\beta}{t}}(a+n,-\alpha)
\end{split}\;\;,
\end{equation}
where the incomplete beta function is $B_z(A,B)=\int _0^z u^{A-1} (1-u)^{B-1}d u$. Note that this is exact but is calculable by removing the limiting $\infty$ for $n$ as follows. Because the series is alternating, for $n>m$, where $m$ is some positive integer, no matter how large, the series sum thereafter has decreasing absolute error, as it then satisfies the Leibniz test, where the absolute error is less than the absolute magnitude of the $n>m^{\text{th}}$ term.
Proof: First note that $\lim_{t\to\infty}B_{1-\frac{\beta}{t}}(a+n,-\alpha)=B(a+n,-\alpha)$, where $B(\cdot,\cdot)$ is the beta function. Next, $\lim_{n\to\infty}B(a+n,-\alpha)=0$. Then $\lim_{n\to\infty}t^{a-\alpha-1}  \frac{(-b\,t)^n}{n!}=0$, no matter how large $t$. Finally, $0\cdot0=0$,  thus the $n^{\text{th}}$ term absolute value can be made smaller than $\epsilon$, no matter how small for $n$ sufficiently large.||
An alternative formulation is used for $t$-long, because the alternating term magnitude inflates as $t$ increases, requiring very high precision for use of the primary definition above. The alternate formula is
\begin{equation}
\begin{split}
\text{GPC}_{\text{I}}(t;a,b,\alpha,\beta)=&-\theta (t-\beta) \frac{ \alpha b^a }{\Gamma (a)}t^{a-1}\sum _{k=1}^{\infty }\left(\frac{\beta }{t}\right)^k \frac{(1-a)_k}{k! (k-\alpha )} \, _1F_1(a,a-k;-b t)\\
&+\theta (t-\beta )\left[ \frac{b^a }{\Gamma (a)} e^{-b t} t^{a-1}-\pi \csc (\pi \alpha )\frac{b^a \beta ^{\alpha } }{\Gamma (\alpha )} t^{a-\alpha -1} \, _1\tilde{F}_1(a,a-\alpha ;-b t)\right]
\end{split}\;\;\;.
\end{equation}
The above is shown as Theorem 1 of this paper.
The GPC Lomax distribution: On the convolution of Pareto and gamma distributions was published in 2007 and is proposed for usage to determine inter arrival times between on-traffic (off-traffic) random variates. It is derived explicitly in that text in a fashion analogous to the GPC type I above, however, it was parameterized differently and to see it either contact the authors or download it from a library service.
Closed form expressions for GPC types I to IV may not be possible. However, by combining certain parameters and reducing their number by one parameter, closed form expressions for simplified GPC types II through IV can be written.


Custom edit Panel/Tab for content type

Question: In Drupal 8 I have a custom content type, and I want to add a group of fields to it that are related to tracking. Since these fields don't have to do with the content displayed, I wanted to separate these options in the UI by having them on a different tab or panel.
This is an example of what I have in mind.

What is the best way to accomplish this? Is there some hook to achieve this?
I have done a lot of searching, but I can't find anything relevant.
Comment: Have you tried clicking 'Add Group' and then choosing 'Tabs'   on the 'Manage form display'  section of the content type editing page?
Comment: @Matt TY for the response - If i go to /admin/structure/types/manage/page/fields I don't see any option to add a group for my stock instance of Drupal 8. I only see "Add field" and group / tab is nowhere in that list.
Comment: Hmm must be a module I installed that added that functionality. I'll see if I can track it down.
Comment: Found it. Added it as an answer. Let me know if that doesn't work for you.
Answer: Field Group is a module that provides this functionality.
https://www.drupal.org/project/field_group

Custom edit Panel/Tab for content type


How to check if character is part of a word

Question: I've searched around here about this topic, suggestions that i saw are from topics like

Check if a character is a word boundary

but i don't know if that's what i need exactly
My problem is this, I have to extract a string from word which can be a single character but also can be multiple, in this question I'm only discussing single character because that's the main problem in my situation, other types where string is multiple characters is easily identifiable because there's only one encounter for it in the string where I'm removing it from
"S Shoulder Pads"

In this example i have to remove character S from this string, problem is data is not really consistent, So strpos() or strrpos() don't always work. this same string can be provided reversed and because of this i can't consistently know where my needed character is located at
"Shoulder Pads S"

My only validation for the single character string that i need to extract is, if character is a single letter and it's not a part of any word in this example S then it's valid for removal. is there some nice way of doing this in PHP?
Comment: Preg_replace and regex word boundaries?
Comment: A better explanation with wording https://stackoverflow.com/questions/1324676/what-is-a-word-boundary-in-regex#:~:text=A%20word%20boundary%2C%20in%20most,-Za-z_%5D%20).
Comment: if get it correctly something like this "\bS\b" would work in my case, (quick test on regexr)
Comment: thanks for the help, do i understand correctly that regex word boundaries is used to determine if a specific string starts/ends a string
Comment: They make sure a string is not surrounded by any other word character.
Answer: As you have guessed it correctly, you can use a word boundary \b around your string to match it in such a way that it exists individually and not as a part of any string. You can use preg_replace to replace the matched string with any string, which is the second parameter for this function.
Snippet:
<?php

$tests = [
        "S Shoulder Pads",
        "Shoulder Pads S",
        "SSSSS S S S"
    ];

foreach($tests as $test){
    echo preg_replace('/\bS\b/','',$test),PHP_EOL;
}

Comment: Thanks for the explanation, i just discovered the same solution as well


Pull-request "linter"

Question: I had seen a tool a while ago that would let me define rules for GitHub pull-requests, and could be enforced during CI.
The rules could be for instance:

The commit title should respect a format
The number of files changed cannot be higher than 10
There should be no stray ":focus" in the specs
etc.

I can't remember the name of this tool.
Comment: Any Github-integrated CI will do this. For example. check this: https://github.com/puppetlabs/puppet/blob/master/.travis.yml and this: https://github.com/puppetlabs/puppet/blob/master/Rakefile
Comment: Thanks. I'm trying to remember the tool that among other things does "verify that commit messages match CONTRIBUTING.md requirements" but with a DSL, not having to write your own commands.
Answer: HoundCI by thoughtbot is a pretty popular tool. It is SaaS-based and free to use for open source projects: https://houndci.com/
It supports ruby and javascript.
Comment: thanks! it seems to be limited to code checking. the tool I had in mind was also applying to the PR, commit messages themselves if I remember correctly.
Answer: I found the tool I was looking for: it's called Danger:

What is Danger?
Danger runs after your CI, automating your team's conventions
  surrounding code review.
This provides another logical step in your process, through this
  Danger can help lint your rote tasks in daily code review.
You can use Danger to codify your teams norms, leaving humans to think
  about harder problems.
For example?
You can:

Enforce CHANGELOGs Enforce links to Trello/JIRA in PR/MR bodies
Enforce using descriptive labels Look out for common anti-patterns
Highlight interesting build artifacts Give specific files extra focus
Danger provides the glue to let you build out the rules specific to    your team's culture, offering useful metadata and a comprehensive
  plugin system to share common issues.

Pull-request "linter"


Percorrer matriz 4x4 com for, não entendi

Question: Não entendi esse código:
<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i, j;
    for(i=1; i<5; i++) {
        for(j=1; j<5; j++) {
            if(i==j)
                printf("1 ");
            else
                printf("0 ");
        }
        printf("\n");
    }
    system("pause");
    return 0;
}
</code>
Ele atribui valor 1 caso seja verdadeiro e 0 para falso, mas se as duas são iguais, não entendi, porque apenas uma linha vertical 1. e não tudo 1.
<code>1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
</code>
Answer:
Na 1ª iteração do 1º for o valor da variável i é 1.
Assim que entra neste for entra-se em um segundo for (que esta dentro do primeiro) o valor de sua variável j também é 1 logo será impresso 1.
Nas próximas iterações o valor do j do segundo for não baterá com o do 1º for pois o valor do i ainda não foi alterado pois ainda não se completou uma iteração do 1º for.
Assim que se completar a 1ª iteração no 1º for o valor do i será incrementado para 2 e o valor só batera com o do j quando o 2º estiver na segunda iteração, imprimindo 1. E assim sucessivamente.
Logo os valores das variáveis contadoras de cada for só serão iguais quando ambos estiverem na mesma iteração (quando ambos for externo e interno estiverem na 1ª, 2ª, 3ª e 4ª iteração)


C++0x lambdas coding style

Question: I wonder how people are using C++0x lambdas, in terms of coding style. The most interesting question is how thorough to be when writing the capture list. On one hand, the language allows to list captured variables explicitly, and by the "explicit is better than implicit rule", it would therefore make sense to do an exhaustive listing to clearly state the intetion. E.g.:
 int sum;
 std::for_each(xs.begin(), xs.end(), [&sum](int x) { sum += x });

Another argument for this is that, since lifetime of ref-captured locals doesn't change just because they're captured (and so a lambda can easily end up referencing a local whose lifetime has long ended), making capture explicit helps reduce such bugs and track them down.
On the other hand, the language also deliberately provides a shortcut for auto-capturing all referenced locals, so clearly it's intended to be used. And one could claim that for an example such as one above, it is very clear what happens even with auto-capture, and lifetime of lambda is such that it won't outlive the surrounding scope, so there's no reason not to use it:
 int sum;
 std::for_each(xs.begin(), xs.end(), [&](int x) { sum += x });

Obviously this doesn't have to be all-or-nothing, but there has to be some rationale to decide when to auto-capture, and when to do capture explicitly. Any thoughts?
Another question in the same vein is when to use capture-by-copy - [=], and when to use capture-by-reference - [&]. Capture-by-copy is obviously safer because there are no lifetime issues, so one could argue that it should be used by default whenever there's no need to mutate the captured value (or see the changes done to it from elsewhere), and capture-by-reference should be treated as (potentially premature) optimization in such cases, to be applied only where it clearly makes a difference.
On the other hand, capture-by-reference is almost always faster (especially as it can often be optimized down to a copy, if the latter is actually faster, for small types and inlineable template functions such as most STL algorithms), and is safe if lambda never outlives its scope (which is also the case for all STL algorithms), so defaulting to capture-by-reference in this case is a trivial and harmless optimization which doesn't hurt.
What are your thoughts?
Comment: GCC does not have lambdas in the current 4.4 version nor the in-development 4.5 version. See http://gcc.gnu.org/projects/cxx0x.html for details of GCC's C++0x feature support
Comment: I am especially interested in feedback from people who have used lambdas in production code already, and thus have some experience backing their views; but all feedback is welcome.
Comment: Lambdas aren't really implemented in many compilers yet - I doubt you'll find much production code until G++ or MSVC++ support them at the least
Comment: I'm actually working on production code that uses VC10 lambdas pretty heavily (in newer parts especially), but then I'm a developer on VS2010 team, so my case is a bit special I guess... However, I was under impression that newer `g++` releases (not betas!) have production-quality implementation of lambdas - am I mistaken?
Comment: As far as I know, G++ doesn't yet have lambdas. A bunch of other 0x features, but not lambdas.
Comment: MS support them in VC10, but granted people won't be using beta compilers for production code. Likewise even for features which are in g++, I doubt that a whole lot of production code is using -std=c++0x just yet.
Comment: Intel compiler has lambda support, for what matters, but I have not actually used it for anything but small tests so I cannot really offer any experience here.
Comment: Off topic, just in case someone didn't know: `std::accumulate` does what this `for_each` does with that lambda. E.g. `int sum = accumulate(begin(xs), end(xs), 0)`
Answer: I've never heard of the "explicit is better than implicit rule" rule, and I don't agree with it. There are cases where it's true, of course, but also plenty of cases where it isn't. That's why 0x is adding type inference with the auto keyword after all. (and why function template parameters are already inferred when possible) There are plenty of cases where implicit is preferable.
I haven't really used C++ lambdas yet (other than poking around with the VC10 beta), but I'd go with the latter most of the time
std::for_each(xs.begin(), xs.end(), [&](int x) { sum += x });

My reasoning? Why not do it? It's convenient. It works. And it's easier to maintain. I don't have to update the capture list when I modify the body of the lambda. Why should I be explicit about something the compiler knows better than me? The compiler can figure out the capture list based on what's actually used.
As for capture by reference vs value? I'd apply the same rules as I do for regular functions. If you need reference semantics, capture by reference. If you need copy semantics, do that. If either will do, prefer value for smallish types, and reference if copying is expensive.
It doesn't seem different from the choice you have to make when designing a regular function.
I should probably read up on the specs for lambdas, but isn't the main reason for explicit capture lists so that you can capture some variables by value and others by reference?
Comment: Regarding "compiler knows better than me" - compiler doesn't know the lifetime of lambda. If you would have assigned a `[&]` lambda to `std::function` in outer scope, it will happily let you do so and then leave the lambda scope - but, of course, all references in the lambda will be invalid when you actually call it...
Comment: "Explicit is better than implicit" is from The Zen of Python (http://www.python.org/dev/peps/pep-0020/), but that thing isn't really specific to Python.
Comment: There's no explicit rationale for it, but yes, it is something that's only possible with a capture list.
Comment: Ah, thought I'd heard it somewhere before. Never heard it as an independent rule though. But like pretty much any rule, you can take it too literally. There's plenty in Python that's implicit too. (and in some cases it contradicts the following line too - 'simple is better than complex'.) I think the rule is useful in resolving ambiguity (if there's ambiguity, don't rely on obscure implicit rules to resolve it, be explicit about what you want), but when it's clear what you mean, there's no point in stating the obvious explicitly.
Answer: My initial instinct was that capture by value offers more or less the same as Java's anonymous inner classes, which are a known quantity. But rather than using the array-of-size-1 trick when you want the enclosing scope to be mutable, you can capture by reference instead. It's then your responsibility to confine the duration of the lambda within the scope of the referand.
In practice I agree with you that capture by reference should be the default when dealing with algorithms, which I expect will be the majority of uses. A common use for anonymous inner classes in Java is listeners. There are fewer listener-style interfaces to be seen in C++ to start with, so it's a lesser need, but still there. It might be best to strictly stick to capture by value in that kind of case, to avoid the opportunity for error. Will capture-by-value of a shared_ptr be a big idiom, maybe?
However, I haven't used lambdas yet, so I may well have missed something huge.
Comment: Regarding capture-by-value of a `shared_ptr` for captured state that should be able outlive the scope (such as listeners) - good point, and, in fact we have some of that in our code already.
Comment: It should be noted that the absence of listener pattern in C++ standard library is mostly due to its smallish size (most notably no UI). Virtually any UI toolkit has listeners/events in some form, and some of them (Gtk--, IIRC) allow you to register arbitrary function objects as listeners, and not just functions or methods (as e.g. Qt does). This will probably grow even more popular with adoption of `std::tr1::function` (which is `std::function` in C++0x) as a standard way to do this. So the issue will be there.
Comment: @Pavel Minaev: you don't need to capture `shared_ptr`. you can just capture the variable by value (thus it outlives the scope), and then declare the lambda `mutable`, which will allow it to mutate variables captured by value
Comment: @newacct Capturing by value only works if the captured variable is copyable (e.g. you can't capture a `unique_ptr` that way), and if it is not captured by more than one lambda with state sharing semantics between the two being desired.
Answer: I am reading the following link to get a better understanding of C++ lambda. The coding style used in the examples are quite neat and I am able to follow:
http://uint32t.blogspot.com/2009/05/using-c0x-lambda-to-replace-boost-bind.html
Answer: I would go with explicit capture lists when at all convenient, when you want to capture a lot of variables then (you're probably doing something wrong and) you can use the grab all [&] capture list.
My take of the matter is that explicit capture lists are the ideal and the implicit variants should be avoided and are only there so people won't have to type out reams of code when they are actually needed.
Answer: I can see a new coding standard rule here! ;)
This is a bit contrived but just to highlight an "advantage" to being explicit, consider the following:
void foo (std::vector<int> v, int x1)
{
  int sum = 0;
  std::for_each (v.begin ()
    , v.end ()
    , [&](int xl) { sum += x1; }
}

Now, I've purposely chosen poor names etc for this, but it's just to illustrate the point.  If we used an explicit capture list then the above code wouldn't compile, but currently it will.
In a very strict environment (safety critical) I can see a rule like this being part of the coding standard.
Comment: Although what you say is true, you could make exactly the same mistake if you wrote a for loop, and did int xl = *iterator; sum += x1;. Nobody's demanding explicit capture in that situation. In cases where the lifetime of the lambda is confined to the local scope, I think that implicit capture is no more (nor less) dangerous than the fact that simple braces inherit the surrounding automatic scope. It's when the lambda is going to live on that I think you want to be explicit what's captured (and deduce that what is not captured can safely die at end of lexical scope).
Comment: It is not important that the error can exist in other constructs.  This is an additional advantage of lambda's, in that you can reduce the visibility of names more than is possible for a "for loop".  There are many ways that name hiding/visibility can result in subtle errors.  One goal of a coding standard is to reduce the cases that can cause a problem and you'll find several rules regarding name hiding and reduction of name visibility in standards such as JSF++, MISRA C/C++.  I can see this being another.
Comment: But it doesn't actually reduce the visibility compared with the equivalent functor, it just prevents it being extended. That's not an advantage, it's mitigation. So on this point I think lambdas are (very slightly) worse than functors, in that if you think default capture is bad, you now have to ban it and police the ban. But yes, perhaps better than structured programming.
Comment: In fact, if we see `auto nextblock = [&somevar] {thing tmpvar; do_something(somevar,tmpvar); }; nextblock();` in preference to `{thing tmpvar; do_something(somevar,tmpvar);}`, then I will be fully convinced that lambdas offer a genuine advantage over existing constructs by virtue of limiting visibility of all locals except somevar. But I believe their advantages are elsewhere...
Comment: "...reduce the visibility compared with the equivalent functor".  I never implied that it would, however, implicit capture increases the number of names that are unnecessarily visible within the lambda body (compared to the functor case)- I believe this might be considered a "bad thing (tm)" and I can imagine such a rule about implicit capture, especially in a safety critical environment where implicit behaviours in general are frowned upon.  Maybe we should just agree to disagree! :)
Comment: I think I just misread what you meant by "advantage to being explicit". It's an advantage compared with lambdas that don't use explicit capture, rather than an advantage compared with the current way of minimising visibility (functors)? So I do now see the point of the coding standard rule you propose, since it's to stop people "abusing" lambdas to accidentally increase visibility. Thanks :-)

C++0x lambdas coding style


Two-sided permutation test vs. two one-sided

Question: I am working with a set of genes for which I have both methylation values $\beta$ (continuous on unit interval) and gene expression $E$ (non-negative continuous) that I want to test for correlation $\hat\rho(log_2E,\beta)=R$. To filter out only the significant correlations I perform a permutation test where for each site I randomly permute $E$ a large number of times and calculate $R$. This gives me a distribution under the null hypothesis $p(R|H_0)$, i.e. when there is no dependence between $\beta$ and $E$, that I can compare $R$ against.
Now to my question,
I want to test both for positive and negative correlation. Do I make two tests per gene and use double multiple testing correction, where
$p_- = \int\limits_{-\inf}^Rp(x|H_0)dx$
$p_+ = \int\limits_{R}^\inf(x|H_0)dx$
or can and should I calculate a two-tailed p-value directly based on $|R|$ or such, and use normal multiple testing correction? I can only think of the following, but it feels wrong and has lousy power.
$p_2 = \int\limits_{-\inf}^{-|R|}p(x|H_0)dx + \int\limits_{|R|}^\inf(x|H_0)dx$

Edit: Updated the figure and added the missing x-axis label. The y-axis is the same for all panels.
Comment: The green isn't really a test, it is the region that is consistent with the Null hypothesis in the one-sided test of 0 correlation where the alternative is that the correlation is negative. Actually, I wonder if your blues are too big? If you want a 95% two-sided test, the quantiles you want at the 0.25th and 0.975th such that the sum of the blue areas is 0.05 (5%). If a one-sided test, then all the evidence against the null is on one tail, in the two-sided evidence is in both tails.
Comment: What is your Null Hypothesis? That should determine how you derive the $p$ value from the permutation test. If the Null Hypothesis is that the correlation is 0 and that large positive and negative correlations are evidence against this Null, then you want the blue areas.
Comment: You can't test for $R > 0$ here as otherwise you'd need to state something about how big $R$ is. Obviously the real $R$ is unknown otherwise you wouldn't be doing the test. The Null hypothesis is $R = 0$ and you are looking for evidence against this Null. I may have misunderstood what the plots show? Usually these plots would show the permutation distribution of $R$.
Comment: @andrea Okay that is true it is just a different way of looking at the same thing.
Comment: Yes, the null hypothesis would be that the correlation is 0. I just find it hard to understand why I get so much fewer hits than when combining the red and green tests.
Comment: Thanks for taking your time with my question! What if I had tested the null hypothesis that $R>0$ and gotten $R=-0.2$? It would result in the green area above, but you are saying that it would disqualify the test since $R$ directly defies $H_0$? I still don't get whether or not I am allowed to do that test, given that I include it when correcting for multiple testing.

The data underlying the plot is chosen arbitraryily to illustrate the equations. The blue area is 0.147 and would correspond to the $p$ value of $R=\pm 0.2$ under $H_0: R=0$ for this particular gene, wouldn't it?
Comment: When you say _"I want to test both for positive and negative correlation. Do I make two tests per gene"_, do you mean that you want to carry out two one-sided test, where $H_0:R=0$ and in the first test $H_{1,A}:R>0$ and in the second test $H_{1,B}:R<0$, each at an $\alpha/2$ level? Because in that case it would be exactly the same as carrying out one two-sided test where $H_1:R\ne 0$ at an $\alpha$ level, since it is impossible for both hypotheses to be rejected.
Comment: I agree with Gavin.  If the curve is the permutation distribution for R under the null hypothesis the blue area represents the region for the two-tailed test.  If you want to do a one-side test where the alternative is R>0 then a right side tail with the appropriate area for the given significance level is what you would use.  That would not be the green region that you exhibit.
Comment: @andrea One two-sided test is of course possible.  The reject region looks like the figure with the two blue tail regions. The idea is not to reject for any estimated value different from zero but rather to reject when the estimate is either much greater than 0 or much less than zero.
Comment: If you are applying these tests many times to test several different genes than you must adjust your results to account for multiple testing.
Comment: @MichaelChernick: yes, I was only pointing out that two one-sided tests (each at an $\alpha/2$ level), to see whether you have evidence to conclude that $R$ is either larger or smaller than $0$, are exactly equivalent as one two-sided test (at an $\alpha$ level).
Comment: I am starting to see the gist of the problem now. You all agree the two-sided test (blue) is valid and that two one-sided tests should be equivalent to one two-sided. How would you go about doing a one-sided permutation test then, and what happens if the observed R falls on the $H_0$ side vs. the $H_1$ side?
Answer: Here is an R example of permutation testing.
<code>## dummy data
set.seed(1)
x <- runif(20)
y <- 0.5 * x
y <- y + rnorm(20)

## set up for the permutation, compute observed R
nullR <- numeric(length = 1000)
nullR[1] <- cor(x, y) ## obsered R in [1]
N <- length(x)

## permutation test
for(i in seq_len(999) + 1) {
    nullR[i] <- cor(x[sample(N)], y)
}

hist(nullR) ## histogram of R under H0
</code>

Now we can compute the permutation $p$ from the permutation distribution for the various tailed tests you consider:
<code>> ## one side H1 R > 0
> sum(nullR >= nullR[1]) / length(nullR)
[1] 0.908
> ## one side H1 R < 0
> sum(nullR <= nullR[1]) / length(nullR)
[1] 0.093
> ## two sided
> sum(abs(nullR) >= abs(nullR[1])) / length(nullR)
[1] 0.177
</code>
Comment: I fail to see how this is any different than my examples, except that I used `nullR` to estimate the density $p(R|H_0)$ and then integrated rather than sum. For example isn't your first example (where $H_1: R>0$) more or less the same thing as my green case?
Comment: Again, we might be talking at cross-purposes regarding the actual plots, but the way to look at this is via the blue plot. For R to be statistically significant at a given level, in the one tailed test with H1 R > 0 the observed R would need to be in the right hand blue area. For the H1 R < 0, the observed would have to be in the left hand blue area. For the two tailed test with H0 R = 0, H1 R!= 0, then the observed has to be in either of the blue areas.
Comment: @Backlin Your plots are confusing as the upper and lower panels show the regions for **rejecting** the Null in a one tailed test where H1 R < 0 (upper, red area) and **rejecting** the Null of a two tailed test where H1 != 0 (lower, blue areas). The green area in the middle plot is **not** the rejection area for the one-tailed test with H1 R > 0. I think this is what might be the cause of confusion between people here and yourself. In the one side H1 R > 0 we clearly have no evidence against H0 because the observed R lies *in* the green area.
Answer: Your formula for $p_2$ only works if you have distribution symmetric around $0$, which at least your illustration do not seem to have.
A better estimate is given by  $p_2(t) = {\rm min}(2p_{+}, 2p_{-})$. using your definitions of $p_{+}$ and $p_{-}$.


Home modem/router IP address middle of DHCP pool?

Question: I have a home modem/router/gateway. To make it less findable with hard-coded bad-actor scripts running inside my network, I wanted to put the modem/gateway IP address in the middle of the DHCP pool of addresses instead of ".1" (10.0.0.50, with a DHCP pool of 10.0.0.40-10.0.0.200).
The modem won't let me.  I get one of two errors.  If I put the modem at the edge of the DHCP pool, I get "The Beginning IP Address cannot be the same as the modem IP address."  If I put the gateway somewhere else in the DHCP pool, I get, "The modem IP address cannot be between the beginning IP address and the ending IP address."
Now I know why everybody is pushed to put their modem at x.x.x.1.  If it goes anywhere else, otherwise usable subnet IP addresses are sacrificed from the DHCP pool.  Arghh...
I can't think of a technical reason my gateway shouldn't be able to live in the middle of the DHCP range. Is this just a limit of my device, or is there some technical reason regardless of network hardware vendors?  What am I missing?
Answer:
I have a home modem/router/gateway. To make it less findable with
  hard-coded bad-actor scripts running inside my network, I wanted to
  put the modem/gateway IP address in the middle of the DHCP pool of
  addresses

What exactly is a "hard-coded bad-actor script"?

If a rogue entity has access to your network, putting the router on an ip address other than the "default" isn't going to fool anybody.
If a rogue entity has access to your network then you have bigger things to worry about than your router.
You're tilting at windmills.
Use an ip address close to the beginning or end of your network range, like .10 or .250.
Surely losing a few addresses at the beginning or end of your network range isn't going to be an issue. Unless you have so many network devices as to need every single address in the network range to assign to these devices.
Comment: To emphasize point 1, every device on the network _needs_ to know the router's IP address, and will typically get that information via DHCP on system boot.  This is like "I'm not going to tell you the router's IP address, but if you need to reach the internet, use 10.0.0.50"
Comment: Joeqwerty, I hear your reply sort of as, "that's a silly question."  Okay.  I could explain more at the right time. In this context, however, the original question remains: is there a technical reason to forbid a modem address in the middle of the DHCP pool address space?
Comment: @user4556274, I agree with [others](https://dfarq.homeip.net/clean-malware-router), who identified that a lot of malware just assumes your router is at 192.168.0.1 or 192.168.1.1. If nothing is at those addresses to infect, then the malware just sits harmlessly." You can disagree with me.  That's okay.  To me, it's a bunch of bits and I am just trying to understand if there's any technical reason to justify forbidding arbitrary modem IP in the middle of my DHCP address space.
Answer: It's not that it cannot be in the middle of the range, but it cannot be in the range at all, as having the same address (possibly) assigned to another host would just make everything go haywire. It would work if you use 10.0.0.50 as its address and have 10.0.0.51 - 10.0.0.254 as the range (if it can accept more than one range, 10.0.0.1 - 10.0.0.49 is also usable), unless your router have some more silly checking.
In other words, perhaps you are not aware of the fact that its own address is statically assigned, but not assigned by its DHCP server.
Comment: Tom Yan, I understand the problem of duplicate IPs. However, that's a red herring.  If a DHCP server can reserve (static-like) DHCP addresses for other device MAC addresses, certainly it could reserve it's own specified address from issuing to a second device.
Comment: Red herring doesn't even apply here. As I said, it does not ask the DHCP server for its own address. DHCP reservation (in terms of context, if you know what I mean) expects the reserved addresses to be leased by the server for some corresponding MAC addresses. Certainly you can reserve it for hosts that do not do DHCP and just assign them manually/statically, but you can also leave it out from the pool instead, which again, in terms of context, is the right thing to do, as the MAC addresses isn't really relevant to your goal (and that's the real red herring).
Comment: And at the end of the day, it's all about how the firmware is written. If you are a router vendor, you can certainly write the firmware such that it checks the reservation table and allow the IP reserved for the router's own MAC to be assigned to the router (statically). But you see the clumsiness and silliness here? (It hardly even make sense.) Still, you can do it, if you are the vendor. Just like you can implement the DHCP server so that it can take multiple discrete ranges, btw. (Actually I think dnsmasq can do that, as long as you have access to the conf file.)
Comment: And yes, as the other answer (may have) mentioned/implied, the whole "random one for router" simply isn't a proper approach for security whatsoever anyway. No one in the real world would want to fix problem like that, as it isn't a fix.


Detectar texto dentro de um carácter especial e converte-lo em uma função PHP

Question: É possível percorrer um textarea para detectar um texto dentro do carácter [texto] e transformá-lo em uma função PHP?
Resumindo:
1. Percorrer um textarea
2. Encontrar um texto contendo ao redor []
3. Converte-lo em uma função php
4. Exemplo: [texto] =  Abrephp texto(); Fechaphp
Na prática:
 ...

  <textarea>Lorem impsun [galeria] Lorem impsun</textarea>

 ....

 //Então ao ler a informação "Lorem impsun [galeria] Lorem impsun"
 //O escopo irá tratar como(não dinamicamente):

 ...

Lorem impsun <?php galeria(); ?> Lorem impsun

Comment: Você quer que ao detectar um conteúdo dentro de uma tag executar o comando?
Comment: Exatamente. Editado.
Comment: Faça o teste de usar jQuery `$('textarea').html().replace('[galeria]', 'teste')` e muito facilidade.
Answer: Para o exemplo que deu:
function galeria() {
    return 'Funcao galeria';
}
preg_match('/<textarea>(.*?)<\/textarea>/', '<textarea>Lorem impsun [galeria] Lorem impsun</textarea>', $matches1);
$funcPattern = '/\[(.*?)\]/';
preg_match($funcPattern, $matches1[1], $matches2);
if(isset($matches2[1])) {
    if(function_exists($matches2[1])) {
        echo preg_replace($funcPattern, $matches2[1](), $matches1[1]);
    }
    else {
        echo 'Função ' .$matches2[1]. '() não existe';
    }
}
else {
    echo 'não há função definida';
}

Comment: haha @Lollipop . Ainda bem que ajudei
Comment: Obagdo é porque é suposto imprimir o que está dentro da `` e substituir os `[...]` pelo retorno da função @zekk. Também só soube disso depois do AP dizer no 1º comentário. Vi a sua resposta, também daria com str_replace depois ... Mas não se esqueça que as funções podem ser mais do que uma. Pode haver `galeria1`, `galeria2` etc... Isso seriam muitas verificações e o codigo ficava extenso. O ultimo é para fazer replace no sitio do texto onde está o nome da função
Comment: Entendi o que quis dizer... Criei uma var para a pattern @zekk. Obgado pelo reparo
Comment: tem um problema...onde está o Lorem impsun? Só me retorna "Funcao galeria". Tem que retornar: **Lorem impsun Funcao galeria Lorem impsun**
Comment: Pensei que só quisesse o que estiver dentro de `[]` @Lollipop
Comment: Não manin :( pode ajudar? Mas já dei +1 pelo preg_match
Comment: Vou editar @Lollipop
Comment: Ediatdo @Lollipop
Comment: Te amo...........
Comment: Ficou bacana o código, só uma coisa, por que você usa o `/\[(.*?)\]/` duas vezes? +1
Comment: Miguel, cria um novo, abaixo do que já fez, retirando um preg_match, no caso preciso que retire a condição para que NÃO seja mais entre um , mas sim que ele detecte em qualquer local entre [texto]
Comment: Ou seja qualquer `[...]` certo de um texto qualquer @Lollipop
Comment: Isso. Imagina um monte de paragrafo e entre ele existe um [func] que chama algo. Esquece o , mas mantem o codigo acima que ta show. É a mesma ideia só vai tirar a condição que limita entre o textarea
Comment: O motivo é porque as outras tag estão atrapalhando a execução da verificação e está dando erro.
Comment: Uma pergunta: pode haver mais do uma `[func]`?
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/43432/discussion-between-miguel-and-lollipop).
Answer: Você também pode usar a função strpos para verificar se uma string é encontrada em um texto.
<form method="post" action="#">
  <textarea name="texto" rows="4" cols="40">Lorem impsun [galeria] Lorem impsun</textarea>
  <input type="submit" name="submit" value="Enviar" id="submit"/>
</form>

<?php

$valorTextarea = isset($_POST['texto']) ? $_POST['texto'] : "";

if (strpos($valorTextarea, "[galeria]") !== false){
    FuncaoGaleria();
} else {
    echo "Palavra-chave não encontrada!\n";
}

function FuncaoGaleria(){
    echo "Função Galeria!\n";
}

?>

Edição
Para extrair mais de uma palavra-chave do texto, use a seguinte função:
function extrairPalavras($texto, $sepInicial, $sepFinal){
    $resultado = [];
    $contador = $inicio = $final = 0;

    while ($contador < strlen($texto)){
        $posIn = strpos($texto, $sepInicial, $inicio);
        $posFn = strpos($texto, $sepFinal, $final);

        if ($posIn !== false){
            $inicio = $posIn + 1;

            if ($posFn !== false){
                $final = $posFn + 1;
                $resultado[$inicio] = $final;
            }
        }
        $contador++;
    }
    return $resultado;
}

Use assim:
function funcao1() {
    return '<Funcao galeria 1>';
}
function funcao2() {
    return '<Funcao galeria 2>';
}

$texto = "Lorem [funcao2] impsun [funcao1] Lorem [heya] impsun";
$indices = extrairPalavras($texto, '[', ']');

foreach($indices as $inicial => $final){
    $nomeFunc = substr($texto, $inicial, $final - $inicial - 1);

    if(function_exists($nomeFunc)) {
        if (!isset($textoResultado)){
            $textoResultado = str_replace("[$nomeFunc]", $nomeFunc(), $texto);
            continue;
        }
        $textoResultado = str_replace("[$nomeFunc]", $nomeFunc(), $textoResultado);
    }
}
echo $textoResultado . "\n";
// Lorem <Funcao galeria 2> impsun <Funcao galeria 1> Lorem [heya] impsun

Ver demonstração
Comment: E o Lorem impsun? Porque não aparece?
Comment: @Lollipop Veja a edição.
Comment: lol. perfeito..
Answer: A pedido do @Lollipop não editei/retirei a minha primeira resposta, e ponho aqui uma solução alternativa que concluimos (por conversa em comentários/chat) que seria melhor:
function galeria1() {
    return htmlentities('<Funcao galeria 1>');
}
function galeria2() {
    return htmlentities('<Funcao galeria 2>');
}
$texto = 'Lorem [galeria2] impsun [galeria1] Lorem [heya] impsun';
preg_match_all('/\[(.*?)\]/', $texto, $matches);
foreach($matches[1] as $func) {
    if(function_exists($func)) {
        if(!isset($final)) {
            $final = str_replace('[' .$func. ']', $func(), $texto);
            continue;
        }
        $final = str_replace('[' .$func. ']', $func(), $final);
    }
}
echo $final;

Caso exista uma função não declarada dentro de [...] essa permanecerá no texto, caso não queira no texto acrescente o else {...:
...
if(function_exists($func)) {
    ...
}
else {
    $final = str_replace('[' .$func. ']', '', $final);
}
...

Comment: PERFEITO. Sem mais comentários.


Setting up a server / What should be the hostname?

Question: I'm purchasing a server from a hosting provider and the order form is asking for the following pieces of information:
Hostname     eg. server1(.yourdomain.com)
NS1 Prefix  eg. ns1(.yourdomain.com)
NS2 Prefix  eg. ns2(.yourdomain.com)
Root Password

We need to have the webservice on this server, ie ppl will be accessing www.mydomain.com and the application/apache will be on this machine. If I set it with a name like "main.ourdomain.com", will that mess things up?
What nameservers should I setup? I want to have the domain name registered at the same service provider, but what consequences does entering the ns1/ns2 prefixes have on my server?
Answer: The hostname doesn't have any connection to the sites being hosted, it is just a name for the server doing the hosting. It can be most anything you like, but short and unique is good.
Comment: Thanks Grant - what does setting the ns1/ns2 servers imply?
Answer: Do you (or your organization) have a DNS server? Have you purchased the domain name yet? If so, where did you purchase it from? The nameservers (the NS1 and NS2 they refer to) may be configured by the hosting provider, but it sounds like you may need to configure it yourself. The nameserver is what essentially directs browsers to the right place when they access any subdomain of your domain. You can enter whatever you want for the hostname, but it's common to have it match the name of the server you are running.
If you're unsure about how to set up the nameservers, contact your domain registrar; they should be able to give you more specific information on whether they've configured it or you need to. For example, for my website, the nameservers are NS1.HOSTMONSTER.COM and NS2.HOSTMONSTER.COM, even though my domain is something else entirely.
Answer: You say you are going to have the domain registered  by the same service, by which I assume you mean you want the service provider to host you DNS for you, i.e. you will delegate you domain to the service providers DNS and they will run the DNS servers for you.
In which case I think their question about DNS is simply asking you what name you want to give you DNS servers.
Unless you have a reason not to, I'd go with ns1 and ns2 as they suggest, as that is a common convention,
As for the hostname, as others have said, that does not have to be related to the name of your site - it can be most anything.
My personakl preference is to always have hostnames independant of any service names for services that will run on the host.
E.g. don't have a hostname of "www" or "web" for web servers.
The service name, i.e. the name that you give the public/users to access your sevice should be independant of hostname, so that you can at some other date move the service to another host without requiring the server to be renamed (i.e. have a new hostname set up).


Grid bootstrap ficando desalinhado em painel com resultados trazidos do banco

Question: Estou exibindo o resultado de uma consulta em painéis, só que eles estão ficando desalinhados, quero que mostre como ta na imagem abaixo só que 1 debaixo do outro, da forma que esta, esta gerando um efeito piramide, segue código e imagem de exemplo:

 <?php
      while ($row = mysql_fetch_array($query_chamados)) {

        $var_chamado   = $row['CHAMADO'];
        $var_problema  = $row['PROBLEMA'];
        $var_descricao = $row['DESCRICAO'];
        $var_contato   = $row['CONTATO'];
        $var_telefone  = $row['TELEFONE'];
        $var_abertura  = $row['DATA_DE_ABERTURA'];
        $var_horasemab = $row['HORAS_EM_ABERTO'];
        $var_numloja   = $row['NUM_LOJA'];
        $var_area      = $row['AREA'];
        $var_setor     = $row['SETOR'];
        $var_tecnico   = $row['TECNICO'];
        $var_abertopor = $row['ABERTO_POR'];
        $var_status    = $row['STATUS'];
        $var_painel    = $row['PAINEL'];

echo"

                  $var_chamado
              ";
              if( $var_painel == 1){
              echo"CIENTE";
                }

              echo"

             ABERTO A 0$var_horasemab HORAS

             TELEFONE : $var_telefone

             ABERTO POR: $var_abertopor

             LOJA: 0$var_numloja

";
     }
  echo"
";
 ?>

@Gabriel Sousa
echo"

         ";
if( $var_painel == 0){
  echo"CIENTE
        ";
    }
 echo"

           $var_chamado

";
    }
echo"
";
 ?>

@Matheus Godoi
<?php while ($row = mysql_fetch_array($query_chamados)) : ?>

<?php endwhile; ?>

Answer: o bootstrep usa um sistema de grid que uma linha (row) pode ter ate 12 colunas.
qualdo você dola o loop while
ele gera um numero x de quadrados dentro de uma row
cada quadrado usa coluna usa 4 espaços da row
sendo assim se o while imprimir mais de 3 row exede o valor limite suportado por uma row
tem que se gerar uma logica para a cada 3 quadrados gerados ele feixe a row antiga e abra uma nova
o código fica rial mais ou menos assim
<?php
        $i = 0;
        $row = 0; // contador de quadrados inseridos na row
    ?>

        <?php while($i < 20) : ?>

        <?php
           if($row == 3){
// se dois quadrador for adicionado fecha a row e abre uma nova
                 echo '

 ';
// como a row é nova o marcador zera
                 $row = 0;
               } ?>

        <?php

        $row++; // incrementa 1 pois um quadrado foi adicionado a row
        $i++;

        endwhile; ?>

Comment: Exatamente isso, perfeito , Obrigado !
Answer: Vamos por partes
Semanticamente o HTML esta errado

                  $var_chamado
              ";
              if( $var_painel == 1){
              echo"CIENTE";
                }

              echo"

Tem um h3 dentro de outro h3
pode parecer que não mas isso influencia na forma que o navegador vai renderizar isso na tela.
Outra coisa é o color

No HTML5 deve ser estilizado por CSS esta forma esta obsoleta.
Tenta arrumar o código sem o PHP primeiro, se não complica mesmo,
depois vê se tem error usando este site https://validator.w3.org
por ultimo coloca o PHP.
Tentei organizar já so o HTML

              CIENTE

             ABERTO A 0$var_horasemab HORAS

             TELEFONE : $var_telefone

             ABERTO POR: $var_abertopor

             LOJA: 0$var_numloja

Comment: Editei a pergunta e incluir uma nova edição, limpando ao máximo o codigo, mais o problema persiste, teria mais alguma dica ? ; Veja a edição que coloquei abaixo de seu nome
Comment: O `` precisa ficar fora do `<?php while` caso contrário, a cada novo loop, será criada uma nova row e não é bem isso que queremos.
Comment: Confere se no código todas as `div` estão sendo fechadas. Removi a `div` de fechamento da div de classe col-xs-4 e tudo funcionou direitinho.

Olha: https://jsfiddle.net/matheusasdev/ga3j3wjz/
Answer: Verifique se não há nenhum text-align: center no seu css.
Uma dica: tente corrigir esse echo do PHP. Ao invés de tratar o HTML como uma string simples, use desta forma:
<?php while ($row = mysql_fetch_array($query_chamados)) : ?>

 //código HTML

<?php endwhile; ?>

Obs: Posso estar enaganado (uma vez que eu não conheço todo o contexto do seu projeto) mas como você já está usando o mysql_fetch_array, não é necessário ficar criando variáveis e atribuindo a elas os valores de $row;
Comment: Veja nova edição, fiz como você disse mais ainda continua errado.


How to compare one column array with another?

Question: I have 2 SQLs: SQLa and SQLb. SQLa selects the latest 9 articles from the database. The other does the same but orders the articles by view count. So, I want the second SQL, that is, SQLb not to select articles that is selected in the first SQL (SQLa).
$sqla = "SELECT post_id, title, post_img, cnt FROM post ORDER BY post_id DESC LIMIT 9;";
$sqlb = "SELECT post_id, title, post_img, cnt FROM post ORDER BY cnt DESC LIMIT 9;";

Comment: How is this related to PHP? Why not do this purely in the database?
Comment: a `NOT IN` SQL query should allow you to do this all in one SQL statement, without needing PHP to assit
Comment: @ADyson that doesnt work. Because rows are array
Comment: Sorry I don't understand what you mean. I was thinking something like `SELECT post_id, title, post_img, cnt FROM post WHERE post_id NOT IN (SELECT post_id FROM post ORDER BY post_id DESC LIMIT 9) ORDER BY cnt DESC LIMIT 9;`. Did you try that? What exactly was the result? "doesn't work" isn't really a useful description of any problem you might have. (obviously it would be easier for us to help if we could see your schema and some sample data. A [DBFiddle](https://dbfiddle.uk/) demo would be even better.)
Answer: With a WHERE post_id NOT IN (id,id,id,id) you can exclude the earlier selected posts. To obtain those id's you have to loop the result of the first query and store the id's in an array.

execute $sqla and store in $result.

then loop $result:
$not_in=[];
foreach($result as $row){
   //do what you need to do with the values of query 1
   //...
   //store the id's in an array
   $not_in[]=$row['post_id'];
   }

Now you can use them in your second query:
$in = implode(',', $not_in);
$sqlb = "SELECT post_id, title, post_img, cnt
       FROM post
       WHERE post_id NOT IN ($in)
       ORDER BY cnt DESC LIMIT 9;";


HTML/CSS slider not displaying correctly on mobile

Question: I have a slider in the form of a figure that takes 200% width of the body, inside this figure I have set up 2 images slider one next to another with flexbox each taking 100% width of the body I have set the body to be on overflow-x: hidden; so that only 1 of the 2 images would show at a time. The slider is activated through radio links and a simple transform: translate(-50%);
This works perfectly on PC browsers but unfortunately not on mobile:
as shown in this screenshot here
here's the link to the site containing he slider:
https://jzsgpbizbig5vvch0nnmdg-on.drv.tw/Openclassroom/webagency/Webagency.html
here's the html part of the slider

    <input type="radio" id="i2" name="images" />
    <input type="radio" id="i1" name="images" />

WEBAGENCY: L'AGENCE DE TOUS
VOS PROJECTS!

Vous avez un projet web? La WebAgency vous aide à le réaliser!

Plus d'infos

WEBAGENCY: L'AGENCE DE TOUS
VOS PROJECTS!

Vous avez un projet web? La WebAgency vous aide à le réaliser!

Plus d'infos

And here's the CSS
body
{
    font-family: 'Roboto', Arial, sans-serif;
    display: flex;
    flex-direction: column;
    font-size: 100%;
    width: 100%;
    overflow-x: hidden;

        /* Slider */

    figure
    {
        display: flex;
        position: sticky;
        top: 90px;
        left: 0px;
        width: 200%;
        transition-duration: 1s;
    }

    #slide1 , #slide2
    {
        width: 100%;
        height: 100%;
    }

    #slide1 img , #slide2 img
    {
        width: 100%;
    }

    .text
    {
        position: absolute;
        height: 40%;
        width: 40%;
        left: 5%;
        top: 20%;
    }

    .text2
    {
        position: absolute;
        height: 40%;
        width: 40%;
        left: 55%;
        top: 20%;
    }

    #slide1 h1 , #slide2 h1
    {
        left: 150px;
        top: 150px;
        color: white;
        font-size: 2.4vw;
    }

    #slide1 h1 span , #slide2 h1 span
    {
        color: #30ABB1;
    }

    #slide1 h3 , #slide2 h3
    {
        padding-top: 5px;
        font-family: arial;
        color: white;
        font-size: 1vw;
    }

    #slide1 h5 , #slide2 h5
    {
        display: inline-block;
        color: white;
        background-color: #30ABB1;
        padding: 10px;
        margin-top: 10px;
        border-radius: 3px;
        font-size: 1.5vw;
        cursor: pointer;
    }

    #i1 , #i2
    {
        display: none;
    }

    #i1:checked ~ figure
    {
        transform: translate(-50%);
    }

    #i2:checked ~ figure
    {
        transform: none;
    }

    .left-control
    {
        display: inline-block;
        position: absolute;
        left: 50%;
        top: 50%;
        height: 60px;
        width: 30px;
        border-radius: 0 60px 60px 0;
        background-color: rgba(45 ,45 ,45 , 0.7);
        z-index: 90;
    }

    .left-control i
    {
        position: absolute;
        color: white;
        font-size: 1.3em;
        font-weight: bold;
        top: 30%;
        margin-left: 5px;
        cursor: pointer;
    }

    .left-control:hover
    {
        height: 60px;
        width: 40px;
        transition-duration: 250ms;
        overflow: hidden;
        padding-left: 10px;

    }

    .right-control
    {
        position: absolute;
        right: 50%;
        top: 50%;
        height: 60px;
        width: 35px;
        border-radius: 60px 0 0 60px;
        background-color: rgba(45 ,45 ,45 , 0.7);
        z-index: 80;
    }

    .right-control i
    {
        position: absolute;
        color: white;
        font-size: 1.3em;
        font-weight: bold;
        top: 30%;
        margin-left: 15px;
        cursor: pointer;
    }

    .right-control:hover
    {
        height: 60px;
        width: 40px;
        transition-duration: 250ms;
        overflow: hidden;
        padding-right: 10px;
    }

                                                                /* Slider ends here */

So my question is: How can I make this design work the same on mobile?
Thanks in advance for your time and sorry for the long post. XD
Comment: Welcome to Stack Overflow! Unfortunately your code is incomplete or non-existent (we can't run it). Please read [How to Ask a good question](https://stackoverflow.com/help/how-to-ask) and [how to provide a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
Comment: I agree with ResetACK, and would additionally say that you should include the *actual code* in your question, and not just a link to the code.
Comment: Thank you for your feedback and sorry about the lack of code this is my first post i wasn't sure how to share this, I'll try your suggestions right away ^^
Answer: Only Change
.figure{ position: absolute;}

To
.figure{ position: sticky; }

And
#services{ margin-top: 500px; }

To
#services{ margin-top: 0px; }

also remove this
.section { overflow-y: hidden;}

Comment: Thank you for your feed back this indeed helped improve some issues i was having with the margins between the header and the services sections. But in responsive the second part of the slider is still showing.


How to alter image captcha title in drupal 7

Question: I am working on drupal 7 image captcha module.I want to alter or hide image captcha title like 'What is in your code'.How can I do it by without hacking the module?
Answer: use hook_form_FORM_ID_alter() and Form API pre_render function. E.g:
<code>// Explains pre_render. This is when you create a form;
function feedbackForm($form, &$form_state) {

  $form['#pre_render'][] = 'feedbackForm_pre_render';

  $form['name'] = array(
    '#title' => t('Ваше имя'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );

  $form['actions'] = array(
    '#type' => 'actions',
  );

  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Отправить'),
  );

  return $form;
}

function feedbackForm_pre_render($element) {
  $element['captcha']['captcha_widgets']['captcha_response']['#title'] = t('Защитный код');
  return $element;
}
</code>
You can also use hook_form_alter() function:
<code>function MY_MODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);

  if($form_id == 'FORM_ID') {
    $form['#pre_render'][] = 'feedbackForm_pre_render';
  }
}
</code>
Comment: @user3094034 I don't think that you need to change the image_captcha.module or its functions for this task.. hook_form_alter is the suitable way to achieve this kind of functionality.. If you didn't understand how did I get a rendered $element array, you can install Devel module and use its dpm function within pre_render function, like dpm($element) in my case. it will show you all elements of $element array in readable format.
Comment: Hi,Thank you for quick reply.It worked like charm.Just asking how did you get rendered array like $element['captcha']['captcha_widgets']['captcha_response']['#title'].Earlier I tried to use module_load_include for image_captcha.module to change image_captcha_cpatcha().Could it be done on that way?


Asymptotic behaviour of Integrals

Question: Let $f,g$ be functions in $C_b\left(\left[\varepsilon,\frac{1}{2}\right]\right)$, $\forall \; \varepsilon > 0$, or equivalently $f,g \in C\left(0,\frac{1}{2}\right]$.
We have $f(p) \overset{p \to 0}{\sim}g(p) $, meaning that $\limsup_{p \to 0}\left\lvert\frac{f(p)}{g(p)}\right\rvert < \infty$ and $\limsup_{p \to 0}\left\lvert\frac{g(p)}{f(p)}\right\rvert < \infty$.
My question is, if it holds that
\begin{align*}
  \int_p^{\frac{1}{2}}f(x)dx \overset{p \to 0}{\sim}\int_p^{\frac{1}{2}}g(x)dx \; \; \; ?
\end{align*}
I would be happy for any ideas.
Comment: What is $C_b?\,\,$
Comment: continuous, _bounded_ functions. the first line is as good as writing
$f,g \in C\left(0,\frac{1}{2}\right]$.
Comment: A function in $C(0,1/2]$ need not be bounded.
Comment: We can assume $f,g$ are nonvanishing? (Else those divisions are not defined)
Answer: The integrals are affected by the behavior of f, g everywhere and not just near zero,  so I'd say the answer is no.

Asymptotic behaviour of Integrals


Extending operator from subspace of Banach space to whole space

Question: Let $Y$ be subspace of Banach space $X$.  $T:Y \rightarrow \ell_{\infty}$ is continuous linear operator. Show that there is linear function $S:~X \rightarrow \ell_{\infty}$ such that $S\vert _{Y}=T$ and $\| S \|=\| T \|$
Answer: You have to use the Hahn Banach theorem.
Comsider the linear function $\phi_n$ on $l_{\infty}$ given by $\phi_n(a_1,..a_n,..)=a_n$. Then $\phi_noT$ is a linear functional on $Y$ and by the Hahn Banach theorem, it has an unique extension to a linear functional $\psi_n$(say). Define $S(x)=(\psi_1(x),..\psi_n(x),...)$. Check that $S$ extends $T$ and satisfies that $||S||=||T||$.
Space with such extension property have different names: injective, isometrically injective or $\mathcal{P}_1$-space. There is a deep result due to Nachbin, Goodner, Kelly and others stating that every such space is isometrically isomorphic to the space $C(K)$ of continuous functions on extremelly disconnected compact $K$. For example $\ell_\infty\cong_1 C(\beta\mathbb{N})$, where $\beta\mathbb{N}$ is a Stone-Chech compactification of $\mathbb{N}$.
Comment: I was thinking about it, but I failed. Could you give me more precise hint or write a solution?
Comment: Sure- let me edit my answer.


What triggers the usage of the negative time to live DNS SOA record value?

Question: I'm reading through the following dns tutorial and it has this example in it:
domain.com.  IN SOA ns1.domain.com. admin.domain.com. (
                                        12083   ; serial number
                                        3h      ; refresh interval
                                        30m     ; retry interval
                                        3w      ; expiry period
                                        1h      ; negative TTL
)

The description for the negative TTL value says this:

1h: This is the amount of time that the name server will cache a name error if it cannot find the requested name in this file.

What are the conditions that could trigger the server to cache a name error like this?  An example would be really helpful.
Answer: The negative caching interval in the SOA comes into play when an authoritative server indicated that the requested record did not exist. The specific cases are:

Replies with a response code of NXDOMAIN.
Replies with a NODATA synthetic state, but only forms where a SOA record is present.  (NOERROR rcode, 0 answers, 1 SOA record in authority section + optional NS records)

It's common for server software to enforce a locally configured maximum on this value, so even if you have a negative TTL of 86400 the non-existence isn't necessarily going to be cached for that long by remote recursive servers.
The cases are covered by section RFC 2308 if you want to read further. Read section 2 as a primer, then 5-6.
Comment: IIUC if I request "not.available.example.com" from the authoritative server then it gets cached for the negative time to live?
Comment: Correct. Full recursive servers will reliably cache the non-existence, but behavior of stub resolvers (such as OS resolver libraries) will vary. Windows does, for example. You would find "Name does not exist." in the output of `ipconfig /displaydns`, which represents `NXDOMAIN`. You'll find instances of "No records of type X" in that output as well, which corresponds to `NODATA`. Most UNIX based systems do *not*, because they do not cache at all without additional configuration. (`nscd` with caching enabled, local recursive server and using 127.0.0.1 for DNS lookups, etc.)
Comment: So if I'm imagining the purpose correctly, is it to be able to double check that "not.available.example.com" really was not available according to the full recursive server?  In other words if I don't get an ip address, I can query the server at something like a /displaydns endpoint, and the result should contain confirmation that the address does indeed not exist?
Comment: `ipconfig /displaydns` exists to tell you the contents of the local stub resolver cache. No more, no less. What admins might want to do with that info is open ended.
Comment: @Ole The purpose is to prevent repeated queries for the name, once the server has already told the resolver that it doesn't exist. Just like any other caching.


Convert categorical data to numerical data to compute a distance then

Question: I want to calculate euclidean distances for a dataset I have. However, there are two attributes which are not numbers. One attribute is country(10 different countries), the other one is race(3 races). I think I need to convert these two categories into numbers somehow. I am thinking to use 0, 1, 3 to represents different races. But, I don't think this could give me meaning results. What are the common techniques could be used to transform these attributes?
Comment: Why do you need distances at all? What do you want to do with them? If you have mixed types of variables, people typically use Gower's distance (eg, see [here](http://stats.stackexchange.com/a/164694/7290)).
Comment: [Gower](http://stats.stackexchange.com/a/15313/3277) coefficient is often used as the (dis)similarity between data points when attributes are mixed (categorical, continuous). But generally it is not a very good idea to try to compute a distance on such mixed attributes because of the problematic issue of reasonable weighting them.
Comment: Why do you need Euclidean distances? They wouldn't often make sense for categorical variables.
Answer: Why should a comparison between races 0 and 1 be considered less dissimilar than comparisons between races 0 and 3 or races 1 and 3?
Consider instead using Gower's generalised similarity measure:
$$d_{jk} = \frac{\sum_{i=1}^m w_{i}d_{ijk}}{\sum_{i=1}^m w_{i}}$$
(here expressed as a dissimilarity as will become apparent shortly). $d_{jk}$ is the dissimilarity between samples $j$ and $k$ where $i$ indexes the $m$ variables in the dataset. The $w_{i}$ are weights that can be assigned to each variable to downweight their contributions to the dissimilarity.
For continuous variables we compute
$$d_{ijk} = 1 - \frac{|x_{ij} - x_{ik}|}{R_i}$$
where $R_i$ is the range of the the $i$th variable. This implies a standardisation of the continuous variables to account for differences in scales. The 1- bit here turns this into a dissimilarity.
For categorical data $d_{ijk}$ is computed as
$$ d_{ijk} = \left \{
  \begin{array}{lr}
    0 & : x_{ij} = x_{ik}\\
    1 & : x_{ij} \neq x_{ik}
  \end{array}
\right. $$
which basically means that if $j$ and $k$ match on the $i$th category then 0 is added to the cumulative dissimilarity over the $m$ variables. If $j$ and $k$ do not match on the $i$th variable then 1 is added to the dissimilarity.
As the dissimilarity is computed for each pair of samples variable by variable, you can use mixed data such as you describe, with each comparison contributing the same amount of information to the final dissimilarity (assuming $w_i = w \: \forall \: i$).
Answer: How you should do this (and whether you should do it at all) depends a lot on why you need a dissimilarity measure and what "similarity" means for you.
If you just have categorical data, then @Gavin gave an excellent method that will work very well for e.g. cluster analysis.
But perhaps you have more?  You say you have 10 countries. Countries are differently similar to each other: The United States is more like Canada than it is like Laos, for instance.  But how dissimilar countries are depends on the characteristics that you are interested in.  There is lots of available data on countries and you might be able to use that data to get a better dissimilarity measure.  You might even do some preprocessing (e.g. a factor analysis) to get that.


C line wrap indentation rules in emacs

Question: I am currently working on a C project with other people where they have decided that the indent style for wrapped lines is to indent 8 spaces, instead of where the opening parenthesis/bracket is, e.g.
if (long cond 1 &&
        long cond 2 &&
        long cond 3) {
    //do stuff
}

instead of
if (long cond 1 &&
    long cond 2 &&
    long cond 3) {
    //do stuff
}

However, emacs defaults to the latter and I don't know how to change it to behave like the former. Anyone know how to do this?
Answer: Put this in your .emacs:
(c-set-offset 'arglist-cont-nonempty 8)

C line wrap indentation rules in emacs


Why does scikit learn's HashingVectorizer give negative values?

Question: The HashingVectorizer in scikit-learn doesn't give token counts, but by default gives a normalized count either l1 or l2.
I need the tokenized counts, so I set norm = None. However, after I do this, I'm no longer getting decimals, but I'm still getting negative numbers. It seems like the negatives can be removed by setting non_negative = True. However, I don't understand why the negatives are there, or what they mean. I'm not sure if they're corresponding to the token counts. Can someone please help explain? How do I get the HashingVectorizer to return token counts?
You can replicate my results with the following code - I'm using the 20newsgroups dataset which comes with scikit learn:
from sklearn.datasets import fetch_20newsgroups
twenty_train = fetch_20newsgroups(subset='train', shuffle=True, random_state=42)
from sklearn.feature_extraction.text import HashingVectorizer

# produces normalized results with mean 0 and unit variance
cv = HashingVectorizer(stop_words = 'english')
X_train = cv.fit_transform(twenty_train.data)
print(X_train)

# produces integer results both positive and negative
cv = HashingVectorizer(stop_words = 'english', norm=None)
X_train = cv.fit_transform(twenty_train.data)
print(X_train)

# produces only positive results but not sure if they correspond to counts
cv = HashingVectorizer(stop_words = 'english', norm=None, non_negative = True)
X_train = cv.fit_transform(twenty_train.data)
print(X_train)

Answer: I got my answer from sci-kit learn's mailing list. Here it is:
"it's a mechanism to compensate for hash collisions, see
https://github.com/scikit-learn/scikit-learn/issues/7513 The absolute
values are token counts for most practical applications (if you don't
have too many collisions).  There will be a PR shortly to make this more
consistent."
(The above response is from Roman Yurchak)


Find expression for p-value of significance test in terms of Φ(f(a)) when the value of a is unknown?

Question: What keeps me from solving this question is that the values that a can take are not given, hence we don't know where in the distribution of X it'll be located. It if were, let's say on the left side of µ, then I'd find P(X<a) and times that by two but since I don't know where it's located it might as well be on the right side and then P(X<a) would not give half of alpha...
The answer to this question is 2phi(-(15-a)/1.5)
Comment: is it so difficult to begin to use MathJax for your formulas?
Comment: Yeh, sorry, it's just, I don't know where to find it in the posting section...
Answer: $\alpha$ is not needed. They ask you to find the p-value, that is the area of the two tails of the gaussian
I suppose you know that $a\sim N(\mu;\frac{\sigma^2}{n})$ and thus your p-value is
$$\mathbb{P}[Z >\frac{|a-15|}{\sqrt{\frac{4.5^2}{9}}}]=\mathbb{P}\Bigg[Z >\frac{|a-15|}{1.5}\Bigg]$$
..and this is exaclty what  you solution states (it is just a matter of writing this probability in terms of $\Phi$ but I think you can do it by yourself)
After calculating it, if you  p-value is lower than the fixed $\alpha$ you will reject your null hypothesis, if it will be higher you will not reject it.
Comment: Right, okay, I now understand that α is not needed. However, how did you know to standardize the value of a? Wouldn't 2Φ(|a|) be equally correct?
Comment: @Manolis Gustavsson: no, under $H_0$ the sample mean is gaussian distribuited with mean 15 and variance $\frac{4.5^2}{9}$
Comment: thank you for your explanation. However, in your calculations above, shouldn't we be using the inequality 'smaller or equal to' instead so that we can use Φ(z), and then wouldn't we have -abs(a-15)/1.5? (I'm just asking cause I'm not sure myself)
Comment: @Manolis Gustavsson : do a drawing and use the symmetry of $\Phi$
Comment: Okay, one last thing, how do I go from 2Φ(-abs(a-15)/1.5) to 2Φ(-((15-a)/1.5))?