Como acessar os índices de um vetor muito grande em C?

Question: Estou com um problema que tenho que montar um vetor (vet2[50]) com a soma de um vetor grande (vet1[100]), esse vetor vet1 é fornecido pelo usuário e a soma se da por:
vet2[0]=vet1[0]+vet1[1]

vet2[1]=vet1[2]+vet1[3]
.
.
.
vet2[49]=vet1[98]+vet1[99]

Não consigo estabelecer uma lógica para fazer essa soma, se os vetores fossem menores daria pra fazer manual (método acima), mas como são grandes estou meio perdida.
Comment: Esse vetor é minúsculo. Precisaria de mais informações. Seria bom colocar seu código na pergunta e dizer onde está tendo problema. Mas qualquer tamanho não faz sentido fazer um por um.
Answer: Precisa fazer um laço e variar o índice pela variável do laço.
Eu fiz um exemplo com 6 números, mas é só mudar para 100 na segunda linha. Não coloque um valor ímpar que vai dar problema.
Iniciei os vetores zerando eles, fiz um laço para ler todos itens, depois fiz o laço da soma e finalmente o laço mostrando o resultado.
No laço de soma criei cada elemento do segundo vetor somando os elementos equivalentes de acordo com a fórmula aparentemente pedida na pergunta (não é fácil fazer algo sem uma definição de fórmula, mas estou confiante que é isso que deseja).
Para um exercício acho que está bom assim.
#include <stdio.h>
#define MAX 6

int main(void) {
    int vet1[MAX];
    int vet2[MAX / 2];
    for (int i = 0; i < MAX; i++) scanf("%d", &vet1[i]);
    for (int i = 0; i < MAX / 2; i++) vet2[i] = vet1[i * 2] + vet1[i * 2 + 1];
    for (int i = 0; i < MAX / 2; i++) printf("%d\n", vet2[i]);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


How to determine a file in command line is a string and whether it exists or not

Question: I wanna get a file from command line and open it. If the filename is not a string, it will print('Wrong type') and if the file can't be accessed or doesn't exist it will give an error with content 'Cannot find filename'. I wonder how can I do this. Is this code below right?
import sys
filename=sys.argv[1]

if type(filename) is str:
    pass
else:
    raise Exception('wrong type')
try:
    open(filename,'r')
except FileNotFoundError:
    raise FileNotFoundError('Cannot find filename')

Comment: What particular problem do you have with it?
Comment: sys.argv values will always be strings. What, I think, you want here is to either match the parameter to a file format {name}.{estension} or to `try` opening the file and `except` the `FileNotFound` exception
Comment: This really belongs over at [Code Review](https://codereview.stackexchange.com/).
Comment: @SimasJoneliunas Exactly. Is my code right?
Comment: logically, I believe that the `type(filename) is str` will always default to `true`, so you i would replace that part with `sys.argv.__len__() >= 2`. its also worth to check if `sys.argv[1].__len__() > 0`.  But overall, i believe that your code does what you want it to do.
Comment: @SimasJoneliunas OK, thank u bro
Answer: Agree with posting this on Code Review tho, but still can simplify it:
import sys
filename=sys.argv[1]

if not isinstance(filename,str):
    raise Exception('wrong type')
try:
    open(filename,'r')
except FileNotFoundError:
    raise FileNotFoundError('Cannot find filename')

Simplifying if/else into a if, and more efficient is isinstance, instead of type(..) == ..
Btw sys.argv[1] is always a string so no need for if statement:
import sys
filename=sys.argv[1]

try:
    open(filename,'r')
except FileNotFoundError:
    raise FileNotFoundError('Cannot find filename')

Btw, os.path.exists:
if not os.path.exists(filename):
    raise FileNotFoundError

Comment: This is pointless, there is no way for `sys.argv` to ever contain something which isn't a string.
Comment: @AnYan Happy that i helped,
Comment: @tripleee It's at the bottom of the post, but i still will edit
Comment: @AnYan No need for `if`, `sys.argv` values are always strings
Comment: @U9-Forward yeah obviously...and I know that. But this is a question from a quiz.


How do I know what ports are on my Macbook?

Question: I'm trying to go through this particular code example from "The Well Grounded Rubyist" regarding TCPServer and threads. The code is below:
require 'socket'
server = TCPServer.new(3939)
connect = server.accept
connect.puts "Hi. Here's the date."
connect.puts 'date'
connect.close
server.close

How do I know what port is on my Macbook? The docs has 2000 in the example. However, when I try both of these numbers the code doesn't execute, it continues to hang indefinitely.
How can I check if these numbers are verified ports? I tried telnetting to the port number and the connection is refused everytime.
Comment: The reason this hangs is because it is waiting for connection. Your mac, as every other machine, do have port 3939.
Comment: Wikpedia's "[List of TCP and UDP port numbers](http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers)" might be good for you to read.
Answer: server.accepts waits for a client to connect to the server. If that does not happen, it just keeps waiting. Run the code, then open terminal and type:
require 'socket'

s = TCPSocket.new 'localhost', 3939

At this point you will create TCPSocket, which will connect with your server. This will cause  the rest of the code to execute. You can check it with your socket:
while line = s.gets # Read lines from socket
  puts line         # and print them
end

Comment: Thanks for the quick reply BroiSatse. This did the trick. One last thing, can I insert any number onto the TCP.new constructor?
Comment: Ports below 1024 are usually reserved for some services, like 80 is reserved for html, 443 for https and 22 for ssh to name just a few. In practice network ports are just a numbers (16-bit numbers) and there are no hardware sitting behind those (unlike computer ports).


Alguém pode me explicar um parte desse codigo?

Question: O código em questão é o de baixo, boa parte dele eu estou entendendo mais o loop for me confundiu, ele recebe a sequencia da variável, mas no print, ele informa exatamente a sequencia que o usuário digitou, como ele sabe qual é a "letra" na variável index ?
<code>def jogar():
    print("******************************")
    print("**BEM VINDO AO JOGO DA FORCA**")
    print("******************************")

palavra_secreta = "brasil"

while True:
    chute = input("Qual a letra? ")
    chute = chute.strip()
    index = 0
    for i in palavra_secreta:
        if(chute.upper() == i.upper()):
            print("Encontrada sua letra {} na posição {}".format(chute.upper(), index))
        index = index + 1

 if(__name__ == "__main__"):
     jogar()
</code>
Comment: Uma string é um iterator, podes ver isso como uma string é um array/list: https://repl.it/repls/TruthfulBusyFanworms
Answer: Na parte do for ele percorre com "i" cada letra da palavra secreta no caso "brasil" sendo assim em cada volta que o for da ele vai seguir a sequencia "b" depois "r" depois "a" e assim por diante.
Exemplo:
minha letra digitada: "s"
posição -> [index]
posição 0 do for [0] letra "b"  posição 1 do for [1] letra "r"  posição 2 do for [2] letra "a"  posição 3 do for [3] letra "s" -->Encontrada minha letra "s" na posição 4 index 3  posição 4 do for [4] letra "i" posição 5 do for [5] letra "l"
no caso o "i" faz o papel de ir pegando cada letra uma por uma,
depois no if ele compara se a letra digitada é igual a alguma letra da palavra secreta, se no caso o cara digitou a letra "r" quando o for rodar cada letra da palavra secreta irá encontrar essa letra, no print ele mostra a letra encontrada e o index dela que vai pegar a posição do for
Comment: Ok, obrigado, estava pensando na mesma coisa tentando entender, mas não conseguia juntar os pensamentos, valeu pela explicação


Hecke Bound for Cusp - Modular Forms

Question:
The problem statement, all variables and given/known data

i have a  questions on the piece of lecture notes attached:

Relevant equations
The attempt at a solution

I agree 2) of proposition 2.12 holds once we have 1). I thought I understood the general idea of 1), however, my reasoning would hold for $M_k$ it does not depend on $f(t)$ being a cusp and so it must be wrong. This was what I thought was happening:
$q=e^{2\pi i n (u+iv)} \approx e^{-v} $ for large v, and exponential dominates over $v ^ {x}$ ( v>0 as on upper plane )
This would ofc still hold if I included some constant term, I would still get the same quantity is bounded.
can someone please tel me where I have gone wrong with the above reasoning?
Answer: I don't think that the reasoning would apply to a form with a constant term.
If $f$ is cusp, we can write $|f(q)|=e^{-2\pi m v}|g(q)|$, where $0<|g(0)|<\infty$ and $m>0$. Then $v^{k/2}|f(q)|= v^{k/2} e^{-2\pi m v}|g(q)|$. Clearly the product $v^{k/2}e^{-2\pi m v}$ has zero limit at infinity, and since $|g(0)|$ is not infinity, we get that the limit of $v^{k/2}|f(q)|$ at infinity is zero.
If, on the other hand, $f$ is not a cusp form, then $|f(0)|>0$ and so the limit of $v^{k/2}|f(q)|$ at $v=\infty$ will not be dominated by anything going to zero, and so you get an infinite limit, hence $Im(z)^{k/2}f(z)$ would be unbounded on the fundamental domain.
Comment: this sure makes sense, thank you. sorry i think i got tired by that time, it was late evening :P
Answer: It may be handy to have a particular non-cuspidal modular form in mind for examples like this. The prototypical non-cuspidal modular form is the Eisenstein series of weight $2k$
$$ E(\tau) = \sum_{m,n \in \mathbb{Z}^2 - \{(0,0)\}} \frac{1}{(m+n\tau)^{2k}},$$
whose Fourier expansion is
$$ E(\tau) = 2\zeta(2k)\left(1 + c_{2k} \sum_{n \geq 1} \sigma_{2k-1}(n) q^n\right).$$
This expansion looks like a constant term $1$ and a lot of terms with exponential decay in the imaginary part, coming from $q^n$. Your reasoning applies to the exponential decay portion: all terms with exponentials vanish as the imaginary part goes to $\infty$.
But the constant term doesn't, and $\mathrm{Im}(\tau)^k \cdot 2 \zeta(2k)$ clearly goes to $\infty$ as the imaginary part goes to $\infty$.

Hecke Bound for Cusp - Modular Forms


Estimation of school effects using xtmixed (in Stata 12)

Question: I am trying to estimate school effects on student scores. I ran a model with student effects as a random effect and school effects as fixed effects as follows:
xtreg studentscore lagstudentscore limitedEng poor `gradeyeardum' `schoolyeardum', re

where student score is regressed on lag of student score, student's language proficiency and poverty status, and a set of grade-year dummy variables and a set of school-year dummy variables. The coefficients on the school-year dummy variables are the key fixed effects of interest.
I want to estimate an equivalent model using xtmixed. I ran the code below but the MLE doesn't seem to converge - I got the "not concave" message for several iterations. Here's the code I ran:
xtmixed studentscore lagstudentscore limitedEng poor `gradeyeardum' schoolyeardum', || schnamyearid : || studentid:

I am not sure if I should estimate both the individual level and school level standard deviations for the variance component. I am interested in the school level variation, so perhaps the following model makes more sense?
xtmixed studentscore lagstudentscore limitedEng poor `gradeyeardum' schoolyeardum', || schnamyearid :

