O restante do código dentro do Try é executado após encontrar Exception?

Question: O resto do código existente dentro de um try é executado após encontrar uma exception ou pula direto pro código dentro do catch(Exception e)
try{
  x = 10;
  //alguns erro de try catch
  x = 20;
} catch (Exception e)
{
  x++;
  MessageBox.Show("Valor de x: " + x);
}

No caso a mensagem mostraria 11 ou 21?
Comment: Se a `Exception` ocorrer na linha que você está comentando o resultado seria `11`, pois o `x` sairia do bloco com valor `10`.
Comment: Concordo com o Fernando, o valor de X será impresso como 11.
Answer: Resposta curta:
Exibirá o valor 11. O valor 21 nunca seria exibido, pois o bloco catch é executado apenas quando houver uma exceção.
Resposta longa
Vamos lá, diretamente do MSDN

When an exception is thrown, the common language runtime (CLR) looks
  for the catch statement that handles this exception. If the currently
  executing method does not contain such a catch block, the CLR looks at
  the method that called the current method, and so on up the call
  stack. If no catch block is found, then the CLR displays an unhandled
  exception message to the user and stops execution of the program.

Isto é, quando uma exceção é levantada, o CLR procura pelo catch mais próximo de onde esta exceção foi levantada e executa seu bloco de código. Isto significa que caso o bloco atual de código onde a exceção foi levantada não possui um catch, este catch será procurado nos métodos que o chamaram até chegar no topo da pilha de chamadas, onde será levantada uma exceção do tipo Unhandled Exception para o usuário, parando a execução do programa.
Então...

O resto do código existente dentro de um try é executado após
  encontrar uma exception ou pula direto pro código dentro do
  catch(Exception e)

O bloco try contém o código que pode levantar uma exceção, e ele será executado enquanto não houver uma exceção ou até que seja finalizado. Em outras palavras, caso uma exceção ocorra, ele irá procurar diretamente pelo catch mais próximo sem executar o restante do código dentro do bloco try.

The try block contains the guarded code that may cause the exception.
  The block is executed until an exception is thrown or it is completed
  successfully. For example, the following attempt to cast a null object
  raises the NullReferenceException exception:

Por que este comportamento?
Uma exceção indica que algo fora do comum ocorreu durante a execução do seu código. Se "algo de errado" ocorreu durante esta execução, você quer que o restante de seu código seja executado normalmente? O bloco catch deve ser utilizado justamente para executar um código específico para estes casos anormais, quando você sabe que eles podem acontecer.
O bloco catch pode ser utilizado de várias formas, como pode ser visto abaixo:
catch(InvalidOperationException ex)
{
  //Deve ser executado quando uma exceção do tipo InvalidOperationException seja levantada
}
catch(SqlException ex) when (ex.Message.Contains("TIMEOUT"))
{
   //Deve capturar uma exceção do tipo SqlException e que contenha no message a palavra TIMEOUT
}
catch(Exception ex)
{
   //Deve capturar uma exceção que não seja uma InvalidOperationException ou **SqlException que não contenha** no message a palavra TIMEOUT
}

Evite capturar exceções genéricas (Exception ex) em códigos específicos da sua aplicação, a menos que você saiba o que está fazendo (registro de log no ponto mais alto do sistema, por exemplo), ou levante ela novamente com um throw ou colocando-a como uma Inner Exception. Por fim, existem algumas categorias de exceções que você pode utilizar para se guiar sobre o seu tratamento:

Usage errors: Um erro de uso representa um erro na lógica do programa
que pode resultar em uma exceção. Contudo, este tipo de erro não deve
ser resolvido com um bloco try catch, e sim com uma modificação no
código a ser executado. É um erro que você sabe que vai acontecer e
que pode ser evitado.
Program error: Um erro em tempo de execução que não pode ser evitado na construção do código pode se enquadrar nesta categoria. Imagine que você precisa ler um arquivo em um diretório específico. Para não cair no Usage error, você verifica antes se este arquivo existe para poder então utiliza-lo. Contudo, embora a verificação tenha retornado verdadeiro para a existência do arquivo, no momento da leitura ele encontrou-se indisponível (foi deletado ou está sendo utilizado por um outro processo), levantando uma exceção de FileNotFoundException, ou similar.
System failures: Falhas no sistema são exceções que podem ocorrer em tempo de execução e que normalmente não podem ser tratadas de forma muito útil. O que você como desenvolvedor pode fazer caso seja levantada um OutOfMemoryException? Você pode contudo, registrar as informações desta exceção em um log antes que a aplicação seja finalizada, para uma posterior análise de forma a evitar que este erro ocorra novamente.

Leituras recomendadas

"Boas práticas com exceções"
Exceções consomem muito processamento?
Answer: A execução do código é interrompida no momento em que a exceção é encontrada, portanto, a resposta é não. O restante do código abaixo da exception não é executado.
Este é um dos objetivos da estrutura try/catch. Você pode prever algum erro (exceção) que o código possa gerar e trata adequadamente, sem que o programa trave e exiba erros na tela do usuário.
try{
  x = 10; //Aqui está atribuindo valor 10 a variável x
  // exceção capturada pelo try/catch
  x = 20; // Essa linha não é executada por causa da exception.
} catch (Exception e)
{
  x++; //x está recebendo ele mesmo (10) mais 1;
  MessageBox.Show("Valor de x: " + x);
}

Portanto a mensagem impressa seria Valor de x: 11
Answer: Coloquei um exemplo completo e verificável no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura. Veja também no SharpLab.
Note que a linha do x = 20; tem um warning indicando que ela nunca será executada. Claro que se p throw estivesse dentro de um método ou em algo condicional isso não ocorreria. Mas o exemplo é justamente para o caso de ser certo que o lançamento da exceção será executado. O próprio compilador informa que é garantido que o código não será executado nessa circunstância.
using System;
public class C {
    public static void Main() {
        int x = 0;
        try {
          x = 10;
          throw new Exception();
          x = 20;
        } catch (Exception) {
          x++;
          Console.WriteLine($"Valor de x: {x}");
        }
    }
}

Para quem tem um conhecimento mais avançado pode ajudar ver o IL:
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: stloc.0
IL_0003: nop
IL_0004: ldc.i4.s 10
IL_0006: stloc.0
IL_0007: newobj instance void [mscorlib]System.Exception::.ctor()
IL_000c: throw
IL_000d: pop
IL_000e: nop
IL_000f: ldloc.0
IL_0010: ldc.i4.1
IL_0011: add
IL_0012: stloc.0
IL_0013: ldstr "Valor de x: {0}"
IL_0018: ldloc.0
IL_0019: box [mscorlib]System.Int32
IL_001e: call string [mscorlib]System.String::Format(string, object)
IL_0023: call void [mscorlib]System.Console::WriteLine(string)
IL_0028: nop
IL_0029: nop
IL_002a: leave.s IL_002c
IL_002c: ret

Answer: Em adição ao que já foi dito,
se quiseres que um bloco de código seja executado apesar de ser apanhada uma excepção, podes incluir o Finally a seguir ao Catch.
   try
   {
        // Código a executar
   }
   catch(Exception)
   {
        // Código para tratar a excepção
   }
   Finally
   {
        // Código a executar mesmo que seja accionada uma excepção
        // Exemplo: Fechar um ficheiro que tenha sido aberto pelo System.IO.StreamReader
   }

Answer: O valor de X será 11 se a exceção for disparada entre:
X = 10 e X = 20.


facets do not display on my search page

Question: I've setup apache solr and the facet api for my drupal 6 site, however I can't seem to get my facets to show up on my search page. The only time they show up is when I enable 'show enabled facet blocks under the search box' when there are empty results.
I tried to add my facet block to a region, but it remains blank.
I would think the facets should display on the search page automatically?
Answer: You should put your facet blocks into a regions and also you should be sure that they are rendered after the search is executed.

facets do not display on my search page


How would the condition for linearity for function with multiple variable be given?

Question: I know that a function is called linear if it satisfies the conditions
$$f(x+y)=f(x)+f(y)$$
and
$$f(ax)=af(x)$$
(i.e. it preserves the properties or operation).
How is the condition for linearity given when there are multiple variable in the funciton?
for ex
$$f(x+y,z)$$ and
$$f(ax,z)$$
I know
$$f(x+y,z)=f(x,z)+f(y,z)$$
is a condition for multilinear function, but can there be multivariable function which is linear and not multilinear,ie linear in all the variables at once and not seperately (like in multilinear function). How to make sense of multivariable function that is linear and that is multilinear?
Edit: Extra details.
A function $f(x,y)$ is called multlinear(bilinear to be specific) if
$$f(x+a,y)=f(x,y)+f(a,y)$$
$$f(x,y+b)=f(x,y)+f(x,b)$$
and also $$f(nx,y)=nf(x,y)=f(x,ny)$$.
So is
$$f(x+a,y+b)=f(x,y+b)+f(a,y+b)+f(x+a,y)+f(x+a,b)+f(x,y)+f(a,b)+f(x,b)+f(a,y)$$
when $f(x,y)$ is multilinear and
$$f(x+a,y+b)=f(x,y)+f(a,b)$$
when $f(x,y)$ is linear?
Comment: Multlinear means linear in each variable separately, the classic example is $\det$. It is a weaker condition than linearity (in all variables).
Comment: @copper.hat I know when a multivariable function can be called a multilinear function. When can the multivariable function be called a linear function? or does being linear means defining it separately with respect to each individual variables. Also what does linearity in all variable mean?
Answer: Let $f:\mathbb{R}^{n}\rightarrow\mathbb{R}^{m}$ a function. We say $f$ is linear in the $i^{th}$ variable if, given fixed $x_{j}$ for $j\neq i$ the function $T$ defined by
$$T(x)=f(x_{1},x_{2},\dots,x_{i-1},x,x_{i+1},\dots,x_{n}) $$
is linear. If $f$ is linear in the $i^{th}$ variable for each $i$, we say that $f$ is multilinear.
For example, an inner product <$\cdot,\cdot$> is bilinear, because
$$\left<x+y,z\right>=\left<x,z\right> + \left<y,z\right> $$
$$\left<x,y+z\right>=\left<x,y\right> + \left<x,z\right> $$
Comment: @GRANZER a function that is multilinear is linear in each variable separately. A function is linear if it's a linear in all variables simultaneously. For example the determinant function is multilinear, but not linear.
Comment: @GRANZER Rather than think of them as variables think of it as a vector with scalar coefficients.Then you simply have to verify the usual linear condition which is $f(ax)=af(x)$ and $f(x + y)=f(x)+f(y)$ where $a$ is a scalar with $x$ and $y$ vectors. Note that scalar multiplication and vector addition impact all the variables at once which is why we say "simultaneously" for this case.
Comment: @GRANZER for a multilinear function it should go $f(x+a,y+b) = f(x,y+b)+ f(a,y+b) = f(x,y) + f(x,b) + f(a,y) + f(a,b)$ just like you wrote and you seem to understand what being linear in all the variables means as well so I'm not sure your understanding needs correction.
Comment: @MateuRocha When would the multivariable function be called linear and not multilinear?
Comment: @MateusRocha exactly what I was thinking ie a multi-variable function is linear if it is linear in all the variables simultaneously. But I don't know how to write. ie what being linear simultaneously means...what is the condition for  f(x+a,y+b) to be called linear or multilinear.
Comment: @CyclotomicField exactly what I was thinking ie a multi-variable function is linear if it is linear in all the variables simultaneously. But I don't know how to write. ie what being linear simultaneously means...what is the condition for  f(x+a,y+b) to be called linear or multilinear.
Comment: @CyclotomicField Ok please tell me where I am wrong in my understanding.....For For multivariable  linear function : f(x+a,y+b) =f(x,y)+f(a,b), so f(x+a,y)=f(x,y)+f(a,0) -> so (x,y) can be taken as a vector X=(x,y) and (a,b) or (a,o) can be taken as vector A=(a,b) or A=(a,0).i.e Linear function can always be taken as f(X+A)=f(X)+f(A);;  For multilinear function: f(x+           a,y+b)=f(x,y)+f(x,b)+f(a,y)+f(a,b); f(x+a,y)=f(x,y)+f(a,y);;
Comment: @CyclotomicField My doubts between linear and multilinear are clear for now. Thank you. Basically,a multivariable function being linear separately in each variable doesn't mean its linear in all of them simultaneously. Now I understand what it means intuitively.
Answer: If the function $\, f \,$ is the sum of linear functions in each variable separately then you can call the function linear. For example, if
 $\, f(x,y,z) := ax + by + cz, \,$ then $\, f(nx,ny,nz) = n \, f(x,y,z) \,$ and
 $$\, f(x_1\!+\!x_2, y_1\!+\!y_2, z_1\!+\!z_2) = a(x_1\!+\!x_2) \!+\! b(y_1\!+\!y_2) \!+\! c(z_1\!+\!z_2) = f(x_1,y_1,z_1) \!+\! f(x_2,y_2,z_2). \,$$
An example of a bilinear function is $\, f(x,y) = axy \,$ where $\, f(nx,y) = f(x,ny) = n\, f(x,y) \,$ and
 $$\, f(x_1+x_2,y_1+y_2) = f(x_1,y_1) + f(x_1,y_2) + f(x_2,y_1) + f(x_2,y_2). \,$$


What are the pitfalls of exclusively using PIP in a CONDA environment?

Question: Background
The official documentation and this blog in the same website - recommend to install as many requirements as possible with conda then use pip. Apparently this is because conda will be unaware of any changes to the dependencies made by pip and therefore will not be able to resolve dependencies correctly.
Question
Now if one exclusively uses pip and go without installing anything with conda, it seems reasonable to expect conda does not need to be aware of any changes made by pip - as conda effectively becomes a mere tool to isolate dependencies and manage versions. However, this goes against official recommendation as one will NOT install as many requirements as possible with conda.
So the question remains: is there any known drawback from exclusively using pip in a conda environment?
Similar Topics
A similar topic in has been touched a bit in here but does not cover the case of exclusively using pip in a conda environment. I have also been here:

Specific reasons to favor pip vs. conda when installing Python packages
What is the difference between pip and conda?
Using Pip to install packages to Anaconda Environment
Answer: Not sure one can give a comprehensive answer on this, but some of the major things that come to mind are:

Lack of deep support for non-Python dependency resolution. While more wheels that bundle non-Python resources have become available over time, it is nowhere near the coverage that Conda provides by being a general package manager rather than Python-specific. For anyone doing interoperable computing (e.g., reticulate), I would expect Conda to be favored.

Optimized libraries. Sort of related to the first point, but the Anaconda team has made an effort to build optimized versions of packages (e.g., MKL for numpy). Not sure if the equivalent is available through PyPI.1

Wasteful redundancy across environments. Conda uses hardlinking when packages and environments are on the same volume, and supports softlinking for spanning across volumes. This helps to minimize replicating any packages that are installed in multiple environments.

Complicates exporting. When exporting (conda env export) Conda doesn't pick up all pip-installed packages - only the ones that come from PyPI. That is, it'll miss things installed from GitHub, etc.. If one did go the pip-only route, I  think a more reliable export strategy would be to use pip freeze > requirements.txt, and then make a YAML like
channels:
  - defaults
dependencies:
  - python=3.8  # specify the version
  - pip
  - pip:
    - -r requirements.txt

with which to recreate the environment.

All that said, I could easily imagine that none of these matter to some people (most of them are conveniences), especially those who tend to work purely in Python. In such cases, however, I don't see why one would not simply forgo Conda altogether and use a Python-specific virtual environment manager.

[1] Someone please correct me if you know otherwise.
Comment: [1] `numpy` on PyPI defaults to OpenBLAS which is comparable to MKL, their performance depends on whether the hardware is Intel/AMD as far as I know. So perhaps it's not a drawback but still it's nice to know


Contour Integration of $\int_0^{\infty} \frac{\sin ^3 t}{t} dt$

Question:
Use contour Integration to evaluate $\int_0^{\infty} \frac{\sin ^3 t}{t} dt$.

First note that $\sin^3 (t)= \Im (\frac{3e^it-e^{3it}}{t})$.
Here I have something like a half donut in the upper half plane.
$\gamma_1$ is the semi-circle with radius $R$ going counterclockwise, where $\theta\in [0,\pi]$
$\gamma_2$ is the line from $-R$ to  $-\epsilon$.
$\gamma_3$ is the semi-circle with radius $\epsilon$ going counterclockwise, where $\theta\in [0,\pi]$
$\gamma_4$ is from $\epsilon$ to  $R$.
For $\gamma_3$, we have $|\int_{\gamma_3} \frac{\sin^3(t)}{t} dt| \leq \frac{\sin^3(\epsilon)}{\epsilon} \pi \epsilon \rightarrow 0$
as $\epsilon \rightarrow 0$.
However, for $\gamma_1$, we can't do this anymore, so we have to evaluate this directly.
So for $\gamma_1$, we have $\int_{\gamma_1} \frac{\sin^3(t)}{t} dt$ But it seems very complicated to evaluate. So I wonder if there's any simpler way of evaluating this, or am I missing something in my calculation?
Thanks in advance!
Comment: Since $0$ isn't a true pole (but rather a removable singularity) of $\frac{\sin^3t}{t}$ - which is why the integral on $\gamma_3$ has $\lim_{\epsilon_to0^+}$ equal to $0$ - we can in fact use an ordinary semicircular contour, if we spot e.g.$$\sin^3t=\Im\frac{3e^{it}-e^{3it}-2}{4}$$for $t\in\Bbb R$.
Answer:
Is there any simpler way of evaluating this?