Answer: If prior to running the xtreg command you have xtset the data with the student as the panel, then your xtreg model is assuming random student effects but fixed effects for everything else. To fit the corresponding model using xtmixed (or mixed, as it's called in Stata 13), you just swap xtmixed for xtreg, and put the variable which was your panel variable (studentid?) as a random effect:
xtmixed studentscore lagstudentscore limitedEng poor gradeyeardum'schoolyeardum' || studentid:

If you model schools' effects as fixed effect, you will get a coefficient estimate for the effect of each school (relative to some baseline school) on the students' scores. If you have lots of schools, and you are interested in the effects' of schools on students scores (or rather how much scores cluster by school), and you're not particularly interested in estimating the differences between particular schools, then it may well be better to model school as a random effect, using something like:
xtmixed studentscore lagstudentscore limitedEng poor gradeyeardum'schoolyeardum' || schooldid: || studentid:

Comment: Thanks for the comment Jonathan. I actually tried running both models. The first one yields estimates of school effects so that is great. When I run the second model, I get a message, "numerical derivatives are approximate - nearby values are missing", by the log likelihood it reads "not concave". I am not too worried as I get the estimates from the first model. However, I do have a followup question. I am new to the Hierarchical Linear Models. Here's my follow-up question - I apologize in advance if it's too rudimentary. Please find the question below:
Comment: How can I account for the autocorrelation and heteroskedasticity at the first level or student level? In other words, I have repeat observations for each student (over several years), so the student level errors are going to be certainly autocorrelated and potentially hetoroskedastic. I should probably modify the above code don't I? Or, does the above command address both of these issues? Please let me know. Thanks.
Comment: The second model allows for correlation between the measurements from the same student, by virtue of having a student random-effect. But it assumes a very simplistic correlation structure - that the correlation between any two measurements on the same student is the same, irrespective of which years they took place in. If the measurements are taken at a small number of distinct time points, e.g. year 1 - year t, you could allow for the correlation in a less restrictive manor, by removing the student random effect but modelling the residual errors using an unstructured covariance matrix...
Comment: The syntax for this would be: xtmixed studentscore lagstudentscore limitedEng poor gradeyeardum'schoolyeardum' || schooldid: || studentid:, nocons resid(unstructured, t(year)) where year is the variable indicating the year of measurement. You will then get a variance for the school random effect and an estimate of the variances and covariances (or correlations) for the residual errors.
Comment: If I use the second model, I won't get the get a coefficient estimate for the effect of each school (which is what I want). Also, doesn't the first model also have student random-effect (which accounts for year-to-year correlation for students)?
Comment: Ok, if you want to estimate the school effects then you can either put the school dummies in as fixed effects, or if put school as a random effect you can predict the school level random effects (see the help for predict after xtmixed). Having a student level random-effect accounts for correlation between measurements from the same student, but in a fairly simple way which ignores the timing of the measurement. The model I suggested in my last comment uses the timing of the measurement to let the correlation between residuals differ between measurements at different times.
Comment: One final question - why can't I use: xtmixed studentscore lagstudentscore limitedEng poor gradeyeardum'schoolyeardum' || studentid:, nocons resid(unstructured, t(year)) ? - this should yield school fixed effects and also solve the problem of autocorrelation right?
Comment: Yes, that sounds fine to me.
Comment: Hi Jonathan, can you let me know how I can get the Empirical Bayes (shrunk) estimates of the school fixed effects?
Comment: If its a fixed effect you get estimates of the coefficients. You can only get an EB estimate of a random effect.
Comment: I get that now - after reading a few papers I conceptualized the idea of EB estimates quite well. Now I understand why you were emphasizing modeling school effects as random effects in the earlier posts. I now want to model school effects as random effects and also account for the correlation of errors within individual students, and when I run the model you suggested - the model doesn't seem to converge - it is still running actually. I read somewhere that I might be getting ("backed up") message possibly due to the fact that "variance component estimates is perilously close to zero" (cont..)
Comment: which seems to be true when I run a model with student effects as random effects. When I try to specify only school effects as random effects and specify residuals as above - resid(unstructured, t(year)) I get an error - "repeated time values within lowest-level panels". Does this mean that I am specifying residual at the school level and not student level? Please help.
Comment: So, to be clear, can I just specify school effects as random effects and not have "||studentid:" part in the syntax, but still account for the within student correlation in errors due to repeat observation on students across years?
Comment: When I pass the syntax "xtmixed studentscore lagstudentscore limitedEng poor gradeyeardum' || schooldid:", the model converges, but this model does not account for the correlation between errors overtime due to repeat observations on students right? I think you know this, but just to remind you, the structure of my model is Yijk, i.e. outcome for student j in school i in year k.


Quick way to bind data from data transfer object to DAL object?

Question: I have multiple data transfer objects that need their data transferred over to their DAL equivalent models.
Is there a generic binding function or class that I can use in C# to do so? I have searched but to no avail. At the moment I am manually creating the new DAL objects and setting the equivalent properties from the DTO data. Very time consuming, especially as my domain grows.
Thanks, any help/tips would be ace.
Comment: I'm not sure if it helps, but AutoMapper [http://automapper.codeplex.com/] comes into my mind while reading your post. Is it something for you?
Answer: I strongly recommend Automapper :)
It's a .net tool you can use to easily map between objects; you can add custom rules if the properties of your objects have different names, or if you need some special processing, but for simple objects it works out of the box!


PyCharm moves caret after line commenting

Question: I use PyCharm as Python IDE editor.
When I push default keyboard shortcut ctrl+slash to comment a line - caret (keyboard cursor) is moved to the next line (if text is not selected).
There is a way to make caret stay on the same line?
Comment: @Mr. Che, did you end up figuring this out?
Comment: @Viragos No, unfortunately.
Comment: What's the purpose??
Comment: @R.A.Munna To stay on the same line. ;)
Comment: @Dr_Zaszuś In PyCharm 2019.3.2 (Community Edition) `ctrl+slash` cursor stay on the same line. :) Thank you
Answer:
In case you always want the action to keep caret on the same line, there's an option in 'Advanced Settings' - 'Move caret down after Comment with Line Comment action'.

https://youtrack.jetbrains.com/issue/IDEA-283756/Line-comment-shortcut-without-jumping-to-new-line
Comment: The dragon was defeated after six years.
Answer: try for making caret stay in same line at very beginning of the line
shift + #

Answer: As of 2020, apparently there is still no way to disable this behaviour according to
this jetbrains support entry.
There is a workaround described:

1) Start with Edit | Macros | Start Macro Recording
2) Press "Ctrl" + "/" to comment out current line
3) Press "Up" to move caret to that line again
4) End with Edit | Macros | Stop Macro Recording

But if you apply this, selecting multiple lines to comment them out/in behaves different.  There are two tickets in the Issue tracker for this, but it doesn't seem to be worked on.
Highlighting a piece of text on the line and then doing the comment shortcut is the closest non-breaking fix I could find...


Hyper-V Integration Services

Question: Let's just focus on Hyper-V on either 2008 R2 SP1, or Hyper-V on Server 2012. The guests are all modern versions of Windows themselves, either Windows 7 or 8, or 2008 R2 or Server 2012.
Do I really need to install the Hyper-V Integration Services on my guests? Everything seems to work just fine without them. And I understand why they may be necessary on older versions of Windows or of course non-Windows OSes...
I read a bit about what the Integration Services are for, but I could not find any information that was specific enough to convince me that I need to worry about installing them on Win7,Win8,2008R2,etc., guest OSes.
Answer: It "works fine" but the performance is going to be much poorer than if you installed Integration Services. This is because it provides paravirtualized drivers for performance-critical virtual disks, network adapter, etc.
Answer: If the guest is the same version of Windows as the Hyper-V installation, the integration services are built in.  If they're close to the same version, then you'll have some version built in, and they'll negotiate down to the lowest common denominator protocol, which may mean that you leave some performance on the table.
Comment: I think this is closer to the answer I was looking for. I noticed that my Win7/Win8/2012/etc virtualized guests seemed to already have this built in. i.e., when trying to install the Integration Services it would tell you that you already have it installed. I'm thinking it must already be a part of Windows Update if the guest OS detects that it is a virtual machine...
Comment: No, there's no special magic around Windows Update.  The integration components are either present when the OS is installed (however inactive) and then activated when the OS is virtualized within Hyper-V or they're delivered on the "Integration Services Setup" CD image.  They may be updated by Windows Update once installed, though.

Hyper-V Integration Services


there is any relation between $\pi$, $\sqrt{2}$ or a generic polygon?

Question: I'm a programmer, I'm always looking for new formulas and new way of computing things, to satisfy my curiosity I would like to know if there are any formulas, or I should say equalities, that make use of both $\pi$ and $\sqrt{2}$ .
I would also like to know if it's possible to generalize this relatively to any n-sided polygon ( even a 3D figure ), $\sqrt{2}$ that usually appears in quadrilaterals only.
Of course I would like to know about any possible domain, but since we should start from something, I would say that the domain of polygons and polyhedron triggers my interest in the first place.
Comment: [This](http://math.stackexchange.com/questions/85217/why-is-this-series-of-square-root-of-twos-equal-pi) seems relevant.
Comment: Apparently Plato thought that $\pi=\sqrt{2}+\sqrt{3}$, exactly. In fact $\sqrt{2}+\sqrt{3}$ approximates $\pi$ to within two-thousandths of a percent, which is not bad.
Comment: @user2485710 It's based on simple mensuration formulas for plane shapes. The area of a unit circle is $\pi$. An inscribed octagon inside the circle will have area $2\sqrt{2}$. A circumscribed hexagon around the circle will have area $2\sqrt{3}$. The average of the areas of the hexagon and octagon is then $\sqrt{2}+\sqrt{3}$.
Comment: @user2485710 For regular polygons, yes. [See the wiki](http://en.wikipedia.org/wiki/Regular_polygon#Area).
Comment: @DavidMitra it's basically the top rated answer at the moment, if I'm not mistaking, nice to read a longer explanation.
Comment: @DavidH it this linked to some study in geometry ?
Comment: @DavidH so there is a generic formula to plot the perimeter, or the vertices or the area of an N-sided polygon using trigonometry ?
Comment: Also see https://math.stackexchange.com/questions/85217/why-is-this-series-of-square-root-of-twos-equal-pi?lq=1
Answer: $$
\pi = 2\sqrt 2 \cdot \frac{2}{\sqrt{2+\sqrt2}} \cdot \frac{2}{\sqrt{2+\sqrt{2+\sqrt2}}} \cdots.
$$
Comment: let me guess, it's some kind of approximation of $\pi$ related to some polygon ?
Answer: Pretty trivial, but for the sake of completeness:
$$\sin\frac\pi4=\cos\frac\pi4=\frac1{\sqrt2}$$
Here I'd say the $\frac\pi4$ relates to a regular octagon, or the canonical eighth root of unity, so yes, it generalizes to other regular $n$-gons, resulting in other algebraic numbers for the sine and cosine of the corresponding angles resp. the real and imaginary part of the corresponding root of unity.
If you want to go 3D, you'd probably start using Euler angles and quaternions, but I'll not go into this.
Answer: Stirling's approximation:
$$
n! \sim \sqrt{2 \pi n}\left(\frac{n}{e}\right)^n
$$
Comment: there are other uses beside the approximation of a factorial for this ?
Answer: I had fun doing that back in the days; lots of paper and the smallest mistake would end in chaos. I felt I had discovered something in the end :)
(Note: bug in the code snippet: k=3 is skipped; the line "if k>3 then" should be "if k>2 then".)

I was $17$ years old when I took on that task, alone at home with a lot of scratch paper. I remember the wow effect when the pattern emerged. It was about expressing PI in function of the square root of $2$. Focus recommended!
In the last $35$ years, I mentioned it $3$ or $4$ times and it never raised much interest, probably because expressing an irrational number in function of another no more rational one does not make sense :).
In iteration $3$, the function starts to look like the precedent one; then it's obvious between $3$ and $5$ and it goes on, making it easy to program. It will get closer to PI before breaking due to the variable's limitations. Here a code snippet (too) quickly put together for demo purposes.

Original post: https://www.facebook.com/yazel.boudour/posts/353578401680948
Answer: $$t_n=\bigg(-\dfrac14\bigg)^n\cdot\dfrac{\displaystyle{2n\choose n}}{1-2n}\qquad=>\qquad\sum_{n=0}^\infty t_n=\sqrt2~,\qquad\qquad\sum_{n=0}^\infty t_n^2=\dfrac4\pi$$

This is based on the fact that $~\displaystyle\sum_{n=0}^N{N\choose n}=2^N,~$ and $\quad\displaystyle\sum_{n=0}^N{N\choose n}^2={2N\choose N}.~$ Now let $N=\dfrac12$
and use the fact that $\Big(\tfrac12\Big)!=\dfrac{\sqrt\pi}2$ . See binomial series, Vandermonde's identity, and $\Gamma$ function
for more details.
Comment: @user2485710: None that I'm aware of. Why? Are you only interested in formulas that have practical applications? If so, then please specify that explicitly in the body of the post, by mentioning exactly what kind of applications you have in mind.
Comment: and this is optimal for what kind of applications ?
Comment: since I was mentioning geometry, polyhedron and polygons I was assuming that this had something to do with it. Anyway since there is a $\sum_{n=0}^\infty$ equal to $\sqrt{2}$ maybe this can be used to approximate some computations .
Comment: Since the two constants you mention are connected to two basic geometric shapes (the unit square and the unit circle), then all formulas about them are connected to the latter as well. But not all connections are necessarily practical. Euler's and de Moivre's formulas are quite helpful in plotting regular polygons or stars, for instance, since they give the coordinates of their vertices. As far as computations are concerned, all processors know how to extract a square root, and all programming languages know the value of $\pi$, so I doubt there's any practical application there.
Answer: You can use the Taylor series of $\sin(x)$ to calculate square roots using $\pi$.
For example, you can calculate the square root of 2 as follows:
$$\sin{(45^\circ)}=\sin{(\frac\pi4)}=\frac{\sqrt2}{2}$$
Therefore:
$$\sqrt2=2\cdot\sum_{x=1}^n \frac{(\frac{\pi}{4})^{4x-3}}{(4x-3)!}-\frac{(\frac{\pi}{4})^{4x-1}}{(4x-1)!}$$
I haven't tried personally,  but I imagine you could relate a lot of square roots back to $\pi$ like this. Simply find the angle, in radians of a triangle with a side length of $\sqrt x$ and then expand by expressing the angle in terms of $\pi$ using the Taylor series.
Answer: $$\exp(i (\sqrt{2})^2 \pi)=1$$
Comment: and this wonderful thing is ... ? :D
Comment: not 100% sure if that counts, as you are using 2 (${\sqrt{2}}^2$), instead of $\sqrt{2}$
Comment: Its $ e^{2\pi\cdot i} $ xD
Comment: @user2485710 This is the most beautiful formula in all mathematics, [Euler's Identity](http://en.wikipedia.org/wiki/Euler%27s_identity).
Comment: from pragmatism to feticism in no time. Why I'm not surprised that the animation of this on the wikipedia looks like it's solving the "squaring the circle" problem.
Comment: @Asimov me neither. But if the user was unaware of the identity, then I'm glad I introduced him to it ;)
Comment: @DavidH Indeed, who can argue as to the beauty of the Euler Formulas applications.
Comment: the funny thing is, I still don't get what "transcendental" means in practical geometric terms, even after seen this, because this is the real difference between $\pi$ and $\sqrt{2}$ and I can't visualize what this means .
Answer: For a programmer the  Ramanujan formula(e) might be quite useful.
Answer: Here are some formulas relating $\pi$ and $\sqrt{2}$. Given the Riemann zeta function,
$$\zeta(s) = \sum_{k=1}^\infty \frac{1}{k^s}$$
Let $q=e^{\pi\sqrt{2}}$. Then,
$$\begin{aligned}\frac{3}{2}\,\zeta(3) &= \frac{\pi^3}{24}\sqrt{2}-2\sum_{k=1}^\infty \frac{1}{k^3(q^{k}-1)}-\sum_{k=1}^\infty\frac{1}{k^3(q^{2k}-1)}\\
\frac{3}{2}\,\zeta(5) &= \frac{\pi^5}{270}\sqrt{2}-4\sum_{k=1}^\infty \frac{1}{k^5(q^{k}-1)}+\sum_{k=1}^\infty \frac{1}{k^5(q^{2k}-1)}\\
\frac{9}{2}\,\zeta(7) &= \frac{41\pi^7}{37800}\sqrt{2}-8\sum_{k=1}^\infty\frac{1}{k^7(q^{k}-1)}-\sum_{k=1}^\infty\frac{1}{k^7(q^{2k}-1)} \end{aligned}$$


During continuous process of fio test, SSD sequential read bandwidth will slows down

Question: I am using fio to test NVMe SSD max sequential read bandwidth, following is my fio command arguments.
<code>fio -direct=1 -filename=/dev/nvme0n1 -name=nvme0n1-read_bw -rw=rw -ioengine=io_uring -rwmixwrite=0 -iodepth=256 -numjobs=1 -bs=128k -output-format=json -time_based=1 -runtime=100 -group_report -output=nvme0n1-read_bw.output"
</code>
In the beginning, fio will achieve about 6400MiB/s, but after running fio job for about 30s, fio will slow down to only about 3000MiB/s
I have tried to accelerate numjobs to 4, then i will see fio sequential read bandwidth get 6400MiB/s. The question is why NVMe SSD will slow down ? and why using 4 numjobs don't slow down ?
(This is an Intel SSD,claim its max sequential read bandwidth is 6000MiB/s)
Answer: It looks like a single thread bug in ioengine – io_uring, which is used for benchmark. The bug has been reported here - https://github.com/axboe/fio/issues/1206
I'd suggest to run benchmark with Linux default engine - libaio
Comment: Thanks a lot, I'm trying to run benchmark with libaio


Risks of Kerberos Delegation

Question: I've been spending hours upon hours trying to learn and understand Windows Authentication, Kerberos, SPNs, and Constrained Delegation in IIS 7.5. One thing I just don't get is why it is "risky" to leave delegation enabled (i.e. not disable delegation for sensitive accounts) for Admins, CEOs, etc. Can someone please explain this to me in simple terms? Please frame your answer with respect to an intranet environment.
My reasoning is that it shouldn't be a concern, because delegation simply allows a front-end web server, for example, to act on the Windows Authenticated person's behalf when communicating to other servers. If the person has access, they have access, I don't understand why this should be a concern.
Please forgive my ignorance. I'm primarily a developer, but my company is running very lean these days and I'm forced to wear the server admin hat too... unfortunately, it still doesn't fit very well, lol.
Answer: Two examples:

Constrained delegation enables impersonation without having the user's credentials or authentication token.  For an example, see this answer.
In a more typical meat-and-potatoes unconstrained delegation scenario, whether it is windows integrated authentication or forms authentication, having delegation access to a user's authentication token is very powerful.  That literally means that token can be used to impersonate that user to access any network resource.  Anyone involved in that process, such as a developer, could use that in a nefarious way to obtain unauthorized access.

In both examples, if the box is checked for "account is sensitive and cannot be delegated", these are not security issues.  It's also possible to architect a system/feature where these capabilities do exist, but are tightly controlled.
That box should be checked for administrative accounts, such as members of the Enterprise Admins group, because (hopefully) those accounts rarely need to use applications that require impersonation.  It is also be a good idea for senior executives who have access to sensitive information, such as a CIO, COO, head of Finance/Treasury, etc.
So the bottom line is, Microsoft provided that checkbox and the accompanying warning for a very good reason, and it should not be dismissed or taken lightly unless it can be demonstrated that a particular scenario does not have undesirable risk exposure, or some compensating control.  This usually involves vetting by some qualified person(s) that are not involved in the actual implementation or development of an application or system.
Comment: Even if using integrated pipeline mode, if the auth token is present, it can be leveraged by IIS and whatever application is running. When using Windows integrated authentication, the auth token is part of the http header. It may be useful to try to perform a penetration test on the proposed configuration to determine if what you think is correct.
Comment: First off, incredibly helpful and in-depth answer. Can't tell you how much I appreciate it. :) I still wonder, what is necessary for this to be exploited because people are certainly not going to have access to our executive's credentials. It should also be noted that the systems we are allowing constrained delegation to are accessible by every employee on the network anyway. Also, I am trying to accomplish this with Integrated pipeline mode and NO ASP.NET Impersonation.
Comment: Holy crap! Part of the HTTP Header? It must at least be encrypted right? Otherwise that's just insane! Why would Microsoft even make such a ludicrous recommendation? I'm afraid I haven't the first clue about pen testing, so I'll just have to take your word for it. Still, none of the apps on this particular intranet server are internally restricted so I think it would be safe. Tokens are limited time and dynamically generated right? We only restrict certain pages using `allow`/`deny` authorization tags.
Answer: I've setup 1000's of customers with delegation most of the unconstrained. I think it is important to note that if you don't trust your application (lets say deployed on IIS) or you are giving our your delegated service account credentials for others to use freely, then constrained delegation is probably a good idea. However if you don't expect anyone to have the ability to rewrite your application, you keep your service account credentials safe, and you trust that your apps are only going to delegate to the service(s) they were designed for, then the there is usually nothing to worry about. I've seen some "security conscious" customers focus very heavily on issues like this while their resources could be better spent working on real security threats...
Comment: I greatly appreciate your insights; very helpful. I've long since given up on configuring delegation on our Intranet and fell back to running the AppPool in IIS under a special account with access to the necessary resource as it was previously setup. I hope to revisit this issue and get a real solution in place, but a lack of time and experience with delegation preclude that hope for now. :(

Risks of Kerberos Delegation


Surface separating the boundary of a cylinder

Question: Let $M^2$ be a connected closed surface. Suppose there exists an embedding from a connected closed surface $N$ into the interior of $M \times [0,1]$ such that $N$ separates $M \times \{0\}$ and $M \times \{1\}$.
Can we prove the genus of $N$ is no smaller than that of $M$?
Answer: Nice question. Yes. Since you say "genus" I assume you implicitly mean to say oriented surfaces.

Proposition: Under your assumptions, projection to $M \times \{0\}$ defines a degree one map $N \to M$.

To be precise, if $i: N \to M \times [0,1]$ is the inclusion and $p: M \times [0,1] \to M$ is projection onto the first component, then $pi$ is degree 1.
To conclude, it is well-known that if $f: \Sigma_g \to \Sigma_h$ is a map of degree 1 then $g \geq h$. I leave it to you to provide or find a proof.

Proof of proposition. Write $M \times [0,1] = M_- \cup M_+$ with $M_- \cap M_+ = N$ and $M \times \{0\} \subset M_-$.
Write $i_0$ for the inclusions of $M \times \{0\}$ into $M \times [0,1]$.
Then (a suitable triangulation of) $M_-$ shows that $N$ and $M \times \{0\}$ are homologous in $M \times [0,1]$. That is, $$(i_0)_*[M] = i_* [N].$$
Composing with $p$ one finds that $$p_* (i_0)_* [M] = p_* i_* [N].$$ But $(p i_0) = 1_M$ and therefore $$p_* i_* [N] = [M],$$ and $pi$ is a degree 1 map as desired.


Can lilypond grace note beams be added to regular beams?

Question: I'm engraving Bach Invention 4 (D Minor) BWV775 in Lilypond and the existing score has grace notes (measure 37) beamed from a regular note:

My reading of https://lilypond.org/doc/v2.21/Documentation/notation/beams#manual-beams is that grace note beams can be in parallel but are seperate.
So my best attempt at present is:
a16[ d,-1] << { b8.-2] a16-. } \\ { b8. \grace { c32 b8 }} >>