I'll provide a solution with the Lobachevsky's Dirichlet Integral Formula:
$$\int_0^\infty \frac{\sin x}{x} f(x)dx=\int_0^\tfracπ2 f(x)dx $$ so here we take $f(x)=\sin^2x$. So $$\int_0^\infty \frac{\sin^3 x}{x} dx=\int_0^\tfracπ2\sin^2 xdx$$$$=\int_0^\tfracπ2\frac{1-\cos 2x}{2}dx$$$$=\fracπ4.$$
Answer: It's a good idea to use $\sin^3 t=\Im(3e^{it}-e^{3it})/4$. Then $$0=\left[\int_{\gamma_1}+\int_{\gamma_2}-\int_{\gamma_3}+\int_{\gamma_4}\right]\frac{3e^{iz}-e^{3iz}}{z}\,dz,$$
$$\lim_{\substack{R\to\infty\\\epsilon\to 0}}\left[\int_{\gamma_2}+\int_{\gamma_4}\right]\frac{3e^{iz}-e^{3iz}}{z}\,dz=8i\int_0^\infty\frac{\sin^3 t}{t}\,dt,$$
$$\lim_{R\to\infty}\int_{\gamma_1}\frac{3e^{iz}-e^{3iz}}{z}\,dz=0,\tag{1}\label{jordan}$$
$$\lim_{\epsilon\to 0}\int_{\gamma_3}\frac{3e^{iz}-e^{3iz}}{z}\,dz=\pi i\operatorname*{Res}_{z=0}\frac{3e^{iz}-e^{3iz}}{z}=2\pi i\tag{2}\label{halfres}$$
(where \eqref{jordan} follows from Jordan's lemma, and \eqref{halfres} holds by  "half-residue" trick).
Answer: We have $\int_{0}^{+\infty}\frac{\sin x}{x}\,dx = \frac{\pi}{2}$, so via $x\mapsto nz$ we also have $\int_{0}^{+\infty}\frac{\sin(nz)}{z}\,dz = \frac{\pi}{2}$ for any $n\in\mathbb{N}^+$. Since
$$ \sin^3(z) = \left(\frac{e^{iz}-e^{-iz}}{2i}\right)^3 = -\frac{e^{3iz}-3e^{iz}+3e^{-iz}-e^{-3iz}}{8i}=\frac{3\sin z-\sin(3z)}{4}$$
it follows that
$$ \int_{0}^{+\infty}\frac{\sin^3(z)}{z}\,dz = \frac{3-1}{4}\cdot\frac{\pi}{2}=\color{blue}{\frac{\pi}{4}}.$$
More generally, for any $m\in\mathbb{N}$
$$ \int_{0}^{+\infty}\frac{\sin^{2m+1}(z)}{z}\,dz = \frac{\pi}{2}\cdot\frac{\binom{2m}{m}}{4^m} $$


What is the most efficient set order in GAMS?

Question: The documentation suggests that sets should appear in the same order to increase performance. If most of our variables share a set, is it better to have the common set first or last?
I.e. which is more efficient?
  y[i,t] =E= a[t] * x[j,t];

or
  y[t,i] =E= a[t] * x[t,j];

Answer: The main point of this "same order" is, that the sets should be used in the order they are controlled. So
Equation1(t,i,j).. y[t,i] =E= a[t] * x[t,j];

should be better than
Equation2(i,j,t).. y[t,i] =E= a[t] * x[t,j];

Other than that, it is not so easy to give many general rules. If you have also full control over the controlling indices, often it is beneficial, if the largest set is last, so if t >> i, than x[i,t] should be better than x[t,i]. In general, the GAMS command line parameter profile (https://www.gams.com/latest/docs/UG_GamsCall.html#GAMSAOprofile) is very useful to check the influence of different formulations of your mode.
Comment: Equation1 should be faster. But not sure, if you want to do a major reformulation for this difference. I made a trivial experiment (cannot post it completely here in the comment): `$set max 200
Set t / t1*t%max%/
    i / i1*i%max%/
    j / j1*j%max%/;
...
Equation1(t,i,j).. y[t,i] =E= a[t] * a[t] *b[t] *c[t] *d[t] * z[t] * x[t,j];
Equation2(i,j,t).. yy[i,t] =E= a[t] * a[t] *b[t] *c[t] *d[t] * z[t] * xx[j,t];`

Here is the profile on my machine:
14.812sec Equation1 (8000000); 16.265sec Equation2
Comment: Thanks! It makes sense that the controlling indices and size of sets are relevant.

Does your answer imply that there is no clear rule of thump for which should be faster between:

Equation1(t,i,j).. y[t,i] =E= a[t] * .. z[t] * x[t,j];

and

Equation2(i,j,t).. y[i,t] =E= a[t] * .. z[t] * x[j,t];

Given that the sets have the same size?
I.e. putting a set shared by most variables first or last (time index in a large dynamic model).

The profiler has been very helpful, but in this case would need a substantial re-formulation to check.
Comment: Very interesting. That is significant enough that I will give the reformulation a try when I have time.
Answer: In case anyone stumbles upon this, the context is a large dynamic economic model.
We tried switching our time index from always being the last set to always being the first.
The model is a square system of around 1m equations, 7m Jacobian elements, of which 2m are non-linear.
The solution time using CONOPT4 was significantly worse after the change. I.e. we have better performance with the time index last rather than first, despite the time index being among the largest sets in the model. The result is probably not transferable to other models, but confirms that there is no trivial answer.


Drupal authentication for a non-Drupal script

Question: I have a non-Drupal PHP script I would like to put on a D7 Drupal site, but I would like it to be available only to users who have logged in via Drupal. What are the best/easiest ways to do this? It's my script, so I can change it any way I want, embed it in a module, a PHP-capable field, etc.
To be specific, it's a signup sheet system that uses form submissions, using files (not the db) to store the data.
Answer: You can wire up your script via a hook_menu, and instead of returning the output to render via Drupal, you can print it directly and exit at the bottom of the function.  The submission handler would do the same thing, but drupal_goto() at the end.
That said, this is a moderately bad idea for the long run.
A better solution would be to use Webforms.  Webforms are really easy to make, get stored in the database, and can be exported to Excel.  I wouldn't be surprised if there is webform hook available so you could do your filesystem thing, too.
Another option is to use the Forms API to make your form w/ your custom validation and submission handlers.
Comment: For more info about my signup sheets requirements, see http://drupal.stackexchange.com/questions/19178/complex-signup-sheets. Unfortunately neither Webforms nor a homegrown Form solve the problem.
Comment: Forms API lets you do pretty much anything you could image that involves user data and the database.  I wouldn't rule it out as a solution.
Comment: I agree, the long-term solution is to Drupalize the script or find some Drupal-based substitute. But in the short term, it sounds like hook_menu() and checking permissions as user1359 suggested is the way to go. Do you agree?
Comment: Implmenting hook_menu pretty much implies setting "access arguments" and/or "access callback" arguments, so yeah, this would likely fit the bill.
Answer: Another option, though you might find it to be too much work, is to roll your functionality up in a module. With a hook_menu call back, you can have the the module run any php code you define. So you would get both your Drupal authentication and your PHP functionality all in one go :)
Edit You would have to create a permission hook in order to limit access to it.
Comment: But you wouldn't get any Drupal _authentication_ with this solution, you'd just get your PHP into Drupal.  If you want authentication, you need to look at the answer @MPD has given.


How To Make All Cells Look The Same On All Devices

Question: Oki so first this is what i want it to look like:
http://i.gyazo.com/e76bf129ee7ae96ce0e2d84baba8e9a8.png
But on different screens it looks like:
http://i.gyazo.com/c756202d83c773b285e00ad161a67266.png
My cells width and height are both 188 if that means anything (This is set by collectionView) I Do want the width and height to be the same also like a square.
The Collections View layout is 'Flow'
View Mode is Scale to Fill
Answer: You need to set width of collectionview cell programatically. it will be self.view.frame.size.width/2.
Comment: Thank you! i feel so stupid when i read that :3. thanks alot tho!


What does it mean that a Gaussian process is 'infinite dimensional?'

Question: I have glossed over this phrase many times without really understanding what it means. According to Wikipedia - Gaussian process

Gaussian processes can be seen as an infinite-dimensional generalization of multivariate normal distributions

What makes it infinite-dimensional? Just because the kernel function handles an arbitrary number of input dimensions?
Comment: Related: https://stats.stackexchange.com/questions/163983/understanding-gaussian-process-regression-via-infinite-dimensional-basis-functio
Comment: Any continuous time series that can be indexed at a time $t$ is "infinite-dimensional". If you thought of "building" a multivariate normal time series by considering 2 time points, then 3, then 4, then... suddenly you have an $2^{\aleph_0}$ cardinality infinite time series.
Answer: While a sample from a multivariate Gaussian distribution produces a vector with a discrete number of elements, a sample from a Gaussian Process is a continuous function, which is "infinite-dimensional" in the sense that it is "indexed" by a continuously varying coordinate.
I'm not an expert in GPs, but I've found this page helpful.
Answer: Suppose we have $X \sim \mathcal N_n(\mu, \Sigma)$. We can think of $X$ as giving us a random function from $\{1, \dots, n\}$ to $\mathbb R$, which we evaluate by indexing so e.g. $X(1) = X_1$. The space of random functions with this domain is $n$-dimensional since it is spanned by the functions $\{e_1, \dots, e_n\}$ where $e_i(t) = \mathbf 1_{t=i}$ are just the standard basis vectors thought of as functions.
The stochastic process view of this is that we have an index set $T = \{1,\dots, n\}$ and then we have random variables $X_t : \Omega\to\mathbb R$ for each $t \in T$. A single realization of this process yields a sequence $(x_1, \dots, x_n)$ which can be thought of as a particular random function. More formally, if $(\Omega, \mathscr F, P)$ is our probability space, then a single realization of the stochastic process is the function from $T$ to $\mathbb R$ given by $t \mapsto X_t(\omega)$ where $\omega\in\Omega$ is the sample outcome.
If we want random functions with an infinite support (so what we more typically think of as functions, like $f : \mathbb R\to\mathbb R$ with
$f(x)=x^2$) we can get those by using stochastic processes with larger index sets like $T=\mathbb N$ or $T = [0,\infty)$. A single realization of one of these processes gives us a function from $T$ to $\mathbb R$, but now these functions live in an infinite dimension space (typically). In other words, the space of functions that can be realized by this process is an infinite dimension function space, as opposed to $\mathcal N_n(\mu,\Sigma)$ where the space of realizable functions is finite dimensional.
If we further make the requirement that the outputs of our random functions have a multivariate Gaussian distribution for every finite collection of index points, then it turns out that this usefully generalizes the idea of a Gaussian distribution over a finite dimension space to an infinite dimension one.
In summary: a multivariate Gaussian gives us random functions in finite dimension spaces, a Gaussian Process can give us random functions from infinite dimension spaces.
Answer: Infinite dimensional Gaussian processes have sample functions which span an infinite dimensional space (subspace of Hilbert space of mean square integrable functions). Equivalently, the kernel expansion requires an infinite number of terms (Mercer's theorem). It is possible to have Gaussian random processes with countable or even uncountable index sets whose sample functions span a finite dimensional space, equivalently a kernel expansion with a finite number of terms, and hence are not infinite dimensional. So the previous answers are not correct


How to move VBO button to under view

Question: I'm just using Views Bulk Operations for the first time.
VBO augments Views  " ...by showing a checkbox in front of each displayed row, and adding a select box on top of the View containing operations that can be applied."
I have it all working as it should, however, I would like to move this select box and button to UNDER the view (under the table that I am making in my view). I've been looking at this for sometime, and haven't been able to figure out how to do this. Can anyone point me in the right direction? Thanks
Answer: You can modify the form by implementing hook_form_alter() either in a custom module or in template.php in your theme.
Here's a code snippet that brings the table above the other form elements by lowering its weight (source):

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if (strpos($form_id,  'your_vbo_form_id') !== FALSE) {
      $form['output']['#weight'] = -99; //Decrease the weight of output to rise it above other elements.
  }
}

Comment: Thanks.

I have already tried that approach, and found that (unless I am doing something wrong)  it doesn't work. My code was exactly the same as yours, as I got it from the same place.

The results I got were that the button and drop down move down a little, in fact they ended up literally on top of (in front of) the top of the table, obscuring it, and still near the top. Do you have any idea why that might be happening?
Comment: Gotcha. (It helps, by the way, to include methods that you've already tried in your question.) I've just tested it and it works perfectly for me. Is it possibly a CSS issue? In your HTML output (using developer tools or view page source), check to see whether `` occurs after ``.
Comment: This solution worked for me. You might try a `dpm` on `$form_id` to make sure that you got it right. I originally had it formatted like `vbo-form-id` instead of `vbo_form_id`.

How to move VBO button to under view


Finding a set of vectors that spans the solution

Question:
Find a set of vectors {u, v} in $\mathbb{R}^4$ that spans the solution set of the equations:
$x - y + 2z - 2w = 0$
$2x + 2y -z + 3w = 0$
($u$ and $v$ are both $4 \times 1$)
$u = ?$, $v = ?$

I put the matrix in RREF to get
$\begin{bmatrix}1&0&3/4&-1/4\\0&1&-5/4&7/4\end{bmatrix} = \begin{bmatrix}0\\0\end{bmatrix}$
Then I got $x = -\frac{3}{4} z + \frac{1}{4} w$ and $y = \frac{5}{4} z - \frac{7}{4} w$
But I'm not sure how to present the answer as they want it.
Comment: HINT: (Assuming your numbers are correct) you've found that $$\pmatrix{x \\ y \\ z \\ w} = \pmatrix{-\frac 34z+\frac 14w \\ \frac 54z-\frac 74w \\ z \\ w} = z\pmatrix{-\frac 34 \\ \frac 54 \\ 1 \\ 0} + w\pmatrix{\frac 14 \\ -\frac 74 \\ 0 \\1}$$
Answer: You can write the solution set $S$ as follows:
$$S=\{(x,y,z,w)\in\mathbb{R}^4: x=-\frac{3}{4}z+\frac{1}{4}w,\, y=\frac{5}{4}z-\frac{7}{4}w;\,\,\ z,w\in\mathbb{R}\}.$$


Must a complex power series be unbounded within its radius of convergence?

Question: Consider a power series $f(z) = \sum_{n \geq 0} a_n z^n$ with some positive finite radius of convergence $R>0$. It is known that $f$ cannot be extended holomorphically on a larger disk. But is it true that $f$ is unbounded on the open disk $D(0,R)$?
Comment: Counterexample: $\sum_{n=1}^\infty \frac{z^n}{n^2}$.
Answer: No - there are easy examples where the function with even natural boundary a circle is infinitely differentiable (in the real sense, as the boundary is a one-dimensional object) on the boundary. So even in the strongest possible case of inability to extend a holomoprhic function beyond a disk, we still can have a lot of smoothness on the boundary.
Also, note that if a function has a circle as the natural boundary, its integrals (antiderivatives) have it too, so for example for $R=1$ and bounded coefficients ($\sum{z^{2^k}}$) you can integrate it enough times to make it and its derivatives of any finite order absolutely convergent on the closed unit disc - for $C^{\infty}$, it is a bit but not much trickier
Eg $\sum{z^{2^k}}$ is unbounded but obviously $\sum{\frac{z^{2^k+1}}{2^k+1}}$ converges absolutely on the closed unit disc so it is continuous hence bounded there and then we can integrate once more to get $C^1$ on the boundary etc


Domínio. com Website Rstudio

Question: tudo bem?
Vcs poderiam me dar um auxilio? Eu quero garantir um dominio .com para construir meu site com shiny/markdown.
Mas ainda estou estudando shiny/html/css portanto ainda vou produzir meu site.
Nesa situacao como faço para garantir meu dominio .com?
Conheco pouco dessa parte da web.
Poderiam me ajudar?
Answer: Existe alguns serviços na internet para você fazer o seu registro prévio.
Uol host é uma empresa de sp que faz esse registro no Brasil e você consegue gerar um boleto e pagar o seu domínio. Porém nós da Aranha Agency preferimos utilizar o serviço namecheap. (é um otimo servioço para registro, porém você vai precisar de um cartão internacional.)

Registro Br - somante registra dominios [.com.br] ex: meusite.com.br
UolHost - Registro de dominios no Brasil.
Namecheap - Registro de dominios no mundo.

Espero ter ajudado.

Domínio. com Website Rstudio


PyDev doesn't autocomplete variables docstring based

Question: I'm using Eclipse 3.8 with PyDev (latest in update channel). The doctring is generated, but pyDev doesn't use it.
def reporthook(self, count, blockSize, totalSize):
    '''
    Comment Example
    :param count: description of count param
    :type count: int
    :param blockSize: description of blockSize param
    :type blockSize: int
    :param totalSize:description of totalSize param
    :type totalSize:int
    '''
    count. # <-- Here with CTRL + Space dont autocomplete

Answer: PyDev shoud indeed be able to give you code-completion from the docstring information (as shown in http://www.pydev.org/manual_adv_type_hints.html).
Now, not sure why it's not working in your case... (just tried the same case you provided here and it worked without any issues) maybe there was a bug in the version you're using? Have you tried updating PyDev to the newest version (although note that you also have to get a newer version of Eclipse -- the latest PyDev requires Eclipse 4.6).
Answer: Your question is confusing. The docstring you give has nothing to do with autocompletion.
This is two different things.
If you want the documentation of your method to show up, press :
YourClass. # Ctrl+Space

Then clicking reporthook in PyDev will display the whole code of this method (including the docstring).
Otherwise, if you are asking for autocompletion, Python being dynamically typed, PyDev has no reason to show up anything by pressing count. # Ctrl+Space (with the dot), as count (even if it was a class - which is not the case), could not be recognized as such.
By another hand, docstrings are only available at runtime, so PyDev has no reason to use it while editing scripts (excepted if the requested module or feature comes from an already compiled module : for example pressing numpy. # Ctrl+Space would provide the doc for its functions, because it is a module loaded in memory by PyDev at startup).
I suggest that you have a look here.
Or maybe, refreshing the Python Interpreter would help (Windows > Preferences > PyDev > Python Interpreter > Apply > Check the interpreter > Press OK), your script being in the PYTHONPATH...
Hope this is helpful...
Comment: Also, to my experience PyDev works quite better under Linux than Windows. (Don't know anything about OSX).
Comment: i want PyDev autocomple my var by type
Comment: Yes I got that, but I'm not sure this is possible. That's what I attempted to tell... If someone demonstrates the opposite, I'm totally disposed to hear the arguments.


Transformation of Random Variable - Normal Distribution

Question: Let $X$ be one observation from a $N(0,\sigma^2)$ population .  What is the distribution of norm of $X$, i.e., $|X|$ ?
My attempt :
$$f_X(x;0,\sigma^2)=\frac{1}{\sqrt{2\pi \sigma^2}}e^{-\frac{x^2}{2\sigma^2}}; -\infty<x<\infty$$
Then i  have stumbled.
Also, is random variable and observation identical terminology as it is mentioned $X$ be  observation .
Comment: You are along the right lines. You can treat observation and random variable as synonymous in this context. Given that X is symmetric about 0 that might give you a clue about the distribution of |X|
Comment: What does your answer give as the density at $|x|=-1$? what should it be?
Comment: You just have to double the Right branch and nullify the left branch
Answer: Since this is self-study I will give you a hint.
$F_{|X|} = P(|X|<x) = P(-x<X<x) = F_X(x) - F_X(-x)$ where $F$ indicates the CDF of the appropriate random variable. Since we know the CDF of a normal random variable, $X$, we now know the CDF the absolute value of $X$. Differentiating will give us the PDF.
Comment: This answer is good for general normal distribution but is overkill for distribution symmetric about 0. There is a very simple solution in this case.
Comment: Agreed! But I personally find this the easiest solution to understand which makes it valuable for self-study. And the generality of the solution to non symmetric random variables also makes it valuable.
Comment: @tristan Your quibble about TrynnaDoStat's answer would be more creditable if you had posted only "good hints" towards the solution in [your own answer](http://stats.stackexchange.com/a/141598/6633). +1 to him.
Comment: @DilipSarwate I wasn't quibbling with the very good and general answer given by TrynnaDoStat but my feeling was that if I'd set this as a self-study question I'd be expecting students to notice the shortcut on this specific case.
Answer: I will try to give you some good hints towards the simple solution:

The distribution for $Y=|X|$ must be 0 for $Y<0$.
As $X$ is symmetric about 0 we know that $f_X(-x)=f_X(x)$.
$Y$ can take the value $y\ge 0$ if $x=y$ or $x=-y$.

Hopefully that will get you on your way.
Comment: What does Point #3 mean?
Comment: It means that you look at $f_X(-y)$ and $f_X(y)$ to calculate $f_Y(y)$ and from #2 you work out that $f_X(-y)=f_X(y)$ therefore $f_Y(y)=2 f_X(y)$. Sorry that was apparently not the good hint I thought it was.


Como centralizar uma imagem que esta absoluta

Question: Não estou conseguindo centralizar uma imagem que tenha a propriedade position :absolute; tentei utilizar um text-align:center e mesmo assim ano foi porque.
Obs:o resultado tem que funcionar nos navegadores :Google chrome, Mozila, Safari e o Opera

html,
body {
  margin: 0;
  padding: 0;
}
a {
  text-decoration: none;
}
ul li {
  list-style-type: none;
}
.text-center {
  text-align: center !important;
}
.corpo-1 h1 {
  color: #000;
  text-align: center;
  font-family: Gabriola;
  font-size: 2.8em;
  font-weight: bold;
  margin-top: 40%;
}
.corpo-1 p {
  color: #000;
  text-align: center;
  font-family: Gabriola;
  font-size: 1.2em;
  margin-top: -2%;
}
.linha-titulo {
  width: 30%;
  height: 1.9px;
  border: none;
  background: #000;
}
.tamanho {
  -webkit-transform: scale(0.6);
  -o-transform: scale(0.6);
  -ms-transform: scale(0.6);
  -moz-transform: scale(0.6);
  transform: scale(0.6);
}
.info h1 {
  margin-top: -3%;
}
.info p {
  line-height: 10px;
}
.info {
  text-align: center;
  margin-top: 5%;
}
.info li {
  display: inline;
  float: left;
  width: 33%;
  height: 380px;
}
#btn-info {
  border: 3px solid #000;
  border-radius: 5px;
  width: 220px;
  height: 50px;
  text-align: center;
  font-family: Gabriola;
  font-size: 1.5em;
  color: #000;
  background: transparent;
  cursor: pointer;
  clear: both;
  display: block;
  margin: 5% auto 5%;
}
#btn-info:hover {
  background: #000;
  color: #fff;
}
.bg-transparente {
  -webkit-transform: scale(0.8);
  -o-transform: scale(0.8);
  -ms-transform: (0.8);
  -moz-transform: scale(0.8);
  transform: scale(0.8);
  position: absolute;
  margin-top: -10%;
  opacity:0.15;
}

Lorem ipsum dolor adipiscing

            amet dolor consequat

Adipiscing a commodo ante nunc accumsan interdum mi ante adipiscing. A nunc lobortis non nisl amet vis volutpat aclacus nascetur ac non.

Lorem curae eu ante amet sapien in tempus ac. Adipiscing id accumsan adipiscing ipsum.

Lorem Ipsum Dolor

Lorem ipsum dolor sit amet, consectetuer elit.

Vestibulum at purus sed erat suscipit.

Cras facilisis viverra wisi. Class sociosqu...

Lorem Ipsum Dolor

Lorem ipsum dolor sit amet, consectetuer elit.

Vestibulum at purus sed erat suscipit.

Cras facilisis viverra wisi. Class sociosqu...

Lorem Ipsum Dolor

Lorem ipsum dolor sit amet, consectetuer elit.

Vestibulum at purus sed erat suscipit.

Cras facilisis viverra wisi. Class sociosqu...

    <button id="btn-info">leia mais ...</button>

Comment: Coloca o CSS que tens mais um jsFiddle ou outro exemplo pf.
Comment: Irmão, poste o code ai
Comment: Tentou usar flexbox?
Comment: O Tamanho da imagem está fixa?
Comment: ela esta com position absolute e um transform scale (0.8)
Comment: so preciso que fique no centro porque quando dou um text align center nao funciona por causa do absolute
Comment: ok amigo vou posta agora mesmo
Comment: amigo editei o post da uma olhadinha la para vc ver a imagem e claro que nao sao essa peguei da net para facilitar a visualização
Comment: nao conheço isso nao amigo e uma tag ??
Comment: Css: .centro-img  {
    display: flex;
    justify-content: center;
}                                                                                html
Comment: Voce usa ela de background?
Answer: O elemento PAI deve ser Position Relative.
Na imagem que estiver como Position Absolute, você tem que definir as seguintes propriedades CSS;
left:0;
right:0;
margin: auto;


Appended images loaded from file cannot be selected

Question: I am using the following script to load images from a folder and append them to a div:
$(function() {
    var folder = "img/moreprojects/";

    $.ajax({
        url : folder,
        success: function (data) {
            $(data).find("a").attr("href", function (i, val) {
                if( val.match(/\.(jpe?g|png|gif)$/) ) {
                    $("#gallery").append( "

" );
                }
            });
        }
    });
});

However, when I call my next script, which opens a model for the image (which works on images already on the page), the images do not open:
$(function() {
    $('img').on('click', function() {
        $('.enlargeImageModalSource').attr('src', $(this).attr('src'));
        $('#enlargeImageModal').modal('show');
    });
});

How can I have this function, which already works for images in HTML already, work for my dynamically loaded images?
Note: I am using Bootstrap 4 and jQuery.
EDIT
HTML structure (I am using Bootstrap 4):

Welcome to our gallery! Here we showcase all the images from our projects and other work. Use the toggles below, to switch between a list view and a swiping gallery view!

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Comment: Can you post your html structure, and the libraries you are using, to be easier to help you ?
Comment: What exactly are you expecting to be the response of the ajax request, and what response are you getting ?
Comment: The response is working fine, the images display. It is only the on click call that is not working.
Answer: Changing the .on('click', ...) call from:
$('img').on('click', function() {...});
to
$(document).on('click', 'img', function() {...});
fixed the issue for calling a click event on the dynamically loaded images.


Is it legal for a table tennis ball to deflect off a person?

Question: The other day the ping pong ball bounced to person 1's side of the table, bounced off his chest, then surprisingly bounced back on person 2's side of the table. Is that legal play or a foul?
Answer: See this question answered previously. The ball cannot be hit by someone's chest - only their hand (that is holding the paddle) can contact the ball.
Who wins a point where the ball hits a player in the chest would depend on whether or not the ball had already gone over the edge boundary of the table yet or not. If the person was leaning over the table when the ball hit them in the chest - it would be their opponents point. It the ball had already gone past the edge of the table the point would go to the person that got hit in the chest.


String (direct link to modal) gets repeatedly appended to URL

Question: I have some code where the user clicks on an email icon, Outlook opens up, and it contains a link that redirects them to a specific Bootstrap modal.
However, if the user clicks on the re-direct link and then goes through the email icon process again, the url in the email looks like this:
https://website.com/page.aspx/#training-Modal/#training-Modal
It also happens on the page:
The link will still redirect the user properly, but it's confusing to look at.
How can I prevent the modal's hash from being appended repeatedly? I believe the problem lies with the $.each in file.js, but since I'm using it to show every training item I'm wondering if there's something I can edit in index.js to prevent the loop from occurring. Don't know if e.preventDefault or similar would work.

index.js:
// this function is working on the page, but in the email the long url is still happening
function revertToOriginalURL() {
    let original = window.location.href.substr(0, window.location.href.indexOf('/')) // #
    history.replaceState({}, document.title, original);
}

$('.modal').on('hidden.bs.modal', function(e) {
    revertToOriginalURL(e);
});

$(document).ready(function() {
    if(window.location.href.indexOf('#training-Modal') != -1) {
        $('#training-Modal').modal('show');
    } else if(window.location.href.indexOf('#announcements-Modal') != -1){
        $('#announcements-Modal').modal('show');
    }
});

file.js:
       $.each(faqs, (idx, val) => {
         $("#training-content > ul").append(
                "
" +
                    val.Question + "  " +
                    `<a href="mailto:?subject=Dept Training&body=Please review the Dept Training item pertaining to: ${val.Question}%0D%0A${deptUrl}/#training-Modal" target='_top'><i class='far fa-envelope'></i>` + "" +
                    val.Answer +
                "
"
            )
         })

// the code for the #announcements-Modal looks almost exactly the same, except /#announcements-Modal is appended at the end of deptUrl

Answer: Update: I performed a bit of a janky fix, but it's working for me. Simply put, I call revertToOriginalURL(); in the if/else:
$(document).ready(function() {
    if(window.location.href.indexOf('#training-Modal') != -1) {
        $('#training-Modal').modal('show');
        revertToOriginalURL();
    } else if(window.location.href.indexOf('#announcements-Modal') != -1){
        $('#announcements-Modal').modal('show');
        revertToOriginalURL();
    } else {
        console.log('no modal on load')
    }
});

This prevents the modal window hash from being repeatedly appended in the body of the email.


Como repetir um conteúdo em várias páginas estáticas?

Question: A questão é a seguinte, eu tenho apenas arquivos estáticos .HTML e estou procurando uma forma simples de criar os blocos apenas uma vez utilizando apenas o client side.
A idéia é respeitar o DRY, existe alguma forma de fazer isso diretamente com JavaScript ou o jQuery?
Comment: Porque não gravas o codigo.js e o importas nas páginas?
Comment: @Miguel, pode me dar um exemplo simples de como voce importaria?
Comment: , em baixo no html, antes de fechares a tag ``
Answer: Sim, é possível.
Usando o load() jQuery
Exemplo: carregar o conteúdo de header.html para a div com id header.
$("#header").load("public/header.html");

Comment: Vai depender de alguns fatores, possivelmente carregar tudo direto é (minimamente) mais performático, pelo menos em situações normais e também, quase sempre esse ganho de performance é imperceptível. Eu posso te garantir que o ganho em performance em **não utilizar** este tipo de recurso não compensa a perda de tempo e a dor de cabeça que vai ser ter que editar muitos arquivos toda vez que for precisar de uma alteração, ainda mais se o site tiver muitas páginas. Você precisa avaliar uma maneira satisfatória, mesmo que eu soubesse te responder com certeza qual o mais performático, você [+]
Comment: sabe me dizer a questão de performance, se influencia muito?
Comment: [+] vai precisar avaliar o caso diante do seu escopo. (PS: Tou saindo agora. Qualquer dúvida, deixa um comentário aí que quando eu voltar respondo)
Comment: Só complementando, você pode tanto definir o carregamento de páginas inteiras ou apenas um bloco específico, ex: uma div, uma tabela etc. Uma forma de fazer isso: `$("#nome-da-div").load("public/header.html #nome-da-div");`.


Enable a button block programmatically?

Question: How do I enable a button block programmatically?
I've tried:
function openid_connect_block_info() {
  $blocks['openid_connect_login'] = array(
      'info' => t('Login Using PixelPin'),
      'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
      'visibility' => 1,
      'region' => 'content',
      'pages' => 'user',
  );
  return $blocks;
}

Comment: Looks ok. Did you try re-enabling the module that created the block?
Comment: i needed to add `'status' => 1` for it too work
Answer: Setting a block region doesn't work unless you set status to 1, and clearing your cache of course.

Enable a button block programmatically?


Custom C++ allocator far too slow in GCC in debug. is there a fix for this?

Question: I am struggling with the performance of my custom allocator.
My question is regarding a debug build.
normally I don't mind if there is only a bit of a drop. but currently I am playing something in 4fps, while without the custom allocator sits at 60fps ( and can go probably faster) . This makes it harder to develop on the software.
I nailed it down all the way to... basically inheriting the standard allocator
Please see the following results from 'quick-bench.com'
https://quick-bench.com/q/ep3uyYNK6rh_6f8AGAP0zIAflAA
here is a picture:

the blue bar is simply:
int main() {
    std::vector<uint8_t, std::vector<uint8_t>::allocator_type> buffer;
    buffer.reserve(numBytes);
    buffer.resize(numBytes);
    return 0;
}

The yellow bar:
template<typename T>
class CustomAllocatorType : public std::vector<uint8_t>::allocator_type {};

int main() {
    std::vector<uint8_t, CustomAllocatorType<uint8_t>> buffer;
    buffer.reserve(numBytes);
    buffer.resize(numBytes);
    return 0;
}

envelopping the custom allocator with:
#pragma GCC push_options
#pragma GCC optimize ("-O3")
// ....
#pragma GCC pop_options

did not have any effect. I suppose I would need to do this for the vector instance itself, but I don't want to go that far...
Does anyone know a solution for this ?
Comment: It looks like the two code use to produce identical assembly with C++17 but since C++20 additional code is generated for the allocator : https://godbolt.org/z/1P3qTeW46
Comment: If you're allocating memory during every frame, you're probably doing something wrong. It would be preferrable to preallocate as much memory as needed and then reuse this memory.
Comment: @ChrisDodd The question isn't about debug being slower. It's why `std::vector>` is slower than `std::vector` when `CustomAllocatorType` is apparently `std::allocator`.
Comment: @fabian agreed. actually I was planning on using some kind of memory pool inside the allocator. The example here is just demonstration purposes though, to highlight where I am getting stuck.

Thanks so far for the replies. I didn't realize this issue is not in C++17, but I still like to use C++20.
Comment: "*Does anyone know a solution for this ?*" Maybe fall back to `-std=c++17`? https://quick-bench.com/q/LUk0HQxpY4Tqk1dTEU3pzJAxEPM
Comment: It is common for unoptimized g++ to be 10x or 100x slower than optimized code.  You can try using `-Og` to optimize while maintaining debuggability, but that doesn't always work (can be hard sanely debug the result).
Comment: This is **extremely** weird. My thought was that the STL is specializing/overloading some stuff for `std::allocator` to improve performance. This would not necessarily be done for `CustomAllocatorType`. And indeed, there is some stuff that gets optimized specifically. But: I then tried to copy & paste gcc's implementation of `std::allocator` + the specializations/overloads of various stuff, just adapting the name of the allocator to the custom one. In the end, I get **exactly** the same assembly output between the custom allocator and the std one. But the custom one still runs slower. ...
Comment: ... See on [godbolt](https://godbolt.org/z/13osa45eo) (the custom allocator is named `allocator_c`), and [QuickBench](https://quick-bench.com/q/XUPN4Vi5B4-y3IycNb4_DOQyvIM). If you copy & paste the assembly into a text editor and replace `allocator_c` with `allocator`, you see that they are identical.
I have no idea what is going on here. It also does not seem to be a quirk of quick bench, because exchanging the custom and the `std::allocator` exchanges results, too. It also shouldn't be any optimization magic that detects `std::allocator` because optimizations are turned off.
Comment: If I try it locally, I do not get the issue that the assembly code is the same but the performance differs. I have absolutely no idea what is going on on quick bench here.
Comment: Ah, I get it now. It does not work on [quick bench](https://quick-bench.com/q/4DQhSeMGIKyGcrMUaKFCUOmCF_8) because quick bench [force-includes `benchmark/benchmark.h`](https://github.com/FredTingaud/quick-bench-back-end/blob/7430344cc8457767a6952ed5d89acb4e0c73fd37/src/libquick.js#L111) before any of my code, and which in turn [includes ``](https://github.com/google/benchmark/blob/dc901ff9090e2b931433790cc44afc3af3b09ab2/include/benchmark/benchmark.h#L188). godbolt does not do this. Also compare my answer below.
Answer: Reason for the performance decrease
gcc's libstdc++ uses certain performance improvements if the allocator is std::allocator. Your CustomAllocatorType is a different type than std::allocator, meaning that the optimizations are disabled. Note that I am not talking about compiler optimizations but rather that gcc's implementation of the C++ standard library implements overloads or specializations specifically for std::allocator.
To name an example relevant to your example code, std::vector::resize() internally calls __uninitialized_default_n_a() which has a special overload for std::allocator. The special overload bypasses the allocator entirely. If you use CustomAllocatorType, the generic version is used which calls the allocator for every single element. This costs a lot of time. Another function with a special definition and which is relevant to your simple code example is _Destroy().
Put another way, gcc's implementation of the C++ standard library has some measures implemented to ensure that optimal code is generated in cases where it is known that it is safe. This works regardless of compiler optimizations.
If the non-optimized code paths are taken and you enable compiler optimizations (e.g. -O3), the compiler is often able to recognize patterns  in the non-optimal code (such as initializing successive trivial elements) and can optimize everything away so that you end up with the same instructions (more or less).
C++20 vs C++17 and why your CustomAllocatorType is broken
As noted in the comments, the performance decrease when using CustomAllocatorType only occurs in C++20 but not in C++17.
To understand why, note that gcc's std::vector implementation does not use the Allocator from the declaration std::vector<T,Allocator> as allocator, i.e. in your case CustomAllocatorType. Rather, it uses std::allocator_traits<T>::rebind_alloc<T> (see here and here). Also see e.g. this post about rebind for some more information.
Since you did not define a specialization std::allocator_traits<CustomAllocatorType>, it uses the generic one. The standard says:

rebind_alloc<T>: Alloc::rebind<T>::other if present, otherwise Alloc<T, Args> if this Alloc is Alloc

I.e. the generic one attempts to delegate to your allocator, if possible. Now, your allocator CustomAllocatorType inherits from std::allocator. And here comes the important difference between C++17 and C++20: std::allocator::rebind was removed in C++20. Hence:

C++17: CustomAllocatorType::rebind is inherited and thus defined and is std::allocator. Therefore, std::allocator_traits<CustomAllocatorType>::rebind_alloc, meaning that std::vector ends up actually using std::allocator instead of CustomAllocatorType. If you pass in a CustomAllocatorType instance in the std::vector constructor, you end up with splicing.
C++20: CustomAllocatorType::rebind is not defined. Thus, std::allocator_traits<CustomAllocatorType>::rebind_alloc is CustomAllocatorType and std::vector ends up using CustomAllocatorType.

So the C++17 version uses std::allocator and thus enjoys the library based optimizations described above, while the C++20 version does not.
Your code is simply incorrect, or at least the C++17 version. std::vector does not use your allocator at all in C++17. You can also notice that if you attempt to call buffer.get_allocator() in your example, which will fail to compile in C++17 because it will try to convert std::allocator (as used internally) to CustomAllocatorType.
I think the correct way to fix the issue is to define CustomAllocatorType::rebind instead of specializing std::allocator_traits (see here and here), like so:
template<typename T>
class CustomAllocatorType: public std::allocator<T>
{
  template< class U > struct rebind {
    typedef CustomAllocatorType other;
  };
};

Of course, doing so means that the C++17 version will be slow in debug but actually working.
I think this also shows again the general rule that inheriting from C++ standard library types is usually a bad idea. If CustomAllocatorType did not inherit from std::allocator, the problem would not appear in the first place (also, because you'd need to think about how to set the elements correctly).
Improving performance
Assuming the allocator was fixed for C++17 or you use C++20, you get the bad performance in debug because the library implementation uses the generic versions of the above mentioned functions to fill and destroy data. Unfortunately, all of this is an implementation detail of the library, meaning that there is no nice standard way to enforce the generation of good code.
Hacky solution
A hack that works in your trivial example (and probably only there!) would be to define custom overloads of the functions in question, e.g.:
#include <bits/stl_uninitialized.h>
#include <cstdint>
#include <cstdlib>

// Must be defined BEFORE including <vector>!
namespace std{
  template<typename _ForwardIterator, typename _Size, typename _Tp>
  inline _ForwardIterator
  __uninitialized_default_n_a(_ForwardIterator __first, _Size __n, CustomAllocatorType<_Tp>&)
  { return std::__uninitialized_default_n(__first, __n); }

  template<typename _ForwardIterator, typename _Tp>
  _GLIBCXX20_CONSTEXPR inline void
  _Destroy(_ForwardIterator __first, _ForwardIterator __last, CustomAllocatorType<_Tp>&) {
    _Destroy(__first, __last);
  }
}

These here are copy & paste from gcc's std::allocator overloads (here and here), but overloaded for CustomAllocatorType. More special overloads would be required in real applications (e.g. for is_copy_constructible and is_move_constructible or __relocate_a_1, no idea how many more). Defining the above two functions before the include of <vector> leads to decent performance in debug for your minimal example. At least it does so for me locally using gcc 11.2. It does not work on quick bench because quick bench force-includes benchmark/benchmark.h before any of your code, and which in turn includes <vector> (also compare the second bullet point coming next).
This hack is awful on multiple levels:

It is absolutely non-standard. It only works with stdlibc++ and might break at any up- or downgrade of the library version.
You also need to ensure that the overloads are defined before the <vector> header is included, because otherwise they will not be picked up. The reason is that the calls to std::__uninitialized_default_n_a() are qualified, i.e. are std::__uninitialized_default_n_a(arguments) rather  than __uninitialized_default_n_a(arguments), meaning that overloads after the definition of std::vector are not found (cf. e.g. this post or this one). As already explained above, this is the reason why the hack fails on quick bench. Also, if you mess this up in some places, you might violate the one-definition-rule (which will probably lead to more weirdness).
The example hack assumes that allocating and freeing memory does not require the use of CustomAllocatorType, just like std::allocator. I highly doubt that this holds for your true CustomAllocatorType implementation. But maybe you could actually implement e.g. __uninitialized_default_n_a() properly and more efficiently for your CustomAllocatorType by calling an appropriate function on your allocator.

I do not recommend doing this. But depending on the use case, it might be a viable solution.
Enabling -Og
I do get notably better performance with gcc when compiling everything with -Og. It attempts to perform some optimizations without interfering with the debugging experience too much. In your trivial example the performance is improved from 160x slower to 5x slower compared to the std::allocator version. So if you cannot change the compiler, I think that might be the best way to go.
Using clang
Switching to clang (without any optimization flags) seems to improve the performance somewhat. With libstdc++, the custom allocator version is "only" 90x slower.
Surprisingly, with libc++ quick bench reports roughly the same performance. Unfortunately, I cannot reproduce this locally: libc++ is also taking ages. No idea why the result differs locally and on quick bench.
But I can reproduce that clang is optimizing with -Og much better than gcc and gives roughly the same performance with the custom allocator. This holds both with libstdc++ and libc++.
So my suggestion is to use clang, possibly with libc++, and use -Og.
Alternative ideas
Enabling optimizations locally (#pragma GCC optimize ("-O3") etc) is rather unreliable. It did not work for me. The most likely reason is that the optimization flag is not propagated to the instantiation of std::vector because its definition is somewhere else entirely. You'd probably need to compile the C++ standard library headers themselves with optimizations.
Another idea would be to use a different container library. For example, boost has a vector class. But I have not checked if its debug performance would be better.
Comment: It blows my mind on how deep you managed to dive into this. Thank you very much for the details! I'll see if I can maybe just use clang for now. Seems to be the nicest solution in my case
Comment: @FrançoisAndrieux Thank you! To my shame, I have to admit that I was not aware of the problems with the term "STL". I always thought it was synonymous with the C++ standard library, but have never really thought about it. My bad. Also, yes, I meant C++17, not C++20, that was a typo. Moreover, I now also understand why the hack fails on quick bench: Quick bench force-include ``. I have updated my answer accordingly.
Comment: I also added a more viable solution: `-Og` has a great impact, as well has switching to clang. So I think the best solution would be to use clang with `-Og`.


If a sequence is increasing, then the series is always divergent?

Question: I wanted to know if the above statement is true. If not, please provide a counter-example. If true, please provide a proof.
Thanks
Comment: Did you try at all?  lol
Comment: What "series?"  How does the increasing sequence relate to the series?
Comment: You should share your thoughts on the problem.
Answer: Consider
$$a_n=-\frac{1}{2^n}$$ as a counterexample.
Clearly,
$$a_n\lt a_{n+1}$$ for all $n\in \mathbb N$.
Moreover,
$$\sum_{n=1}^{\infty}a_n=-1$$
Answer: If the terms of the sequence are eventually positive, the corresponding series is necessarily divergent. If not, it need not be. You might have $a_n=-2^{-n}$, for instance; clearly the sequence $\langle a_n:n\in\Bbb N\rangle$ is increasing, but the series is just a geometric series with ratio $\frac12$, so
$$\sum_{n\ge 0}-2^{-n}=\frac{-1}{1-\frac12}=-2\;.$$


Is it possible to solve following integral with partial-fraction decomposition?

Question: I have a integral
$$\int_0^1\frac{-x^2+4x+4}{x^2-4}~dx$$
Which I changed to
$$\int_0^1\frac{-x^2+4x+4}{(x-2)(x+2)}~dx$$
But I don't know how to change numerator to have lesser polynom degree than the denominator to use partial-fraction decomposition.
Comment: Start by dividing $x^2-4$ into $-x^2+4x+4$.
Comment: Use long division first
Answer: First divide numerator by denominator, then apply partial fraction decomposition to the resulting fraction from the remainder divided by the denominator (and integrate the quotient part separately).
Answer: The numerator is
$$8-(x-2)^2$$
so the integrand is
$$\begin{align}\frac{8-(x-2)^2}{(x-2)(x+2)} &= \frac{8}{(x-2)(x+2)} - \frac{x-2}{x+2} \\ &= 2 \left (\frac1{x-2} - \frac1{x+2} \right ) - \frac{4}{x+2} +1 \end{align}$$
You should be able to go from here...
Answer: Big Hint:
$$
\begin{align}
\int_0^1\frac{-x^2+4x+4}{x^2-4}\,\mathrm{d}x
&=\int_0^1\left(\frac{4x}{x^2-4}-1\right)\mathrm{d}x\\
&=\int_0^1\left(\frac2{x-2}+\frac2{x+2}-1\right)\mathrm{d}x\\
\end{align}
$$


Create a map of pointers to objects in a list?

Question: In trying to patch memory leaks among other things in a side project I've totally confused myself with pointers and lists and maps and memory, etc.
I want to create a list of objects to use throughout the programs life.  But I also want to use a map to quickly access individual objects from that list through their unique id. I figured I could have a map of pointers to the objects in the list to cut down on memory size.
Is this possible?
I've been working on test code that looks like:
list<cObject> mylist;
map<int, ciEntity*> mymap;

void main(void)
{
    int x = 0;
    class cObject *temp;

    for(x = 0; x < 10; x++)
    {
        temp = new cObject;
        temp->name = new char[25];
        strcpy(temp->name, "Test");
        temp->id=x;
        mylist.push_back(*temp);
        // now what with the map?
        delete temp;
    }

}

I've had other ideas too messing around with the map declaration.  I've tried using an iter to go through the list and then mymap[id]=iter or similar variations.  I've had zero luck getting anything to work.  I know my fundamentals aren't where they should be in regards to working with memory.  Any help is appreciated!
Comment: Please add some more info on the cObject and ciEntity classes to allow a better answer...
Answer: I would alter this a little bit, and use something like a std::shared_ptr<cObject> in both your list and your map.  You can, for the map, use either an int, or possibly a std::string for the key-type, and then for the value-type, use the std::shared_ptr<cObject>
So your code would look more like:
using namespace std;

list<shared_ptr<cObject> > mylist;
map<int, shared_ptr<cObject> > mymap;

void main(void)
{
    int x = 0;

    for(x = 0; x < 10; x++)
    {
        std::shared_ptr<cObject> temp = shared_ptr(new cObject);
        temp->name = new char[25];
        strcpy(temp->name, "Test");
        temp->id=x;
        mylist.push_back(temp);

        // now what with the map?
        mymap[x] = temp;

        //no need to delete temp since it's a managed pointer-type
    }

}

If for some reason your compiler doesn't have std::shared_ptr, you can also get it from boost.
The nice thing with this approach is that your list and map are now pointing to the same object, so if you change the object in the list, the changes will also be reflected in the map.  Also the shared_ptr object will manage the life-time of the pointer through reference counting, so once there are no more references to the pointer, it will call delete on the pointer without you having to worry about cleaning up the pointers from each container (and avoiding ownership issues of the pointers as well).
Comment: Agreed. Any attempt to create a pointer to an object in the list will actually point to the specific item in the vector at that location. If the item changes position in the vector, or if the vector reallocates its internal storage (if it needs to grow after a push_back) the pointer would become invalid. Storing a pointer in both the vector and map is the only option if you don't want to put extra copies in the map.
Comment: I think this might work.  I have some test code with this now and it seems to work the way I need it to, however debugging just got a lot harder in VS2008 when I step through code to see the values :)  thanks!
Answer: You don't need both the list and the map. Maps support iteration in much the same way that lists do, so you can access the values in the map both quickly, via the key, and slowly by iterating. I'm also dubious why you are creating things using new - the array of char should probably be a std::string, and the objects themselves should probably be values.


3/4 eigth notes to 4/4 triplets? How to calculate tempo?

Question: So I have a piece that I'm writing that is mostly in 3/4 with a main melody purely in eighth notes.
I'm trying to implement a time signature change to 4/4, where what was an eighth note melody in 3/4 turns to triplet eighth notes in 4/4 while playing the melody at the same speed... but of course the tempo can't be the SAME.
How do I calculate which tempo I'm changing to?
The first ten seconds of this:

 is kind of what I'm going for. Notice how the time signature changes.
Comment: thanks for the info. I can't reply to you guys, but I'll let you both know that your answers satisfied my question.
Answer:
New Tempo:Old Tempo = New Pivot Value:Old Pivot Value

So what does this mean? The Pivot is the length of the note that you want to remain constant. In your case, you want the eighth notes of the old tempo to be equal to the quarter note triplets in the new tempo. Which means that the old pivot value is 1/2 (half a beat) and the new pivot value is 1/3 (third of a beat). 1/3:1/2 = 1/3*2/1 = 2/3. So if you want to move from the old tempo to the new tempo, you multiply the tempo by 2/3 (for example: old tempo=90, new tempo=60).
This is called a metric modulation (or tempo modulation, or proportional tempi).
Answer: This is straightforward arithmetic, if you can remember what you learned about fractions in elementary school.
If the 3/4 tempo is X quarter notes per minute, you are playing 2X 8th-notes per minute.
If you group those notes in threes, there are 2X/3 groups per minute.
If you write the group as a triplet, that means the tempo is 2X/3 quarter notes per minute.
As an example, if the 3/4 tempo was quarter-note = 72, the 4/4 would be quarter-note = 72x2/3 = 48.
Comment: When you do this kind of arithmetic, the tempo signature doesn't really matter if both the old and the new tempo are `?/4`, right? I mean, even if the time signature of the initial tempo was `2/4` or `4/4` at 72 BPM instead of `3/4`, you would still do `72 * 2/3 = 48`. Correct? Thank you!


Why does the conditional expectation minimize L2 loss?

Question: The claim is that, for a regression task, the conditional regression function $f(x) = \mathbb{E}[\mathbf{Y}|\mathbf{X}=x]$ minimizes the L2 loss $\arg\min(\mathbb{E}[\mathbf{Y} - f(\mathbf{X})]^2)$. I can see why it's true for a normal distribution. But why is it true in general?
Answer: To find $\arg\min(\mathbb{E}[\mathbf{Y} - f(\mathbf{X}|\theta)]^2)$ you get the first order condition
$$\frac \partial {\partial \theta} \mathbb{E}[\mathbf{Y} - f(\mathbf{X}|\theta)]^2=0$$
The differentiation is with respect to the parameters $\theta$ of your model $f(x|\theta)$. Proceed with differentiationg:
$$ \mathbb{E}\left[\frac \partial {\partial \theta}(\mathbf{Y} - f(\mathbf{X}|\theta))^2\right]=
\mathbb{E}\left[-2(\mathbf{Y} - f(\mathbf{X}|\theta))\frac \partial {\partial \theta}f(\mathbf{X}|\theta)\right]=
$$
$$\mathbb{E}\left[(\mathbf{Y} - f(\mathbf{X}|\theta))\right](-2\frac \partial {\partial \theta}f(\mathbf{X}|\theta) )
$$
This holds when the following condition holds:
$$\mathbb{E}\left[(\mathbf{Y} - f(\mathbf{X}|\theta))\right]=0$$
$$\mathbb{E}\left[\mathbf{Y}\right]=  f(\mathbf{X}|\theta)$$
Comment: Why were you able to pull out $-2\frac \partial {\partial \theta}f(\mathbf{X}|\theta)$?
Comment: @Ryker, if you have your function constant for any input data X then it's a trivial solution with all coefficients zero, no?
Comment: Which function is constant, the derivative?


what is best config for php-fpm and nginx with this server?

Question: I have a server with following specs and was wondering what's the best config I can set for nginx and php-fpm?
RAM: 96GB
CPU: 48 Cores
SSD: 200GB
OS: Drupal
Daily users: 52k to 55K
PHP: 7.3
Mysql: 8.0
I have the following nginx config:
server {
    listen 80;
    listen 443 domain.com www.domain.com;
    root /some_directory/;
    index index.php index.html;
    access_log /var/log/nginx/access.log;
    error_log  /var/log/nginx/error.log;
    client_max_body_size 50M;
    /// some CMS confis ///
    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_path_info;
            fastcgi_read_timeout 300;
        }

and use the defailt php-fpm settings but I sure do need to change it since I'm getting
[pool www] seems busy (you may need to increase pm.start_servers, or pm.min/max_spare_servers), error
Comment: Additional DB information request, please.
Post TEXT data on justpaste.it and share the links.
From your SSH login root, Text results of:
A) SELECT COUNT(*) FROM information_schema.tables;
B) SHOW GLOBAL STATUS;    after minimum 24 hours UPTIME
C) SHOW GLOBAL VARIABLES;
D) SHOW FULL PROCESSLIST;
E) STATUS;  not SHOW STATUS, just STATUS;
F) complete www.MySQLTuner.pl (perl) report or similar.
G) SHOW ENGINE INNODB STATUS;
for server workload tuning analysis to provide suggestions.
Comment: AND very helpful OS information, includes -
htop            1st page, if available, TERMINATE,
top -b -n 1  for most active apps,
top -b -n 1 -H  for details on your mysql threads memory and cpu usage,
ulimit -a       for list of limits,
iostat -xm 5 3 for IOPS by device & core/cpu count,
df -h  for Used - Free space by device,
cat /proc/meminfo includes VMallocUused,
for server workload tuning analysis to provide suggestions.
Comment: Could you post current content of php-fpm.conf for analysis?  Your 48 cores should have some influence on limits of pm-min max values used.
Comment: @WilsonHauck here it is: pm.max_children = 530 pm.start_servers = 48 pm.max_spare_servers = 96 pm.max_requests = 500'
Comment: What is the value for pm?  STATIC - ONDEMAND - DYNAMIC?  Would you like performance tuning suggestions for current workload?  If yes, please post requested Additional Information.  Thanks.
Comment: @WilsonHauck the value is set to dynamic. other than those modifications, nothing else is changed
Comment: Since you have only 48 cores, please consider more than PHP-FPM needs to run on your server.  Consider trying pm.max_children =10 (concurrent running processes) pm.start_servers =12  pm_min_spare_servers = 12  pm.max_spare_servers = 12 and keep pm.Max_requests = 500  (queue limit).  This will allow MySQL to breathe for processing active requests.  Any thoughts on workload performance tuning?
Comment: @WilsonHauck when I was using the default values for php-fpm, I'd get 524 error  on my website and in error logs, I had '[pool www] seems busy (you may need to increase pm.start_servers, or pm.min/max_spare_servers)' error. Ever since I changed it, no more down time, but today, I got PDOException: SQLSTATE[HY000] [1040] Too many connections in lock_may_be_available() after few days which is weird! I restarted mysql then the site came back online. I'm not too sure about the values you suggested, because those values gave me error every day
Comment: Please post your entire A) php-fpm configuration and B) entire report from phpinfo request - for analysis. Thanks
Comment: @WilsonHauck Thank you, here are the info you requeste:
A) https://pastebin.com/1VWeYfa4
B) https://mega.nz/file/6FQhgIIA#mgD5JNhQoE-bzrpfoAS2nd7T-Umq27BWvAsisZt4btE
Comment: Could you provide the phpinfo as .txt rather than .png formatted report?
Comment: @WilsonHauck for sure. here it is
https://mega.nz/file/zIAGWD4L#YYhQQLX012b2cgSGjPqS5VqOhjfdbBuHRl5y_hLmYeU
PS: Any ideas why I'm getting the database error? I mean Mysql takes 12GB ram in htop and every day around exact time I get the PDOException: SQLSTATE[HY000] [1040] Too many connections in lock_may_be_available() error. It started to show up after I disabled Memcached (it was messing with my database, so I had ro turn it off) but before that, it was running without a problem. I also saw your answers to another similar problem which is why I'm looking forward for your help. thank you
Comment: Since the 1040 error occurs every day near an exact time, please gather FIVE MINUTES before the expected error, the requested DB additional information  and requested OS additional information as requested a few days ago.  It will be Monday before I have analyzed your PHP info supplied over the past couple days.  My basic perception is your 48 cores CAN NOT support pm.max_children of 530.  Besides your server has multiple apps running besides PHP-FPM, MySQL has to have use of some cores to complete your clients processing requests.  Put a throttle on it, as requested.
Comment: sam oolix, PHP-FPM suggestions will be delayed until you can provide Additional DB info requested Sep 4, 2022 at 12:54  and Additional OS info requested Sep 4, 2022 at 12:56.   Looking forward to assisting with actionable suggestions.
Comment: @WilsonHauck sorry I forgot to post them. Here are the details you asked for:
https://pastebin.com/0ZR4dU6h  innodb
https://pastebin.com/je1VSKUL  status
https://pastebin.com/52VXPyuR  full process list
https://pastebin.com/7jXGdsYp  global variables
https://pastebin.com/EAjPwvs5  select
https://pastebin.com/B2jBuWnK  global status
https://pastebin.com/q37Sa04V Mysql Tuner