which gives me:

Trying a beam into the \grace { } gives me unterminated beam error, so it appears grace notes are beamed seperately. I suspect there may be a different approach than using a seperate voice for the grace notes though.
Comment: Without knowing what piece this is from, those don't look like grace notes; they look like alternative notes. Either way, it seems like they could be written as a second voice using a smaller note size.
Answer: I suppose you do not really want grace notes there but rather something like
\new Staff
{
  \time 3/8
  a''16 d''
  <<
    \mergeDifferentlyDottedOn
    {
      \override Beam.length-fraction = 0.70
      \override Stem.length-fraction = 0.9
      \override Beam.beam-thickness = 0.37
      b'32[ \tiny c'' b'8]
    } \\
    {
      b'8. a'16
    }
  >>
}

Answer: Here's a slightly different way to do the same thing using \magnifyMusic and force-hshift.  The main advantage (beside being smaller) is that you only have to manually adjust one thing.
\new Staff \relative a'' {
  \time 3/8
  \mergeDifferentlyDottedOn
  a16 d,
  <<
    {
      \override NoteColumn.force-hshift = 0.4
      \magnifyMusic #2/3 { b32[ c b8] }
    }
    \\
    {
      b8. a16
    }
  >>
}

Comment: Hello Knute. That is looking good. But I'd suggest to remove the hshifting and instead do something like `\magnifyMusic #2/3 { \once\normalsize b32[ c b8] }`, which will lead to better general alignment. Cheers, Valentin
Comment: Ah yes, that's even better! We shouldn't be shy in commenting on other people's code. We learn more that way.


Expander header has incorrect width with rotated text

Question: I have an (right-direction) expander which should hide the header when expanded, and display some text rotated to be vertical down the right hand side when it is collapsed.
I have managed to achieve this using the following code:
<code><Expander Grid.Column="1" ExpandDirection="Left"
      IsExpanded="True" Name="rightHandExpander"
      MaxWidth="{Binding RelativeSource={RelativeSource PreviousData}}">
    <Expander.Header>
        <TextBlock Text="Header text" RenderTransformOrigin="0,0"
            Visibility="{Binding IsExpanded, RelativeSource={RelativeSource
                         AncestorType={x:Type Expander}, Mode=FindAncestor},
                         Converter={StaticResource boolToVisibilityConverter}}">
            <TextBlock.LayoutTransform>
                <TransformGroup>
                    <RotateTransform CenterX="25" CenterY="25" Angle="90" />
                </TransformGroup>
            </TextBlock.LayoutTransform>
        </TextBlock>
    </Expander.Header>
    <!-- controls here -->
</Expander>
</code>
However when the expander is collapsed, the header takes up far too much space- the text is rotated, but the header's width appears to remain as if it has not.
Using VisualTreeHelper in the code-behind I discovered that the expander's header, border and dockpanel were too large, but the inner toggle button was the correct size. I tried setting the header, border and dockpanel's width to the correct size but they did not change.
Can anyone help?
Edit:
The expander is contained in a grid with two columns with a grid splitter and another expander in the first column. The other expander does the same thing but collapsing to the left hand side- this expander seems to work correctly, however.
Comment: can you post a bit more code about how your expander is set into your container (a Grid maybe, i see Grid.Column) in your code.
Comment: If you put your expander in a page/window on its own, how does it behave?  It's possible that the `Grid` control is stretching your `Expander` to fit the size of the column.
Comment: Can you post all the Grid xaml? It will be more explicative than words
Answer: I believe setting 'HorizontalAlignment' to 'Right' may fix the behaviour you are getting, as the default behaviour of most controls in a grid will be to fill all available space in their cell. It is kind of strange your left one works though, unless it is not directly in a grid, or has HorizontalAlignment set to Left?
Comment: thanks this helped! I think it was a combination of including the horizontalalignment, and that I had set the MaxWidth of the lhs panel so the right one could not fully collapse.


Selenium webdriver waits (python)

Question: I have a little issue with selenium webdriver (using python 3.x).
Question is - application which I am testing is 'too fast', I was trying to use explicit/implicit waits, but non of these are working.
As we know it's not the great solution of using sleep() method, so maybe you will help me. Here is few lines of code.
We are writing code with bdd (gherkin/behave).
<code>from behave import when, then
from selenium.webdriver.common.keys import Keys

from some_module.ui.bdd_tests import helpers
from some_module.ui.bdd_tests.pages.method_x import method_x_method
from some_module.ui.bdd_tests.pages.also_module import another_page
from some_module.ui.bdd_tests.pages.profile_builder import ProfileBuilderPage

@when('user collapses method_x_step')
def step_impl(context):
    method_x = method_x_method(context.browser)
    method_x.find_clickable_element(method_x.COLLAPSE_EXPAND_method_x).click()

@then('method_x_step is collapsed')
def step_impl(context):
    method_x = method_x_method(context.browser)
    assert method_x.find_text_in_element(method_x.COLLAPSE_EXPAND_method_x, 'Expand All')

@then('method_x_step is expanded')
def step_impl(context):
    method_x = method_x_method(context.browser)
    assert method_x.find_text_in_element(method_x.COLLAPSE_EXPAND_method_x, 'Collapse All')

@when('user collapses attacks')
def step_impl(context):
    method_x = method_x_method(context.browser)
    method_another_page = another_page(context.browser)
    attacks_header = method_x.find_clickable_element(method_another_page.ATTACKS_method_x_HEADER_CONTAINER)
    attacks_header.find_element(method_another_page.ICON_CARET_UP.method,
                                method_another_page.ICON_CARET_UP.location).click()

@then('attacks are collapsed')
def step_impl(context):
    method_x = method_x_method(context.browser)
    method_another_page = another_page(context.browser)
    attacks_header = method_x.find_clickable_element(method_another_page.ATTACKS_method_x_HEADER_CONTAINER)
    assert method_x.find_clickable_element(method_another_page.ICON_CARET_DOWN)
    assert attacks_header.find_element(method_another_page.ICON_CARET_DOWN.method,
                                       method_another_page.ICON_CARET_DOWN.location).is_displayed()

@when('user expands attacks')
def step_impl(context):
    method_x = method_x_method(context.browser)
    method_another_page = another_page(context.browser)
    attacks_header = method_x.find_clickable_element(method_another_page.ATTACKS_method_x_HEADER_CONTAINER)
    attacks_header.find_element(method_another_page.ICON_CARET_DOWN.method,
                                method_another_page.ICON_CARET_DOWN.location).click()

@then('attacks are expanded')
def step_imp(context):
    method_x = method_x_method(context.browser)
    method_another_page = another_page(context.browser)
    attacks_header = method_x.find_clickable_element(method_another_page.ATTACKS_method_x_HEADER_CONTAINER)
    assert method_x.find_clickable_element(method_another_page.ICON_CARET_UP)
    assert attacks_header.find_element(method_another_page.ICON_CARET_UP.method,
                                       method_another_page.ICON_CARET_UP.location).is_displayed()

@then('burger menu options are visible')
def step_impl(context):
    method_x = method_x_method(context.browser)
    assert method_x.find_text_in_element(method_x.EDIT_BUTTON, 'Edit')
    assert method_x.find_text_in_element(method_x.RENAME_BUTTON, 'Rename')
    assert method_x.find_text_in_element(method_x.DUPLICATE_BUTTON, 'Duplicate')
    assert method_x.find_text_in_element(method_x.DELETE_BUTTON, 'Delete')

@when('user clicks out of the panel to hide the menu')
def step_impl(context):
    method_x = method_x_method(context.browser)
    method_x.find_visible_element(method_x.CLICK_OUT_OF_method_x).click()

@then('edit name input disappears')
def step_impl(context):
    method_x = method_x_method(context.browser)
    method_x.find_invisible_element(method_x.NAME_EDIT_INPUT)

@then('burger menu options are not visible')
def step_impl(context):
    method_x = method_x_method(context.browser)
    assert method_x.find_invisible_element(method_x.DELETE_BUTTON)
    assert method_x.find_invisible_element(method_x.RENAME_BUTTON)
    assert method_x.find_invisible_element(method_x.DUPLICATE_BUTTON)
    assert method_x.find_invisible_element(method_x.DELETE_BUTTON)

# 1 parameter steps
@when('user clicks on "{button}" option in method_x_step context menu')
def step_impl(context, button):
    method_x = method_x_method(context.browser)
    if button == 'Edit':
        method_x.find_present_element(method_x.EDIT_BUTTON).click()
    elif button == 'Rename':
        method_x.find_present_element(method_x.RENAME_BUTTON).click()
    elif button == 'Duplicate':
        method_x.find_present_element(method_x.DUPLICATE_BUTTON).click()
        method_x.find_visible_element(method_x.RENAME_PROFILE_FIELD).send_keys(Keys.ENTER)
    elif button == 'Delete':
        method_x.find_present_element(method_x.DELETE_BUTTON).click()
    else:
        raise ValueError(f"{button} is a wrong option")

@when('user clicks "{modal_button}" modal button')
def step_impl(context, modal_button):
    pb = ProfileBuilderPage(context.browser)
    if modal_button == 'Update':
        pb.find_clickable_element(pb.UPDATE_BUTTON).click()
    elif  modal_button == 'Delete Profile':
        pb.find_present_element(pb.DELETE_BUTTON_MODAL).click()
    else:
        raise ValueError(f"{modal_button} is a wrong option")

@when('user renames method_x_step profile with "{method_x_profile}"')
def step_impl(context, method_x_profile):
    method_x = method_x_method(context.browser)
    method_x.find_present_element(method_x.RENAME_PROFILE_FIELD).clear()
    method_x.find_visible_element(method_x.RENAME_PROFILE_FIELD).send_keys(method_x_profile)
    method_x.find_visible_element(method_x.RENAME_PROFILE_FIELD).send_keys(Keys.ENTER)

@then('there is "{method_x_profile}" profile on method_x_step')
def step_impl(context, method_x_profile):
    method_x = method_x_method(context.browser)
    method_x.find_element_by_child_element(
        method_x.method_x_ENTITY.parent, method_x.method_x_ENTITY.child, method_x_profile)

@then('method_x_step profile "{method_x_profile}" has been duplicated and got suffix: "{suffix}"')
def step_impl(context, method_x_profile, suffix):
    method_x = method_x_method(context.browser)
    method_x.find_element_by_child_element(
        method_x.method_x_ENTITY.parent, method_x.method_x_ENTITY.child, method_x_profile + suffix)

@when('user clicks burger icon on "{method_x_profile}" left profile attacks')
def step_impl(context, method_x_profile):
    method_x = method_x_method(context.browser)
    method_x_profile = helpers.adjust_resource_name(context.preconfigured_resources, "attacks", method_x_profile)
    burger_icon = method_x.find_element_by_child_element(
        method_x.method_x_ENTITY.parent, method_x.method_x_ENTITY.child, method_x_profile)
    hamburger = burger_icon.parent.find_element(
        method_x.BURGER_MENU_method_x.method, method_x.BURGER_MENU_method_x.location)
    hamburger.click()
</code>
Expected results are to just slow down the application with selenium's waits.
Answer: Python selenium: wait until element is clickable - not working
Perhaps this is what you're looking for? I can't test your code right now, so I'm not too sure what you're waiting for. This is for waiting for elements to appear on screen.
Comment: Hi there,
I have a problem with any modals/pop-ups - I have to slow down the app, because, when some modal comes up selenium just hangs.

Selenium webdriver waits (python)


postfix, dovecot 2, mailman, dovecot-lda on same domain, config does not work anymore

Question: this configuration used to work but after updating to Dovecot 2 (Ubuntu 12.04) mails to mailman get not delivered anymore:
Instead of delivering to mailman, I get a bounce for non-existing user email@example.com
postconf -n:
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases, hash:/var/lib/mailman/data/aliases
append_dot_mydomain = no
biff = no
broken_sasl_auth_clients = yes
config_directory = /etc/postfix
dovecot_destination_recipient_limit = 1
inet_interfaces = all
inet_protocols = ipv4
mailbox_command = /usr/lib/dovecot/dovecot-lda -f "$SENDER" -a "$RECIPIENT"
mailbox_size_limit = 0
mydestination = $myhostname
myhostname = host.domain.tld
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 141.x.x.x
myorigin = /etc/mailname
owner_request_special = no
readme_directory = /usr/share/doc/postfix
recipient_delimiter = +
relayhost = smarthost.domain.tld
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP
smtpd_recipient_restrictions = reject_unknown_recipient_domain,     reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated,    reject_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous
smtpd_sasl_tls_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_tls_CAfile = /etc/postfix/cacert.pem
smtpd_tls_cert_file = /etc/ssl/certs/ssl-mail.pem
smtpd_tls_key_file = /etc/ssl/private/ssl-mail.key
smtpd_tls_loglevel = 3
smtpd_tls_received_header = yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_tls_session_cache_timeout = 3600s
smtpd_use_tls = yes
tls_random_source = dev:/dev/urandom
unknown_local_recipient_reject_code = 550
virtual_alias_maps = mysql:/etc/postfix/mysql_virtual_alias_maps.cf,     hash:/var/lib/mailman/data/virtual-mailman, hash:/etc/postfix/virtual
virtual_gid_maps = static:1002
virtual_mailbox_base = /home/vmail
virtual_mailbox_domains = mysql:/etc/postfix/mysql_virtual_domains_maps.cf
virtual_mailbox_limit = 51200000
virtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf
virtual_transport = dovecot
virtual_uid_maps = static:1002

master.cf:

# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master").
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       -       -       -       -       smtpd
submission inet n       -       -       -       -       smtpd
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       -       -       -       smtpd
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
#628      inet  n       -       -       -       -       qmqpd
pickup    fifo  n       -       -       60      1       pickup
cleanup   unix  n       -       -       -       0       cleanup
qmgr      fifo  n       -       n       300     1       qmgr
#qmgr     fifo  n       -       -       300     1       oqmgr
tlsmgr    unix  -       -       -       1000?   1       tlsmgr
rewrite   unix  -       -       -       -       -       trivial-rewrite
bounce    unix  -       -       -       -       0       bounce
defer     unix  -       -       -       -       0       bounce
trace     unix  -       -       -       -       0       bounce
verify    unix  -       -       -       -       1       verify
flush     unix  n       -       -       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       -       -       -       smtp
# When relaying mail as backup MX, disable fallback_relay to avoid MX loops
relay     unix  -       -       -       -       -       smtp
    -o smtp_fallback_relay=
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       -       -       -       showq
error     unix  -       -       -       -       -       error
retry     unix  -       -       -       -       -       error
discard   unix  -       -       -       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       -       -       -       lmtp
anvil     unix  -       -       -       -       1       anvil
scache    unix  -       -       -       -       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  -       n       n       -       -       pipe
 flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix  -   n   n   -   2   pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman   unix  -       n       n       -       -       pipe
  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
  ${nexthop} ${user}
# Dovecot LDA
dovecot   unix  -       n       n       -       -       pipe
   flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -d ${recipient}
#smtp      inet  n       -       n       -       1       postscreen
#smtpd     pass  -       -       n       -       -       smtpd
#dnsblog   unix  -       -       n       -       0       dnsblog
#tlsproxy  unix  -       -       n       -       0       tlsproxy

mm.cfg is also pretty straightforward:

MTA='Postfix'
POSTFIX_STYLE_VIRTUAL_DOMAINS = ['my.host.tld']

Dovecot is configured to authenticate only users via mysql - but the mailman aliases are identical. The domain is a postfix virtual domain.
Any hints where to look? What to test?
It used to work with the identical configuration, but now I'm using dovecot-lda from dovecot 2.0 and it does not work anymore, but It can also be a another problem, some configuration change.
Answer: It's not a dovecot issue or a Postfix issue. It was a problem related to the delivery of messages for mailman. I'm still not sure why it once worked but I've got it now working:
Mailman Doc Entry for this Problem
If I follow all these steps and add the newly generated transports-mailman file to Postfix it works.
Answer:
Is smtp auth still working?
Is dovecot login still working? Can user pick up mail via imap or pop3?
Test /usr/lib/dovecot/dovecot-lda -f "$SENDER" -a "$RECIPIENT" manually with real email address in your domain.

If (2) or (3) failed, then it is dovecot issue.
Comment: 1: yes
2: yes
3: works

I've found the problem and post it as an answer for others to read


change date format from dd/mm/yyyy to yyyy/mm/dd in angular on input field

Question: I am using D.O.B field in register form which is a reactive form where input type of D.OB i am using is type = "date"
The format I am getting is in dd-mm-yyyy but I want the format to be yyyy-mm-dd on my html side..
is there a way to do this and if yes then how..
angular version is 12
To be specific again I want my view on client side to be of yyyy-mm-dd format not of dd-mm-yyyy
Answer: Import DatePipe from '@angular/common' in the "app.module.ts" file.
import DatePipe from '@angular/common';

....

providers:[
 DatePipe
],

Import DatePipe in your components and construct
import { DatePipe } from '@angular/common';

...
constructor(private datepipe:DatePipe){

}

ngOnInit(){
 var ddMMyyyy = this.datePipe.transform(new Date(),"dd-MM-yyyy");
}

you can refer this article to get more idea:
https://www.code-sample.com/2019/02/angular-7-date-format-datepipe-example_23.html
Comment: my question was how to show it in yyyy/MM/dd format on html side i.e on screen using input type = date
Answer: const format = 'yyyy/MM/dd';
const myDate = '2021-07-27';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);

Link
Comment: my question was how to show it in yyyy/MM/dd format on html side i.e on screen using input type = date..
Comment: I have the same question @abhassrivastava


Converting Excel MAcro from 32 Bit to 64 Bit

Question: I have a quite large excel macro written in 32bit and need to convert to use n excel 64 bit. Is there an easy way to do this conversion?
It is a large macro and not possible to convert line by line.
I have included part of the code below.
<code>'32-bit API declarations
Declare Function SHGetPathFromIDList Lib "shell32.dll" _
    Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long

Declare Function SHBrowseForFolder Lib "shell32.dll" _
    Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long

Sub DisplayDirectoryDialogBox()
    Dim Msg As String
    FileCount = 0
    Msg = "Select a location containing the files you want to list."
    SelectedDir = GetDirectory(Msg)
    If SelectedDir = "" Then End
    With Application
        .StatusBar = "WAIT..."
        .ScreenUpdating = False
</code>
Comment: Manually add `PtrSafe` to all declarations. Manually convert all `Long`s in the declarations that represent pointers to `LongPtr`s (in the code shown, that would be only `pidl`). Manually update declarations of `Long` variables in procedures that are passed as these parameters to `LongPtr`. There's no other way. You may try to look into refactoring tools/addins that may automate the replacements to a degree.
Comment: Thanks. I will try this and let you know.
Comment: @GSerg seems to work fine. Please put it in answer box and I accept it. Thanks.
Answer: Credit to Gserg:
Manually add PtrSafe to all declarations. Manually convert all Longs in the declarations that represent pointers to LongPtrs (in the code shown, that would be only pidl). Manually update declarations of Long variables in procedures that are passed as these parameters to LongPtr. There's no other way. You may try to look into refactoring tools/addins that may automate the replacements to a degree. – GSerg Jul 18 at 8:55