PS: I had to restart mysql because of the 1040 error, but I will repost tuner info and global status again after 24 hours
Comment: Sam, See Skype for observations on data posted, please.
Answer: Improvements should be looked in following components in this order:

Drupal optimization / caching options, for example utilizing APCu for data caching
MySQL database optimization / settings
PHP optimization (Opcode cache)

There isn't much point optimizing nginx, since majority of request processing happens in PHP / MySQL.
Also, it is impossible to just give "best config", because the actual configuration depends a lot on several details. Your best bet is the scientific approach: Make changes, measure the improvement. Repeat until performance is in satisfactory level.
Comment: thank you for your reply. I actually have those 3 steps covered (APCu, DB Optimization and OPCache)
Any ideas about the reasonable numbers for php-fpm child and etc settings?
Comment: You should monitor your CPU load, and increase the numbers of PHP-FPM childs as high as possible without making CPU load too high. That doesn't affect performance as such, it only allows more visitors before the limits block them.
Comment: Right now the only thing that uses Most of my CPU is mysql, since drupal stores its cache in database (NOT WISE AT ALL !) and there's nothing much I can do about that. The cache is set to clear by cronjob, and here's what I;ve decided to use: 'pm.max_children = 530
pm.start_servers = 48
pm.max_spare_servers = 96
pm.max_requests = 500'
is it ok for now? PS: I've set memcached memory to 4GB as well
Comment: Change Drupal to cache its data to memcached or APCu. For example, https://hostadvice.com/how-to/how-to-optimize-drupal-8-caching-with-memcached-on-cpanel-hosting/ step 4 tells how to change Drupal to use memcached for its cache.
Comment: thank you very much for your help. I will try to use that method.