Relation between Ranges of compact operators

Question: I am reviewing functional analysis and getting stuck in this problem. Let $X,Y$ be two Banach spaces and $A,B\in L(X,Y)$. Prove that if $A$ is a compact operator and $R(B)\subset R(A)$ then $B$ is also a compact operator.
Can anyone give me some hints for this question ? Thank you very much.
Comment: I think you need to assume that $B$ is bounded
Comment: Yes. B is a bounded linear operator
Answer: Endow $R(A)$ with the quotient norm having the unit ball $A(K_X)$ where $K_X$ is the unit ball of $X$. This is a Banach space and $\tilde B:X\to R(A)$, $x\mapsto B(x)$ is
well-defined by assumption, linear, and has closed graph (because the norm of $Y$ gives a coarser norm on $R(A)$ which makes $B$ continuous). The closed graph theorem implies the continuity of $\tilde B$ so that $\tilde B(K_X) =B(K_X) \subseteq c A(K_X)$ for some $c>0$. Since $A(K_X)$ is relatively compact in $Y$ the same holds for $B(K_X)$.
Comment: What is the quotient norm on R(A) #Jochen
Comment: The quotient norm of $z\in R(A)$ is $\inf\lbrace \|x\|_X: A(x)=z\rbrace$. The open unit ball of the quotient norm is the image of the open unit ball of $X$.


Serial correlation: estimation vs robust SE

Question: We have route-level data (that I cannot share) on monthly bus ridership in New York City, creating a panel $N= 185$, $T=36$. We estimate a fixed effects model and random effects model with R's plm package. (For this MWE, I use the Grunfeld investment data, which illustrates the problems I am seeing fairly well).
library(plm)
data("Grunfeld")
model_1A <- lm(inv ~ value + capital, data= Grunfeld)
fe.plm <- plm(formula(model_1A), model="within", index=c("firm", "year"),
              data=Grunfeld)
re.plm <- plm(formula(model_1A), model="random", index=c("firm", "year"),
              data=Grunfeld)

A Hausman test indicates that the FE model is preferred, because the estimates differ (note that in the MWE, we fail to reject).
phtest(fe.plm, re.plm)

##  Hausman Test

##data:  formula(model_1A)
##chisq = 2.3304, df = 2, p-value = 0.3119
##alternative hypothesis: one model is inconsistent

pbgtest(fe.plm)

##  Breusch-Godfrey/Wooldridge test for serial correlation in panel models

##data:  formula(model_1A)
##chisq = 65.0632, df = 20, p-value = 1.14e-06
##alternative hypothesis: serial correlation in idiosyncratic errors

pbgtest(re.plm)

##  Breusch-Godfrey/Wooldridge test for serial correlation in panel models

##data:  formula(model_1A)
##chisq = 69.9495, df = 20, p-value = 1.856e-07
##alternative hypothesis: serial correlation in idiosyncratic errors

This is where what I think should happen diverges from what many people try to do. My understanding of serial correlation is that it affects the standard errors but not the coefficients. This would suggest to me a serial correlation-robust standard error. For instance (as in this answer),
fe.rse <- sqrt(diag(vcovHC(fe.plm, type="HC1", cluster="group")))
re.rse <- sqrt(diag(vcovHC(re.plm, type="HC1", cluster="group")))

** Why not just use sc-robust standard errors?**
But what many authors do instead is include specific AR(1) or ARMA disturbances because Stata makes this easy. For the FE models, we can use gls from the nlme package on demeaned data (note: fe.plm and fe.gls are virtually identical),
# within estimator is demeaned
demean <- numcolwise(function(x) x - mean(x))
Grunfeld.dm <- ddply(Grunfeld, .(firm), demean)
Grunfeld.dm$year <- Grunfeld$year

fe.gls <- gls(update(formula(model_1A), .~.-1), method="ML",  data=Grunfeld.dm)
fear.gls <- update(fe.gls,  correlation = corAR1(form = ~ year | firm))
fearma.gls <- update(fe.gls, correlation = corARMA(form = ~ year | firm,
                                                   p=1,q=1))

The RE models can be estimated in with lme in the nlme package (again, re.plm and re.lme are identical).
re.lme <- lme(fixed = formula(model_1A), random = ~ 1|firm, data = mta)
rear.lme <- update(re.lme,  correlation = corAR1(form = ~ year | firm))
rearma.lme <- update(re.lme,  correlation = corARMA(form = ~ year | firm,
                                                    p=1,q=1))

There are a few things I don't understand about this:

Why do the coefficients change when serial correlation doesn't (shouldn't?) affect estimates?
Can we still use the Hausman test to select between FE and RE models with autoregressive errors?
How can we test for residual autocorrelation? And if it exists, wouldn't we still need a robust standard error?
Answer: I think I can help with some of your questions.
1) Why not just use serial correlation robust standard errors?  Clustered standard errors will be more robust.  For example, if you have serial correlation and heteroskedasticity, clustered standard errors would be valid here, while serial correlation robust standard errors would not be.
2) Why do the coefficients change (I think you mean between FE and adding some explicit AR process)?  I think that what is happening is that two procedures that are both consistent may lead different numeric results in finite samples (Fixed Effects vs. Random Effects when random effects assumptions are valid is a good example of when this would be the case).   Also, misspecification of the the serial correlation could be a problem for consistency (not 100% sure here).
3) Can we use the Hausman test with serial correlation?  Not off-the-shelf.  The test statistic depends on the variance matrix of $\beta_{RE}$ and $\beta_{FE}$.  You would need to adjust these (using e.g. clustered standard errors) to use the Hausman test.
In my opinion, you should do fixed effects estimation and adjust the standard errors as you mention in your post.


How to properly alter response from Solr Search Module

Question: I'm working on Drupal Version 7.22 and I'm trying to modify the results coming from Solr using the hook provided by the Solr Search Module.
The specific hook can be found here: http://drupalcontrib.org/api/drupal/contributions!search_api_solr!search_api_solr.api.php/function/hook_search_api_solr_search_results_alter/7
Here's how I implemented it from the module:
/**
 * Implements hook_search_api_solr_search_results_alter().
 */
function zen_search_api_solr_search_results_alter(array &$results, SearchApiQueryInterface $query, Apache_Solr_Response $response){

  $locations = array();

  $rest = $results['results'];
  foreach($rest as $r){

    $place = $r['fields']['field_business_name'];
    $postal_code =  urlencode($r['fields']['field_business_address:postal_code']);

    $api = 'http://maps.googleapis.com/maps/api/geocode/json?address=' .  $postal_code . '&sensor=false';
    $api_results = file_get_contents($api);
        $data = json_decode($api_results, true);

        if($data['status'] == 'OK'){
            $location = $data['results'][0]['geometry']['location'];

            $locations[] = array(
                'place' => $place,
                'lat' => $location['lat'],
                'lng' => $location['lng']
            );
        }

  }

    $data = array('zen' => array('locations' => $locations));
    drupal_add_js($data, 'setting');

}

So basically what I'm trying to do here is to add the coordinates that I get from the Google  maps Geo-coding API using drupal_add_js.
But I'm getting the following error:

Recoverable fatal error: Argument 3 passed to
  zen_search_api_solr_search_results_alter() must be an
  instance of Apache_Solr_Response, instance of stdClass given

Any ideas what's wrong here?
Answer: The problem was this one:
function zen_search_api_solr_search_results_alter(array &$results, SearchApiQueryInterface $query, Apache_Solr_Response $response){
  ...
}

It should be this:
function zen_search_api_solr_search_results_alter(&$results, $query, $response){
  ...
}


How to send a webform email to all users of a specific role?

Question: Is it possible send webform data in email to all users of a specific role?
In the webform email settings there is no such option.
I also tried with Rules, but in rules the webform tokens are rendering the webform submitted data.
Here is my rule attached.
<code>{ "rules_send_email_to_ce_user_on_webform_submit" : {
    "LABEL" : "Send email to CE user on webform submit",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : "[form-id:value]",
          "selected_webform" : { "value" : { "webform-client-form-121" : "webform-client-form-121" } }
        }
      }
    ],
    "DO" : [
      { "webform_submissions_load" : {
          "USING" : { "nid" : "121", "sid" : [ "data:sid" ] },
          "PROVIDE" : { "submissions" : { "submissions" : "Fetched submissions" } }
        }
      },
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "11" : "11" } },
          "subject" : "Form submission from: [node:title]",
          "message" : "DATA\r\n[data:data]\r\n\r\nRAW\r\n[data:data-raw]\r\n\r\nField value\r\n[data:title-value]"
        }
      }
    ]
  }
}
</code>
Any other method?
Answer: From the exported rule in your question, it seems you already have the Webform Rules module enabled (a prereq for what follows ...).
You may want to give it a try to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

Load the VBO list that you want to be processed.
Add a loop to perform a Rules Action, for each row contained in your Views results.

Some more details about the VBO-view you'd have to create for this:

Create a list users, using the Views module.
It should include an appropriate filter for the role to be processed.
It should have exactly 1 result (row) for each user to be eMailed.
One of the columns should be the eMail Id (I don't see other columns needed for this to work).

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".
Comment: VBO is for views, But I'm using any views here.
Comment: @Ahmad If you don't have a view "yet", just create one (cfr. the bullet "1." I added to my answer.
Answer: You can add an additional submit handler for the webform in hook_form_alter. Then in the submit handler, you get the list of users with that role. You can try the below code to get list of users. Then send email to these users with the submitted data.
<code>// get role data by role name
$role_data = user_role_load_by_name('member');

// get list of users with specific role
$uids = db_select('users_roles', 'ur')
->fields('ur', array('uid'))
->condition('rid', $role_data->rid, '=')
->execute()
->fetchCol();

$users_list = user_load_multiple($uids);
</code>
There may be better solutions for this. But you can have a try.


Can we refocus certain badges?

Question: Rather than have badges that can't be won ever again like Precognition, why not make them more general, like first to do X Y or Z?  The site is apparently still in beta, so there should be a lot of opportunities to be the first to help out with something.
Answer: I don't think that's possible. The badges are general for all SO websites. See some details about it here: Remove impossible badges from per-site metas. There is one badge that can't be earned even on stackoverflow.com

Can we refocus certain badges?


Connect VM to VPN

Question: I am trying to connect my Linux virtual machine(VM) to my corporate VPN via Google Compute Engine. I can make this work on my own Ubuntu computer following this tutorial:
https://help.ubuntu.com/community/VPNClient#PPTP
I do the same steps on my cloud compute engine VM but when I run it, it gives me the error in SSH:

mats@instance-1:~$ sudo pon eurvpn nodetach
Using interface ppp0
Connect: ppp0 <--> /dev/pts/2
Modem hangup
Connection terminated.

May it have something to do with the firewall settings? On the website of my company it says:

Client ports: 1024-65535/TCP
Server port: 1723/TCP
Protocol: PPTP
Allow: IP PROTOCOL 47 (GRE)

And of course I have the gateway, my username and password.
What should I change to my Firewall settings or is there another issue? Help is greatly appreciated!
Kind regards,
Mats
Comment: Try opening ports 1723 and 47 (TCP) and give it another go. Also read [this](http://windowsitpro.com/networking/which-ports-do-you-need-open-firewall-allow-pptp-and-l2tp-over-ipsec-vpn-tunnels)
Comment: Were you ever able to resolve this issue? If so please consider posting a self-answer so the community can benefit.
Answer: It might has something to do with port forwading, give this tutorial a try.

Connect VM to VPN


How can i make a placeholder image add itself if there is no image uploaded?

Question: I have a php script here for adding images to the database. However, I have a problem because when I leave the image selection blank nothing is added to the database and it breaks the rest of the application. Is it possible to add something like a placeholder here, which is added if the file selection is not completed?
//file name is config.php
<?php
$dbHost     = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName     = "codexworld";

// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}
?>

//file name is dodanie_zdjecia.php

<form action="post.php" method="post" enctype="multipart/form-data">
    Select Image File to Upload:
    <input type="file" name="file">
    <input type="submit" name="submit" value="Upload">
</form>
<?php

$dbHost     = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName     = "codexworld";

$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}
?>

//file name is post.php
<?php
include 'config.php';
$statusMsg = '';

$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
    // Allow certain file formats
    $allowTypes = array('jpg','png','jpeg','gif','pdf','mp3');
    if(in_array($fileType, $allowTypes)){

        if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){

            $insert = $db->query("INSERT into images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");
            if($insert){
                $statusMsg = "Plik: ".$fileName. "Został poprawnie dodany do posta. Przejdź na stronę główną: Strona główna";
            }else{
                $statusMsg = "File upload failed, please try again.";
            }
        }else{
            $statusMsg = "Sorry, there was an error uploading your file.";
        }
    }else{
        $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
    }
}else{
    $statusMsg = 'Please select a file to upload.';
}

?>

Comment: Usually, what is done is to have a default.jpg image in the images folder of your website, so if any record is uploaded to the database with an image field and it would remain empty, the default.jpg is automatically set.
Comment: Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).
Answer: if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){

 .....
}else{
$fileName='placeholderimagefilelocation'
            $insert = $db->query("INSERT into images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");

}

OR
if($image != '' ){
 your db saved file
}else{
 your placeholder file location
}

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Yamllint Indentation Warning on Valid Ansible code

Question: I have the following task in my playbooks:
<code>    - name: gather os specific variables
      include_vars: "{{ item }}"
      with_first_found:
        - files:
          - "{{ ansible_distro }}-{{
                ansible_distribution_version|lower|replace('/', '_') }}.yml"
          - "{{ ansible_distro }}-{{ ansible_distribution_release }}.yml"
          - "{{ ansible_distro }}-{{
                ansible_distribution_major_version|lower|replace('/', '_') }}.yml"
          - "{{ ansible_distro }}.yml"
          - "{{ ansible_os_family|lower }}.yml"
          paths:
          - ../vars
          skip: true
</code>
This is correct as of https://github.com/ansible/ansible/blob/devel/lib/ansible/plugins/lookup/first_found.py.
Yamllint is giving me the following error:
<code>  10:7      warning  wrong indentation: expected 8 but found 6  (indentation)
  18:7      warning  wrong indentation: expected 8 but found 6  (indentation)
</code>
Why is Yamllint complaining here and how can I correct it so that it conforms while still being a valid Ansible task?
Answer: Correct for parsing, but not good enough for linter to pass.
Add two spaces for nicer look:
<code>  with_first_found:
    - files:
        - "{{ ansible_distro }}-{{
      ^^ here
</code>
and here:
<code>      paths:
        - ../vars
      ^^