Bootstrap to increase robustness of longitudinal models?

Question: I'm evaluating repeated measures longitudinal data with mixed effects lme4::lmer().
Due to all discussion in favor of bootstrapping as a strategy to perform internal validation and reducing bias, I bootstrapped my estimates and confidence intervals with bootMer().
The statistician I'm working with asked why I did that, since variance estimates are easily obtained from the R lmer4 or lmerTest output.
I remember reading that, when dealing with models with lots of parameters, bootstrapping SEs to obtain only parameters of interest is generally more reliable than simply inverting the Hessian matrix at the MLE for ALL parameters.
What do you think? Should I keep bootstrapped estimates or leave them?
Answer: Unlike maximum likelihood estimation for a well-chosen correlation structure, the cluster bootstrap doesn't really "know" about the correlation structure. The cluster bootstrap allows for a fairly general correlation structure (just as the robust cluster sandwich estimator does) but that's not necessarily enough to be optimal.  The sandwich estimator and the cluster bootstrap do not properly handle imbalanced cases either, i.e., cases where some subjects have many more measurements than others.
The bootstrap distribution doesn't always reflect the sampling distribution, and as a result confidence intervals can be inaccurate if you do your simulation correct, i.e., look at the non-coverage separately in the left and right tails.
Overall I don't find a compelling reason to do the bootstrap in this case and would rather spend time getting the correlation structure right.  For example, random effects without anything else assumes compound symmetry, which is unrealistic for serial data.  There are many good choices for serial correlation structures.  Markov modeling is a another very general and flexible way to go.
Comment: A standard Bayesian mixed models make the same assumptions as a frequentist mixed model.  The equal correlation pattern no matter how far apart in time measurements are taken is unlikely to hold true unless you take rapid repeated measurements that are essentially under duplicate experimental conditions.  Look at frquentist and Bayesian Markov models, and if you instead decide to stick with random effects get into the habit of drawing variograms to check the fit of the assumed correlation structure.
Comment: Thanks, prof Harrell! Markov models seem indeed interesting. In my field trials have been adopting repeated measures continuous outcomes, due to unfeasible time needed for conventional binary/state outcomes, and ordinal outcomes aren't really a thing in the field so far as well. In that context, maybe the best modeling option would be Bayesian mixed models?