</code>
Comment: We've actually converted away from that- removing those two extra spaces. With python's yamllint [the config is](http://yamllint.readthedocs.io/en/latest/rules.html#module-yamllint.rules.indentation) `indent-sequences: false`


Make WordPress User Name the Email Address

Question: Is it possible to make WordPress user name the Email Address?
So unername could be hidden or not required and is replaced with email address.
I know there are plugins that can allow users to use their email as the log in, but they still have to enter the username when they register. I want to try and do away with the username.
Answer: I know this thread is over a year old now, but I just tested creating an account where the username is an email address and it works. In theory, you could create a front-end signup form that saves the email variable to both the username and email fields in the database.
WordPress allows usernames with some special characters, so this is a completely valid way to sign people up: http://codex.wordpress.org/Function_Reference/sanitize_user
Comment: Be aware that usernames are shown in DOM sometimes (some classes for comments etc., depends on a theme), so by using email as a username people can see emails of your users ...
Answer: Yes it is possible. Even you can configure WordPress to Login, Register and Retrieve Password using Email only.
You can put the code below in your theme's functions.php file.
Step-1: Remove Username textfield
add_action('login_head', function(){
?>

<?php
});

Step-2: Remove Username error
//Remove error for username, only show error for email only.
add_filter('registration_errors', function($wp_error, $sanitized_user_login, $user_email){
    if(isset($wp_error->errors['empty_username'])){
        unset($wp_error->errors['empty_username']);
    }

    if(isset($wp_error->errors['username_exists'])){
        unset($wp_error->errors['username_exists']);
    }
    return $wp_error;
}, 10, 3);

Step-3: Manipulate Background Registration Functionality.
add_action('login_form_register', function(){
    if(isset($_POST['user_login']) && isset($_POST['user_email']) && !empty($_POST['user_email'])){
        $_POST['user_login'] = $_POST['user_email'];
    }
});

There is also a plugin to achieve this functionality.
Plugin: https://wordpress.org/plugins/smart-wp-login/
Answer: The username is a core entity in the WordPress DB and philosophy and it can't be bypassed like that. Now if you want to let users login with their emails, use this plugin: http://wordpress.org/extend/plugins/wp-email-login/ It allows you to login with either email/pass or username/pass. Found it like a month ago, works like a charm.
Even plugins that use alternative means for registration and login (facebook, twitter and Google) create a username (for instance, one plugins I've tried creates usernames like fbX where X is the facebook ID. Unfortunately it is not something we can work around.
Hope this helps! :)


Are these chords tied (not played again) or is only the top note tied?

Question: In the recording it sounds like the chords are simply tied... I've been playing piano for 20 years and this seemingly simple question is escaping me. Any help would be appreciated!
The piece is "Caprice in E-Flat" for Piano/Violin by Wieniawski (Kreisler arr.) (from Wieniawski's L'Ecole Moderne, Op. 10, No. 5 "Alla Saltarella").
Answer: The chords in question should be fully tied — no repeated notes.
Although the notation is ambiguous, the music demands ties. The tied chords occur at the ends of musical gestures, and a repeated chord in the piano would interfere with the violin. The editor's reasoning for tie-ing only the top and bottom notes seems to have been (an attempt) to clarify them against the violin part, rather than writing them as dotted quarter notes.
The first and second endings (m. 12), where the violin itself plays a dotted quarter, the piano part also contains a dotted quarter.

Elsewhere in the piece, the chords are tied as expected. For example, measure 24:
Comment: Bit off a lame excuse for the editor - who could have done better.
Comment: Hey this makes sense! Glad to know I'm not crazy for wondering... I naturally tied them but then gave it some more thought and was like... 'should I actually be tying these based on the engraving..?"

I saw that elsewhere in the piece, chords were tied as expected, which made it all the more confusing. Thanks for your insight!
Comment: Any explanation for why the first example's notes have *only the bottom notes* tied, then? It doesn't even look like shorthand for tying all notes in the chord at that point.
Comment: @Dekkadeci In both examples, the ties are placed opposite the stems. The whole thing seems very weird to me, but that seems to be the guiding convention. (Also the ties are outside the staff, so less visual interference.)
Answer: The strict interpretation of this notation is top note tied over, repeat the other two.
I wouldn't be surprised to learn the composer's intention was something else though!
And it could just be sloppy engraving.
More information would help.  What's the piece?
Answer: There are some typesetting conventions and inconsistencies involved here revolving around the difference of slurs and ties.  A slur indicates that there is no separate release of the preceding note (when the note pitch is not continued, the release coincides or even overlaps with the coming attack), a tie indicates that the release is postponed and no new attack is given, prolonging the preceding note value.
Slurs are conceptionally from note column to note column, ties are from note head to note head.  So one typically gets one slur per voice, with voices usually recognised by having their notes connected by a single stem.  The ends of this slur may start from above/below the top/bottom note head and may even encompass the stem.  Sometimes for chords double slurs are used, namely one at the top and one at the bottom of the note column.
The chords you are asking about apparently use that convention.  However, it is rather clear from the musical content that here not slurs but rather ties are intended.  In that case conventions call for one tie each from every note head on the left to the corresponding note head on the right.
This kind of typesetting error resulting from the confusion of ties and slurs is comparatively common with the output of typesetting programs where the editor entering the music does not understand the difference and does not use the program's facilities for specifying either.
I am not sure this is the case here, but as a player I'd clearly interpret this as tied chords even though it is notated as slurred chords (ties tend to be flatter and more to the side of the note heads they correspond to).
Comment: I suspect the confusion between ties and slurs probably stems from instruments where they would usually mean the same thing, which in turn results in the musical meaning varying depending upon what instrument one is using.  On violin, for example, if a slur connects a double-stop containing d' and b' to one containing d' and c'', the d' should sound like a continuous note, but because the same bow is used to produce both notes simultaneously, all notes in a double stop must have the same notated duration, making a tie inappropriate.  A keyboard performance of that same piece...
Comment: ...should likely hold the first d through the duration of the second double-stop (meaning a part *which is printed for keyboard* should use a tie for that note rather than a slur between two double stops), but a keyboardist reading from a violin part should interpret the slur as connecting any notes that don't change pitch.
Answer: There's little point, in 2/4, to not make those note clusters dotted crotchets. That would clear it up nicely. Then we wouldn't need a question about them!
Comment: The reason they're not written that way is to align the piano and solo scores. Very important for an accompanist.
Comment: @Aaron - I don't agree. It's not a complicated arrangement, and any decent accompanist could follow with my suggestion.


OMNeT++ - Veins - Create a scenario of 2 vehicules with a starting position defined

Question: I'm working on Veins | OMNeT++ | SUMO.
Is it possible to select the starting position of our cars and the destination?
I only see spawn of vehicules at the exact same position and don't know how to adapt them. I've already read some topics explaining that we have cars that are created automatically by the TraCI module, but how can we control it?
Answer: Cars are initially created by SuMO and then inserted in Veins by the TraCIScenarioManager. In the demo example from Veins, multiple vehicles are driving from the same origin to the same destination:

194 Cars leaving the Computer Science Building and campus of the University of Erlangen-Nuremberg

In order to have different traffic, you have to adjust the network description files of SuMO - in particular the *.rou.xml. See the SuMO wiki for how to configure vehicles and routes.
Answer: I think you can following method in TraCICommandInterface.h.
bool addVehicle(std::string vehicleId, std::string vehicleTypeId, std::string routeId, simtime_t emitTime_st = -DEPART_NOW, double emitPosition = -DEPART_POS_BASE, double emitSpeed = -DEPART_SPEED_MAX, int8_t emitLane = -DEPART_LANE_BEST_FREE);


Exception messages for exception nesting

Question: Consider I am developing a library. When this library encounters an exception it can't handle itself (e.g. a WebException) it will wrap that exception to hide implementation details from clients and provide them a uniform way of exception handling.
Regarding the message of such an exception, what are the best practices / guidelines / do's /don'ts?
Option 1: Wrapper does not include anything
My personal favorite, each exception is responsible for its own message. The wrapper uses a more general wording than the one being expected from the inner exception.
try
{
  // ...
}
catch (WebException ex)
{
  throw new MyLibraryException("An error occured accessing a web ressource", ex);
}

Option 2: Display the inner message
What more could you want to say, than that what the inner exception has to say? Not sure whether this is viable...
try
{
  // ...
}
catch (WebException ex)
{
  throw new MyLibraryException(ex.Message, ex);
}

Option 3: Concatenate it
I don't believe that this is a good idea, but it came up in a discussion we had locally, so I want to present it as an option.
The outer exception will take care of concatenating inner exception messages.
try
{
  // ...
}
catch (WebException ex)
{
  string message = string.Format("An error occured accessing a web ressource: {0}", ex.Message);
  throw new MyLibraryException(message, ex);
}

I feel that there must be clear guidelines on that topic (e.g. MSDN), but I was not able to find them. I already checked Best Practices for Exceptions, but for no avail.
Option 4: Don't care
From the comments:

do not waste time catching exceptions you cannot handle. Let the caller deal with it.

I don't think that this option is viable, because though I can't handle the exception myself I know that it can occur and I want to hide specifics from the caller (e.g. which exception type to handle?). This is important, because I could someday switch to another framework providing me with Web-Access and thus the exceptions could change. The wrapping helps to maintain the abstraction (IMHO).
edit: There seems to be a lot of confusion. I don't plan to apply this pattern to each and every exception. I will usually ignore or rethrow (throw;) exceptions like FileNotFoundException and many other core framework exceptions. However, there are cases when I want to hide and how am I supposed to do this in the best way possible?
Read this question as: If I had a good reason to nest exceptions, how should my messages look like?
Discussions on if you want to nest exceptions better belong here.
Comment: Option 4: do not waste time catching exceptions you cannot handle. Let the caller deal with it.
Comment: If you know it can occur, perhaps you _should_ be dealing with it, and returning `false` or similar from your method, rather than letting the exception bubble up.  From the best practices article you linked: "A well-designed app handles exceptions and errors to prevent app crashes." You're not handling or preventing crashes by simply replacing one exception with another.
Comment: If you feel that a custom exception makes sense (lets say for example that you want the user of your API to be able to catch on a specific error type or maybe there isn't a suitable exception class already in the framework), then I would recommend option #1.
Comment: A good discussion on when to create custom exceptions is found here: http://stackoverflow.com/questions/3443570/create-custom-exception-or-use-built-in-exceptions
Comment: WPF uses option 3 and it's a pain. I'd really like to see inner exception (option 4) directly.
Comment: What happens when there is a legitimate error and you've stomped the stacktrace...[thats a criminal offence](http://stackoverflow.com/a/178464/495455)
Comment: @JeremyThompson: That is not what I am doing here. I don't throw the exception I received (which would kill the stacktrace), but I *wrap* the exception I received as legitimate innerException. I think that innerExceptions are generally a legitimate measure.
Comment: Thanks @EmilLundin for pointing to this discussion, I believe most other commenters thought I was asking the same question. I think that I will stick with option 1, but I am kind of sad that the discussion here drifted so far away from my question...
Answer: If you need extensive logging it might be wise to capture the error high up the chain to be able to provide as much details as possible about the error in the log message. After logging you should re-throw the exception. Make sure that you use throw; instead of throw ex; to preserve the stack trace.
Answer: Option 4: do not waste time catching exceptions you cannot handle. Let the caller deal with it. Does it really matter to the caller whether they catch MyLibraryException or WebException? If the caller can handle and recover from WebExceptions, then they will want to catch that, not your MyLibraryException.
Also if the exception is thrown up through several layers, with your reasoning each layer would add its own wrapping, which means the top layer then has to drill down through multiple inner exceptions to get to the actual error - ugh!
The very top level can always have a catch all to catch and log any exceptions that have not already been handled.
Finally, you should document what (underlying) exceptions are likely to be thrown from your library, or the code it calls.
Edit: regarding abstraction: abstracting the exception in your MyLibraryException does not help the caller - they cannot recover from a MyLibraryException without knowing the ultimate cause, which is the exception you have wrapped, therefore you might as well not bother wrapping it in the first place, and let the caller catch it directly. If the caller cannot recover from the ultimate exception, then they will probably just catch everything and log the fact that an error occurred, and perhaps then terminate the application.
A concrete example: a FileIOException occurs in your library because of a missing file. Surely it is better for this to be thrown to the caller so they can recover from it (perhaps the user forgot a critical file), rather than the caller having to interpret your MyLibraryException?
Comment: Lets assume I document this clearly. When asking a question I have to balance excessive detail and abstraction. I honestly don't understand why nobody intends to answer the question I asked: What are best practices regarding error messages of nested exceptions? and: are there guidelines? I **did not** ask, whether I *should* nest exceptions.
Comment: I tried to clarify my intent. I do not apply this pattern always. IOExceptions and FileNotFound are good examples of exceptions that I would usually pass untouched. But there are legitimate cases (after all: inner exceptions are not something I made up) and I want to deal with them as good as possible.
Comment: So now it becomes arbitrary as to which exceptions you wrap and which ones you let through. Perhaps in some situations you let IOExceptions through, sometimes you do not. How is the caller meant to know all this? Libraries that use inner exceptions are generally operating much closer to the metal.


Proving that the 2 analytic functions are constant

Question:
Let $$f(z)=u(x,y)+iv(x,y)\,\text{ and }\,g(z)=s(x,y)+it(x,y)$$be two analytic functions on a region D. Suppose$$\left|f(z)\right|^2+\left|g(z)\right|^2=r$$where $r$ is a fixed real number. Show that $f(z)$ and $g(z)$ are constant functions.

I'm thinking of showing that $u$ and $s$ are constants, or $|f|$ and $|g|$ are constants, and either of which will lead to the desired result. I've tried making use of Cauchy-Riemann equations but I'm not getting anywhere. Any hints?
Comment: I'm really not sure how to apply the Cauchy-Riemann equations either. Here's what I got so far (this is not an answer):
Comment: To show that $f$ and $g$ are constant, we need to show that $f'=u_x+iv_y=0$ and $g'=s_x+it_y=0$. Namely, $u_x \equiv u_y \equiv 0$ and $s_x \equiv t_y \equiv 0$.

If $f$ and $g$ are analytic, then the Cauchy-Riemann equations dictate that $u_x=v_y$ and $u_y=-v_x$ for $f$ and $s_x=t_y$ and $s_y=-t_x$ for $g$.

Also, $|f(z)|^2+|g(z)|^2=r$ implies $$(u^2+v^2)+(s^2+t^2)=r.$$ Differentiating both sides with repsect to $x$ gives $$uu_x+vv_x+ss_x+tt_x=0$$
and with respect to $y$ gives
$$uu_y+vv_y+ss_y+tt_y=0.$$
Answer: From the imposed condition, $|f(z)|^2+|g(z)|^2=r^2$, it follows that modulus of each analytic function is oscillating on  $D$ (i.e. $|f(z)|=r\cos(\theta), |g(z)|=r\sin(\theta)$). But by  maximum modulus principle the modulus of an holomorphic function cannot exhibit a true local maximum that is properly within $D$. Hence $f, g$ must be constant functions.
Comment: @Sapphire  The oscillatory property results from the equation $x^2+y^2=r^2$ that is verified by $|f(z)|$ and $|g(z)|$. Moreover, the functions $\cos$ and $\sin$ have distinct points of maxima.
Comment: I get the main idea, but not completely. How does the oscillation guaranteed the existence of maximum within D? Can't seem to visualize it...
Comment: @Sapphire Draw the graphs of real functions $x(\theta)=r\cos(\theta}, \: y(theta)=r\sin(\theta)$ in the same system of axes. The graphs of the functions $z\mapsto |f(z)|$,
Comment: @Sapphire Sorry for the above incomplete comment.  The graphs of functions $z\mapsto |f(z)|, z\mapsto |g(z)|$ are 3D waving surfaces.
Comment: Ok, another part which I don't quite understand is why is the imposed condition sufficient to show the oscillation?


Passing DateTimeKind in ASP.NET Web Api 2.0 GET request

Question: I'm having trouble with DateTimes in my ASP.NET C# Web Api 2 project. I need to pass through an ISO 8601 date in my query string as follows:
api/resource?at=2016-02-14T23:30:58Z

My controller method is as follows
[HttpGet("/resource")]
public IActionResult GetResource([FromQuery]DateTime? at = null)
{
    if (!at.HasValue)
    {
        at = DateTime.UtcNow;
    }
    else
    {
        at = DateTime.SpecifyKind(at.Value, DateTimeKind.Utc);
    }

    // ...
}

Notice the little hack - the date is coming in with a DateTimeKind of Local, despite being specified with the 'Z' signifying UTC.  Dates should always be passed in UTC although I would ideally not like this to be a constraint.  I am using NodaTime internally and only expose DateTime in the query and response models for legacy reasons.

Why are my dates parsed to a DateTimeKind of local?
How can I read my UTC dates from query strings using ASP.NET web api 2?
Comment: What if call a ToUniversalTime() to convert to UTC?
Comment: See [my answer](https://stackoverflow.com/a/46308876/634824) in the dup post.
Answer: If you use DateTimeOffset instead of DateTime, the time-zone offset is preserved. You could then either use it directly, or convert it to a DateTime via the UtcDateTime property.
 DateTimeOffset dto = DateTimeOffset.Parse("2016-02-14T23:30:58Z");
 DateTime dt = dto.UtcDateTime;

[HttpGet("/resource")]
public IActionResult GetResource([FromQuery]DateTimeOffset? at = null)
{
    if (!at.HasValue)
    {
        at = DateTimeOffset.UtcNow;
    }

    // ...
}

Comment: Thanks Markus, that is the solution.  Still find it odd that a DateTime query would simply ignore any time zone information when there is available a DateTimeKind.Utc and various local times, but this does cater for that.