Javascript Forms Select Selectedindex

Question: Having problems with the following - Not working as expected, getting JS doc errors as well.
JSFiddle Nota Worka.
Answer: try this fiddle: http://jsfiddle.net/maniator/egjF4/6/
and change the if line to:
if (document.forms['myform'].selectbox1.selectedIndex == 2)

you need the == to check values
UPDATE
Based on your comments below here is the jQuery for the same thing:
$(function(){
    $('#selectbox1').change(function(){
        if(this.selectedIndex == 2){
            $('#input1, #input2, #asterisk').css('visibility', 'visible');
            $('#input2').addClass('required');
        }
        else {
            $('input, #asterisk').css('visibility', 'hidden');
            $('#input2').removeClass('required');
        }
    })
})

Comment: Without seeming to ask for a ton, is doing this in Jquery better practice? I'm so unfamiliar with JScript and 5 min ago read that doing all this using Jquery is better for X-browser issues. Is Jquery better than JS? Or some flavor of JS? And if so, is it coded WAY differently.  (this worked perfectly by the way..ur fiddle)
Comment: @adg, #1 accept an answer #2, jQuery is library of js, ill show in a fiddle in a minute
Comment: All of you guys were right, but Neal was kind enough to show me this JQuery stuff. I think I like JQuery better. Is there good reference online to it? Or will I google it and find that billions exist. :) Jeez.
Comment: Fantastic. Ya. Looking at it now. Wowza. I've seen it before but I never put it together. I thought it was some obscure language. -- Yes, I'm "the new guy in town".
Comment: @adg also you can get lots o help on jquery by looking at their forums and on stack
Comment: Ya, this is nice. It's got everything here. Can't thank you enough. Saved me hours. I've been working on this visible/hide thing for 5 days. No kidding. :)
Comment: haha yes, jQuery even has cool animations like `fadeIn` and `fadeOut` in the jQueryUI section, and many more ^_^
Comment: Yessiree. This is very happening. I've been sifting thru all the Jquery stuff for the last 4 hours. Loving it.
Answer: you could also do this, http://jsfiddle.net/edelman/egjF4/10/
var form = document.getElementById('myform');
if (form.selectbox1.selectedIndex == 2)

this way you're caching the form in case you want to reference it later, preventing another element lookup and speeding up your code.
Comment: All of you guys were correct, except that choosing options 1 and 3 would also make the hidden elements appear.
Comment: if you check my fiddle, the elements are hidden when 1 and 3 are selected and shown only when 2 is selected
Comment: Yes, I tried to update my comment. I was looking at another fiddle. Probably my own :) No, yours was perfect :) Thanks so much. --
Answer: I believe jsfiddle runs in it's own little protective XPC bubble, so showhidebtime will not be seen as defined via an inline javascript call. Best practice is to always add events in the javascript file, not inline with the elements.
Also you need to change your form to show name="myform" in order for document.myform to work.
Try this fiddle: http://jsfiddle.net/garreh/qb6fw/
Comment: When you say inline (sorry, I'm, uh, "the new guy"), do you mean calling showhidebtime() within the  html element?
Comment: Also, when I select option 1 or 3 both elements leave the hidden state.
Comment: inline javascript = `javascript:` on elements, just like how you describe "inline" css via ``

Javascript Forms Select Selectedindex


Verificar se todos os objetos da classe que estende RealmObject estão vazios

Question: Minha Book.class que estende realmobject
public class Book extends RealmObject {
    private String title;
    private String author;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }
}

Como faço para descobrir se esses objetos estão vazios?
Eu tentei:
public boolean hasBook() {

    return !realm.allObjects(Book.class).isEmpty();
}

Mas não funcinou.
Answer: Você precisa de uma instância de RealmResults para fazer essa verificação.
Ficaria da seguinte forma:
RealmResults<Book> books = realm.where(Book.class).findAll();
if(books.isEmpty())


What is the meaning of $\mathbb R^+$?

Question: For a function $f$ that maps set $A$ to $B$,

$f\colon\mathbb R^+\to\mathbb R^+$, $f(x) = x^2$ is injective.
$f\colon\mathbb R\to\mathbb R$, $f(x) = x^2$ is not injective since $(- x)^2 = x^2$.

what is the difference between $\mathbb R^+$ and $\mathbb R$?
Additionally, what is the difference between $\mathbb N$ and $\mathbb N^+$?
Answer: $\mathbb R^+$ commonly denotes the set of positive real numbers, that is: $$\mathbb R^+ = \{x\in\mathbb R\mid x>0\}$$
It is also denoted by $\mathbb R^{>0},\mathbb R_+$ and so on.
For $\mathbb N$ and $\mathbb N^+$ the difference is similar, however it may be non-existent if you define $0\notin\mathbb N$. In many set theory books $0$ is a natural number, while in analysis it is often not considered a natural number. Your mileage may vary on $\mathbb N$ vs. $\mathbb N^+$.
Comment: Note that $\mathbb N^+ = \mathbb Z^+$. Also if you want to confuse your readers, you can write the empty set as $\mathbb N^-$, the set of negative natural numbers. :-)
Comment: NB : Depending on the country, $\mathbb R^+$ is also used for the set of non-negative real numbers.
Comment: @Carl: Read the first line, I also say it defines the positive numbers. I just never thought zero is positive... :-) (Also, these French just have to do everything the other way around...! :-))
Comment: @user477343: I don't understand you, and your notation is not consistent. So I'm going to stop replying now. Have a great day!
Comment: @Asaf: as Ranabir says in a separate answer, it makes sense for $\mathbb{R}^+$ to be the set of positive reals. In some countries "positive" includes zero.  Compare Willie Wong's answer to http://math.stackexchange.com/questions/26705/is-zero-positive-or-negative
Comment: Go here $\longrightarrow$ https://math.stackexchange.com/questions/263175/what-does-the-notation-mathbb-r2-mean?rq=1
Comment: It implies for all $\mathbb{R}^n$.
Comment: I see now. I thought it meant that R+ included some extra element. This interpretation makes much more sense.
Comment: @Student: Really? $0\in\mathbb R^+$? Sounds bizarre!
Comment: I was taught that $\mathbb{R}^+$ is the set of positive real numbers greater than $0$ and $\mathbb{R}_+ = \{(x, y)\in\mathbb{R} : x,y\geqslant 0\}$.
Comment: @user477343: I didn't know that the elements of $\Bbb R$ are intervals, or ordered pairs... Since they are not, $\Bbb R_+$ as you defined it would be just $\varnothing$.
Comment: @user477343: If only there was a difference between $\Bbb R$ and $\Bbb R^2$...
Answer: Simply $\mathbb R$ means the set of real numbers.
$\mathbb R^+$ means the set of positive real numbers.
And $\mathbb R^-$ means the set of negative real numbers.

What is the meaning of $\mathbb R^+$?


Block all requests except certain header

Question: I'm using CloudFlare in a shared environment and I'm trying to help block non-CloudFlare users who circumvent to my origin IP.  Loading up the web page I see the header server: "cloudflare". So I tried the following htaccess code and I get a 403 right away.
RewriteCond %{HTTP:server-header} !^cloudflare$ [NC]
RewriteRule ^ - [F]

RewriteCond %{HTTP:x-server-header} !^cloudflare$ [NC]
RewriteRule ^ - [F]

I've also tried variances of the code and nothing works.
Comment: What _exactly_ is the name of the header you are seeing? And where are you seeing this? In the browser response?
Answer: Blocking requests based on the existence of this specific header is a bad idea.
The reason is that anyone can spoof that header if they wanted. This could be filed under security by obscurity and it is not even that obscure.
A better approach would be to only allow requests made from CloudFlare IP addresses.
A list of CloudFlare IP addresses can be found here: https://www.cloudflare.com/ips/
An example for IPv4 only would be:
order deny,allow
deny from all
allow from 18.104.22.168/20
allow from 126.96.36.199/22
allow from 18.104.22.168/22
allow from 220.127.116.11/22
allow from 126.96.36.199/18
allow from 18.104.22.168/18
allow from 188.8.131.52/20
allow from 184.108.40.206/20
allow from 184.108.40.206/22
allow from 18.104.22.168/17
allow from 18.104.22.168/15
allow from 22.214.171.124/12
allow from 22.214.171.124/13
allow from 188.8.131.52/22

Answer: I just found two solutions.
One is to use:
RewriteEngine On
RewriteCond %{HTTP:CF-IPCountry} ^$
RewriteRule ^ - [F,L]

The other is here:
https://community.cloudflare.com/t/stop-cloudflare-bypassing-on-shared-hosting/91203
Comment: curl --header 'Host: CF-IPCountry: US' --resolve 'example.com:80:direct-server-ip' http://example.com

Replace the example.com with your domain and the direct-server-ip to your external server IP and eventually the port 80 to 443 for HTTPS. This request would bypass that .htaccess rule.


How to decompose the following $L_2$ norm?

Question: Suppose we have $X\in \mathbb{R}^{n\times p}$, $C\in \mathbb{R}^{n\times n}$ and $\Delta\in \mathbb{R}^p$, and we have the following $\ell_2$ norm:
\begin{equation}
\lVert CX\Delta\rVert_2
\end{equation}
Suppose I wish to separate the $C$ from the rest. The following is incorrect, but something similar to the submultiplicative condition:
\begin{equation}
\lVert CX\Delta\rVert_2\leq \lVert C\rVert_2\lVert X\Delta \rVert_2
\end{equation}
How would this be possible (if possible at all)? Submultiplicative condition of matrix norms does not apply here, nor do I think Holder's inequality is the correct approach.
Answer: You don't need submultiplicativity to conclude that
$$ \lVert CX\Delta\rVert_2\leq \lVert C\rVert_2\lVert X\Delta \rVert_2.$$
Recall the definition of a matrix norm induced by a vector norm, $A \in \mathbb{R}^{n\times p}$
$$ \|A\| = \sup_{\|x\|_\beta =1} \frac{\|Ax\|_\alpha}{\|x\|_\beta}$$
where $\|\cdot\|_\alpha$ and $\|\cdot\|_\beta$ do not have to be the same norm nor even be defined on the same vector space. This means that $\|A\|$ is the smallest constant such that $\|Ax\| \leq \|A\|\|x\|$ for any $x$. As $X\Delta$ is a vector in $\mathbb{R}^n$,
$$\left\|CX\Delta\right\|_2 \leq \left\|C\right\|_2 \left\|X\Delta\right\|_2 $$
Also, I do not see why submultiplicativity of matrix norms does not hold here. It is not necessary for to separate out $\|C\|$ however.