How to create a self-signed certificate using PRINTABLE_STRING, IA5STRING or BMPSTRING as certificate fields?

Question: I need to know how I can make sure certificate fields of my self-signed certificate, like subject common name and issuer common name, is encoded as PRINTABLE_STRING, IA5STRING or BMPSTRING, but not UTF-8 encoding.
I'm trying to create it using PowerShell cmdlet.
I'm trying to create a self-signed certificate that conforms to these rules.
These are the parameters I found that I think comply with those rules.
New-SelfSignedCertificate -DnsName 'wdac' -CertStoreLocation Cert:\CurrentUser\My\ -Type Codesigning -HashAlgorithm "SHA512" -KeyLength 4096 -KeyAlgorithm RSA
Comment: On my system, by default, that command will use `UTF8STRING` for `commonName` fields (tested by exporting to file, then `openssl.exe asn1parse -in TestCert.cer -i`). You *might* be able to alter what encoding powershell sends, like: https://stackoverflow.com/a/40098904/7411885, but I don't think `PrintableString` is an option there. You may need to generate a custom CSR as a separate step
Comment: Why use OpenSSL if a powershell script will do the same.  Often in older version Windows  (Visual Studio) not all the encryption modes were supported so often people used OpenSSL. Now you do not need to use OpenSSL in these cases.  OpenSSL is used in Linux since there are no Linux methods that create Certificates.
Comment: @Jameschad I think you'll need to dip into dotnet for generating these if you want to avoid openssl. The default encoding for X509/X500 stuff is printable strings, and ADCS tends to force it via templates. Stuff like `$DN = [Security.Cryptography.X509Certificates.X500DistinguishedName]::new('CN=TESTCERT')` seem to generate printable strings unless you feed them a "UseUTF8Encoding" flag. I'm not really familiar with the rest of the steps needed for self-signed certs there though.
Comment: Thank you, I just tried it and it is indeed using `UTF8`, that answer is a bit complicated for me and also I'd need some guidance for custom CSR step. Is it possible to create a certificate with those requirements using OpenSSL?
Comment: @jdweng I understand, and I don't want to use OpenSSL, but as I said in my post, I don't know how to do it with PowerShell. there are .NET APIs for it too but I need help figuring it out. I want to create a self signed certificate that will work for a signed WDAC policy and meets these requirements: https://learn.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/use-signed-policies-to-protect-windows-defender-application-control-against-tampering
Comment: @Cpt.Whale I tried the answer from the question you linked to, that didn't work. Also here is a way to find out the encoding of the certificate fields natively `certutil.exe -asn .\cert.cer`
Comment: Read following : https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_signing?force_isolation=true&view=powershell-7.3
Comment: @jdweng I did, so which part of it did you think can help my situation?
Comment: See following : https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_signing?force_isolation=true&view=powershell-7.3#create-a-self-signed-certificate
Answer: You can easily do this using Windows Server (it's free for 180 days and you only need it for 30 mins or less). You can grab the latest Windows server, install it on a Hyper-V VM, create your code signing certificate, set its expiration date to 50 or 100 years so you won't need to repeat this process again.
The certificate generated using the template in Enterprise CA role in Windows server has the correct encoding for the subject and works perfectly with WDAC.
Here is my text-based guide:
https://github.com/HotCakeX/Harden-Windows-Security/wiki/How-to-Create-and-Deploy-a-Signed-WDAC-Policy-Windows-Defender-Application-Control
Here is the video I made based on that text-based guide:
https://www.youtube.com/watch?v=vlu1HGuYPeg


OpenLDAP Invalid Credentials

Question: I'm setting up an OpenLDAP server to authenticate users in a domain on Ubuntu 9.04.
What's interesting/strange is that in the newest version of openldap for Ubuntu, the default is not to use the /etc/ldap/slapd.conf file - instead it stores its configs in cn=config in the database (this has lead to some headaches trying to follow tutorials that specify slapd.conf instead of the newer version).
Whenever I try to add to the database using ldapadd, it returns ldap_bind (49) Invalid Credentials (even when I'm sure I'm using the right password).
The database doesn't have anything in it yet, so starting from scratch isn't a problem, I've just encountered this several times (even after reconfiguring slapd). What's the solution?
Answer: Try specifying "-x" on the commandline.  By default, the LDAP tools use SASL authentication, -x specifies "simple authentication".
Comment: The command I'm using to try to add some example entries in the db:
ldapadd -x -D cn=admin,dc=example,dc=com -W -f example.com.ldif.

-x disables SALS authentication, and -W makes sure it prompts for a the administrator password (which I enter). Still no joy. Any other thoughts?
Comment: Hmm.  I am not familiar with configurations that don't use slapd.conf so I am not entirely sure where to go.  Off the top of my head I would try running slapcat to print out the ldif of the database directly and verify that the rootdn matches what you are entering for your bind.
Answer: I do not know if OpenLDAP returns subcodes on error 49's like Active Directory does.  AD returns a subtype of the error code for bad password, versus bad DN.
Are you confident the DN is correct?
Comment: +1 For coming up with the same answer I figured out. I was using the wrong credentials - should have been using cn=admin,dc=example,dc=com instead of cn=admin,cn=config. Dumb mistake. Easy fix though.

OpenLDAP Invalid Credentials


Facebook não permite a apresentação de posts em iFrames?

Question: Segue uma rotina que busca todos os posts de um determinado usuário via Facebook Graph API, apresenta o horário que foi postado e a mensagem, descrição e o tipo de post numa DIV:
FB.api(
    {
        method: 'fql.query',
        locale: 'pt_BR',
        query: 'SELECT post_id, source_id, message, created_time, type, description, permalink FROM stream WHERE source_id = ' + friend_data[i].id + ' LIMIT 50'
    },
    function(posts){
        if(posts.length>0){
            var divFriendsPost = document.getElementById('friend' + posts[0].source_id);
            var friendPosts = '';
            for(var j=0; j < posts.length ; j++) {
                var d = new Date(0);
                d.setUTCSeconds(posts[j].created_time);
                dateFormat = [d.getDate(), (d.getMonth()+1), d.getFullYear()].join('/');
                timeFormat = [d.getHours(), d.getMinutes(), d.getSeconds()].join(':');
                if(posts[j].permalink != null && posts[j].permalink != '') {
                    friendPosts += '';
                }
                friendPosts += '
';
                friendPosts += '
';
                friendPosts += '
' + dateFormat + '
';
                friendPosts += '
' + timeFormat + '
';
                friendPosts += '
';
                friendPosts += '
';
                friendPosts += '
' + posts[j].message  + '(' + posts[j].type + ')
';
                friendPosts += '
' + posts[j].description +'
';
                friendPosts += '
';
                friendPosts += '
';
                if(posts[j].permalink != null && posts[j].permalink != '') {
                    friendPosts += '
';
                    friendPosts += '';
                    friendPosts += '
';
                    friendPosts += '';
                }
            }
            var newNode = document.createElement('div');
            newNode.innerHTML = friendPosts;
            divFriendsPost.appendChild(newNode);
        }
    }
);

O problema é que não basta apresentar estas informações na DIV, pois na maioria das vezes o post é um compartilhamento ou publicação de fotos, por exemplo.
Tive a ideia de colocar o link (permalink) num iframe sob a DIV, mas o console retorna o seguinte erro:

Refused to display 'https://www.facebook.com/...' in a frame because
  it set 'X-Frame-Options' to 'DENY'.

Eu acredito que o facebook bloqueie este tipo de ação.
Como resolver este problema, ou seja, simplesmente mostrar somente o post (sem nada que o cerca na página do facebook) sob a DIV?
Answer: Isso ocorre porque ao acessar o HTML da página, tem o seguinte header
x-frame-options:DENY

Isso explicitamente diz para o navegador que não quer que o site seja visto dentro de um Iframe. É comum fazer isso para obrigar as pessoas a acessarem o site pela URL do site, e não pela url de outros e, claro, por questões de segurança, e evitar, por exemplo, que seja fácil roubar senhas ao tentar fazer a pessoa pensar que ela realmente está no Facebook.
A solução para você resolver isso é usar a API oficial do Facebook. Eles já disponibilizam botões de likes, comentários e afins. Isso que você está fazendo, aliás, se não for via uma API própria, é explicitamente proibido nos termos de uso do Facebook.
Comment: Simplificando: com exceção das páginas que já existem na API, como botões e comentários, nenhuma página do Facebook abre em um iframe.
Comment: Carregar qualquer url de facebook.com que não seja uma API via Iframe é proibido. Visite https://developers.facebook.com/ e veja tudo que eles autorizam e até facilitam pra você fazer
Comment: É proibido mostrar um post numa página própria ou é proibido mostrar o link num iframe?
Comment: Eu acho que ele só quer pegar os textos dos posts e exibir, mas eu não entendi direito a dúvida, também.
Comment: Sim, _é proibido_. Fazer algo que vai contra os termos de uso do facebook, se detectado, pode bloquear seu acesso e todas as contas que você usa. E pode levar a cadeia em casos mais extremos. Exemplo foi um desenvolvedor que fez um crawler que adicionava pessoas  e foi a publico admitindo isso e só não foi preso porque ele já tinha ajudado a descobrir falhas de segurança antes.
Comment: Felipe, eu possuo inúmeros perfis e fan pages que controlo o conteúdo. Entrar uma a uma dá um trabalho gigantesco. Por isso, estou fazendo esta aplicação para mostrar todos os posts por ordem de data. Existe alguma outra forma de se fazer isso?
Comment: Alexandre isso que está pedindo e outra pergunta. Não faça ela aqui, crie um tópico novo
Answer: Você não precisa criar um iFrame com o post do Facebook. Você pode usar o Facebook Embedded Posts.
Ele cria automaticamente um iFrame com o post que você deseja. Basta passar o link.


Solving Trigonometric Equations

Question: Solve $x$ in the equation $2\cos3x + \cos2x + 1= 0$, where $0 \leq x \leq 2\pi$.
I tried breaking up the triple angle, into a cos compound angle. But, im not sure what to do next.
$2\cos x \cos2x - 2\sin x \sin2x + \cos2x+1=0$
Comment: If you keep going you can obtain a cubic in $\cos(x)$. Specifically, use $\sin(2x)=2\sin(x)\cos(x)$ and $\cos(2x) = 2\cos^2(x)-1$
Answer: Using Prove $\cos 3x =4\cos^3x-3\cos x$ and Double-Angle Formula, we get $$2(4c^3-3c)+2c^2-1+1=0\iff2c(4c^2+c-3)=0$$ where $c=\cos x$
Can you take it from here?
Comment: @user146001, How about this?

Solving Trigonometric Equations


The integral is zero by using a theoretical result

Question: Set $F(x)=|u(x)|^2\cdot x$, where $u\in L^2(\mathbb{R}^N)$, then
$$
\begin{split}
\mathrm{div} \ F(x)
 &= \nabla |u(x)|^2 \cdot x\ +\  |u(x)|^2 \mathrm{div} (x)\\
 &= \overline{u}(x)\nabla u(x)+  u(x)\nabla \overline{u} (x)+N   |u(x)|^2
\end{split}
$$
I want to assert that:
$$
\int_{\mathbb{R}^N} \mathrm{div}\ F(x)\ dx=0
$$
using a theoretical result that states if $f\in L^1(\mathbb{R}^N)$ and if $\partial f/\partial x_1\in L^1(\mathbb{R}^N)$, then
$$
\int_{\mathbb{R}^N} \frac{\partial f}{\partial x_1}(x)\ dx=0
$$
So it seems I must find a function $G\in L^1(\mathbb{R}^N)$ with that $  \partial G/\partial x_1 =\mathrm{div}\ F $. Any idea of how can I find such  function $G$? Thanks in advance.
Comment: Please clarify: $L^2(\mathbb{R}^N$ means square integrable function?
Comment: Yes, exactly. The square integrable functions over Rn
Answer: Not sure what is the "theoretical result" you mention.
This seems like a question about the Divergence Theorem, which states:
$$
\int_{\Omega} \mathrm{div}\ F(x)\ dV = \oint_{\partial\Omega} F.\hat{n}.dS
$$
Now, let $\Omega=B_r(0)$, the ball centered around zero with radius $r$. Then:
$$
\int_{\mathbb{R}^N} \mathrm{div}\ F(x)\ dx = \lim_{r\to \infty}\int_{B_r(0)} \mathrm{div}\ F(x)\ dV
$$
Now let's try to find:
$$
\oint_{\partial B_r(0)} F.\hat{n}.dS =\oint_{\partial B_r(0)} |u(x)|^2\cdot x\cdot \frac{x}{r} dS = \oint_{\partial B_r(0)} |u(x)|^2 \frac{|x|^2}{r} dS
$$
Now, I'm temped to ask if you have more assumptions for $u(x)$.
Comment: No, u is just L^2 on Rn
Comment: But divergence theorem cannot be applied for L^2- function. You need more regularity... anyway if it is applied you had to prove now that the last integral tends to 0 as r tends to infinity... and this is sth not easy, isn't it? Also i think that a diferente approach would be this https://math.stackexchange.com/questions/3167377/proof-by-a-density-argument
Comment: Well, if u is $H^1(\mathbb{R}^N)$ then you know how to conclude?
Comment: Could you please clarify that notation as well? What does $H^1$ stands for?
Comment: That is the set of $L^2$-functions $u$ with first order (weak) derivative, $\partial u/ \partial x_i$ also in $L^2$ for all $i=1,...,N$
Answer: This puzzled me for a while... Notice that:
For $N=1$ we have:
$$
\int_\mathbb{R} \text{div} F(x)dx = \int_\mathbb{R} \frac{\partial F(x)}{\partial x}dx = \lim_{r\to \infty} F(r)-F(-r)
$$
Naturally, because $u(x)$ is square-integrable, we have $\lim_{r\to \infty} u(r)=\lim_{r\to \infty} u(-r) =0$. So there is a gap I cannot fill yet to assert that  $\lim_{r\to \infty} F(r)=0$.  This would demonstrate that for $N=0$ the result is indeed zero.
For higher dimensions:
$$
\int_\mathbb{R^N} \text{div} F(x)dx = \int_\mathbb{R^N} \sum_{i=1}^N\left( \frac{\partial F(x)}{\partial x_i} \right) dx_1dx_2 \cdots dx_N
$$
Swapping integration and summation and reordering each integral with the variable ebign derived:
$$
\int_\mathbb{R^N} \text{div} F(x)dx =  \sum_{i=1}^N \int_\mathbb{R^{N-1}}\left( \int_\mathbb{R}\frac{\partial F(x)}{\partial x_i} dx_i\right) dx_1dx_2 \cdots  dx_{i-1}dx_{i+1}  \cdots dx_N
$$
Then each term in parenthesis is zero by the same logic. Hence the whole integral is zero.


What's the Vue lifecycle chronology between components?

Question: Let's say I have a <router-view> showing one component (A) and through a <router-link> this component will be replaced by another one (B).
Both components have their own beforeCreate and beforeDestroy hooks. I'd expect that if I navigated from A to B the sequence of events would be:

A.beforeDestroy
B.beforeCreate

But after doing some tests it appears to be the exact opposite: B.beforeCreate is always called before A.beforeDestroy.
Is that correct? And if it's correct, why is it this way? Doesn't make sense to me...
In my case all those hooks interact with some common data, so I'm facing race conditions here... Any suggestion on how to deal with that? I need to get some things done before creating B that cannot be started before destroying A...
Comment: as [Vue Github for patch.js](https://github.com/vuejs/vue/blob/dev/src/core/vdom/patch.js#L685) and [VUe Github for lifecycle](https://github.com/vuejs/vue/blob/dev/src/core/instance/lifecycle.js#L50), Vue will create new vnode first, then remove old vnode at the end. the problem you described, probably uses [vue-router navigator](https://router.vuejs.org/guide/essentials/navigation.html) will be one option.
Answer: Before the previous component is destroyed, the next component will be created first.
The purpose is obviously to avoid flickering as the view transitions from the previous component to the next component.
If the behavior you wanted is to make sure that a code should be executed always after the beforeDestroy and not before, you should use the mounted or beforeMount lifecycle hook.


How can we discern the melody of a piece of music in variations of that piece?

Question: Example: Mozart's Twelve Variations on "Ah vous dirai-je, Maman" ("Twinkle, Twinkle, Little Star")

Even though each version sounds drastically different, you can always tell what the melody is. And if you'd never heard this piece before, you could still pick the melody out from the music around it. How is that? Is it something about the way music is written to specifically make the melody discernible?
Answer: Note: I'm only answering from experience here. I'm also answering more from a classical music background.
Part of this is probably psychological - if we already know the melody, it probably makes it easy for us to then pick out the melody even if it has been embellished in some form or another, such as in the Mozart piece you gave as an example.
On the flip side, part of this ability is probably due to performer technique and ability, after the performer has been able to pick out such embellished melodies. For instance, in the piano interlude in Schubert's "Im Fruehling", after "und sie im Himmel sah", the right hand "appeggiations" (for lack of a better term) are probably supposed to mimic the piano melody at the beginning. The actual sheet music in those four measures doesn't really contain anything indicating that the notes comprising the original melody are to be discernible, other than the fact that the A at the very end of the melody is held down (mirroring the original version of the melody).
Rather, the listener and performer are able to distinguish and make discernible the melody in that short passage from 1) noticing the similarities between that passage and the original melody (in both parties) and 2) the pianist thus being able to put slightly more stress on the notes comprising the original melody and make the similarities more prominent.


How do I find the expected value of F(isher)-distribution

Question: $E(F)=\int xf_{k,m}dx$ where $f_{k,m}(t) = \Gamma(t)=\frac{\Gamma((k+m)/2)}{\Gamma (k/2)\Gamma(m/2)}k^{k/2}m^{m/2}t^{k/2 - 1}(m+kt)^{-(k+m)/2}$.
How do you find $E(F)$? Say you have to convert $x*f(k,m)$ to $C * f(k',m')$ where $f(k',m')$ is a pdf itself, which leaves $E(F)=C$ (which is$\frac{m}{m-2}$).
Answer: One elementary way to obtain this result is to integrate the survival function.  I will prepare the way with some notation and definitions, and then will integrate the survival function by changing the order of a double integral.

The cumulative distribution function of $F$ is
$$F_{k,m}(x) = I\left(\frac{x}{x + \lambda}; k/2, m/2\right)$$
where $\lambda = m/k$ and $I$ is the regularized incomplete Beta function
$$I(x; \alpha, \beta) = \frac{1}{B(\alpha, \beta)}\int_0^x t^{\alpha-1}(1-t)^{\beta-1}dt.$$
(For notational convenience, I will continue to equate $\alpha$ with $k/2$ and $\beta$ with $m/2$.)  Notice that because $I$ is a CDF, its full integral must be unity:
$$1 = I(1;\alpha,\beta) = \frac{1}{B(\alpha, \beta)}\int_0^1 t^{\alpha-1}(1-t)^{\beta-1}dt.$$
If you wish, then, you may take $B(\alpha,\beta)$ to be defined by the integral on the right hand side.  What will be important in the sequel is the fact that
$$\frac{B(\alpha+1,\beta-1)}{B(\alpha,\beta)} = \frac{\alpha}{\beta-1}$$
for all $\alpha \gt 0$ and $\beta \gt 1$.  You can prove this in many ways (such as integration by parts).
Integration by parts demonstrates that the expectation of any positive distribution $F$ is the integral of its survival function $1-F$:
$$E[F] = \int_0^\infty x\, dF(x) = \lim_{t\to\infty}\left(t(1-F(t)) + \int_0^t (1-F(t)) dt\right) = \int_0^t (1-F(t)) dt$$
(provided the expectation is finite).  Applying this to the Fisher-Snedecor distribution and changing the order of integration gives
$$\eqalign{
E[F_{k,m}]& = \int_0^\infty \left(1 - I\left(\frac{x}{x + \lambda}; \alpha,\beta\right)\right) dx \\
&= \int_0^\infty \frac{1}{B(\alpha, \beta)}\int_{x/(x+\lambda)}^1 t^{\alpha-1}(1-t)^{\beta-1}dt\,dx \\
&= \frac{1}{B(\alpha, \beta)}\int_0^\infty  t^{\alpha-1}(1-t)^{\beta-1}\left(\int_0^{\lambda t/(1-t)}dx\right)dt \\
&= \frac{\lambda}{B(\alpha, \beta)}\int_0^1  t^{\alpha}(1-t)^{\beta-2}dt \\
&= \frac{\lambda}{B(\alpha, \beta)}\int_0^1  t^{\alpha}(1-t)^{\beta-2}dt \\
&= \frac{\lambda B(\alpha+1, \beta-1)}{B(\alpha,\beta)} \\
&= \lambda \frac{\alpha}{\beta-1} = \frac{m}{k}\frac{k/2}{m/2-1}=\frac{m}{m-2}.
}$$
(Each step is simple and elementary or has been previously demonstrated.)  The penultimate line required $\beta-1 \gt 0$; that is, $m \gt 2$.  It is clear that the last integral (on the antepenultimate line) diverges when $m \le 2$.


How to TASKKILL a specific "program.exe" on a machine with many "program.exe" running

Question: On my server i run a batch that call "program.exe", this program processes some data and close. If it doesn't close i will need to kill it.
The problem is that i could have many "program.exe" on the same machine but i have to kill only mine. Is it possible?
The batch file is called from an ASP page and it is launched with LocalSystem user privileges and does the following:
c:
cd \infos_a\exe
set infos=c:\infos_a\files\paolor
start /LOW program.exe #C:\inetpub\wwwroot\infospnt\bat\01\

if program.exe run more than 30sec it must be killed
Comment: What makes it *yours*? Is it the only one running under your logon credentials .. or ... ?
Comment: You can kill a single one using Taskkill it by process id (PID) instead of by name. How you identify which one, though...
Comment: execute `wmic process where "Caption='program.exe'" get /format:value` and see which attributes you can use to filter the one you want to kill.
Comment: May be a solution in vbscript ==>  Killer-Selector.vbs
Comment: maybe `tasklist /v` is helpful - depends on your exe...
Answer: Taskkill help gives an example
taskkill /im program.exe /fi "Username eq MyName"


Conserve correlation with simulate data

Question: let me explain you the process, I have random variables in a matrix $X_1$: $260\times3$.
I have my correlation matrix $\rho_1$: $3\times3$ from my matrix $X_1$.
Now I use a Cholesky decomposition and I create $X_2$ from the covariance in $X_1$.
As expected correlation $\rho_2$ of $X_2$ and $\rho_1$ of $X_1$ are very close.
When I create $X_3$ as the $X_1$ in which the first column has been replaced by the first one in $X_2$, the correlation matrix is very far from $\rho_1$ and $\rho_2$.
1) I don't really get why as my correlation matrix are very close between $X_1$ and $X_2$ so I was expected $X_3$ to have a correlation close to the two other ?
2) Is there a way to perform this simulation / using Cholesky to in the end keep the two last column of $X_1$ and recreate the first one while keeping the correlation (or very close) of $X_1$ ?
Thank you for your help
Comment: If your sample is rank dependent, (you said you set X3=X1), then there's no way to estimate the covariance matrix without having some form of quasi-inverse of the precision matrix. Depending on what linear algebra package you use, setting the correlation of two identical columns to 0 can be one valid form of a quasi inverse matrix.
Answer: If I understand correctly you want to create only a new first column whose population correlation with the 2 later columns given those later column values is equal to the sample correlations with the original first column. I will assume you want to continue to
 use Cholesky rather than any other choice of decomposition.

Reorder your original variables so the first column is last in the covariance matrix.
Find the Cholesky decomposition of this covariance matrix.
Now simulate only the last variable given the other two

That's your new first variable in the original framework.

Conserve correlation with simulate data


Find a vector w that is not in the image of T.

Question: Let $T\colon \mathbb{R}^2\to\mathbb{R}^3$ be a linear transformation defined by
$$T(x,y) = (10x+2y, -10x+10y, -8x-6y)$$
Find a vector $w$ that is not in the image of $T$.
I just really have no clue on where to start with this. Any ideas?
Answer: $T(x,y)=(10x+2y,−10x+10y,−8x−6y)=x(10,-10,-8)+y(2,10,-6)$. So the image of $T$ is the plane spanned by $(10,-10,-8)$ and $(2,10,-6)$. Any vector not in this plane will not be in the image, for example the cross product of the spanning vectors $(10,-10,-8)\times(2,10,-6)$.
Comment: What if you have 3 vectors for T instead of 2?
Comment: I don't think that is a good solution as it doesn't scale. Rather, row-reduce and solve $av_1 +av_2+av_3=0$ where $v_3$ is an arbitrary $(x,y,z)$ that you're trying to find. You'll get a restriction like $x+y=0$ where that restriction must be satisfied to preserve linear independence. Then use that restriction to find the appropriate linearly independent vector.
Answer: Well for a vector $(a,b,c)$ to lie in the image of $T$, there must be values $x$ and $y$ such that:
$10x+2y = a$
$-10x+10y = b$
$-8x-6y = c$
Notice in particular that we cannot have $a,b,c$ equal and non-zero since then the equations would have no solutions (check this).
So any vector such as $(1,1,1)$ will do.
Answer: Hint: First find a basis for the image of $T$
Comment: @Linax: What are the basis for $\mathbb R^2$?


How do I define the inverse of this function?

Question: Consider the following piecewise surjective function:
$$
f(x) = \begin{cases}
x + 19 & x < 0 \\
x & x \geq 0
\end{cases}
$$
We have the following restriction on the domain:

$x \in \{ -16,-15,-14,-9,-8,-7,-6,-2,-1,0,1,2,6,7,8,9,14,15,16 \}$

Hence, the codomain has the following values:

$f(x) \in \{ 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18 \}$

Naively, we can define the inverse as follows:
$$
g(y) = \begin{cases}
y - 19 & y \in \{ 3,4,5,10,11,12,13,17,18 \} \\
y & y \in \{ 0,1,2,6,7,8,9,14,15,16 \}
\end{cases}
$$
Is there a better way to determine which set $y$ is an element of? Unfortunately, the two sets are non-contiguous and the contiguous subsets are of variable sizes. Otherwise, my first instinct was to use modular arithmetic to define a closed-form expression. I'm interested in a general solution because I have a whole family of such functions that I need to find the inverse of.

To explain how I defined the domain, consider the following vectorization of a hexagonal map:
<code>        16
    15      09
14      08      02
    07      01
06      00      13
    18      12
17      11      05
    10      04
        03
</code>
I've already explained what this means at length in this linked answer. The general idea is to convert a two-dimensional hexagonal map into a one-dimensional array. The numbering in the above diagram denotes the ordering of hexagonal cells in the one-dimensional array. It's arranged in a way that enables neighbors of any given cell (including neighbors that wraparound the edges of the map) to be computed easily using modular arithmetic.
Now, I'd like to create a bijection between the above indices and the following axial coordinates:
<code>                    +0,+2
          -1,+2               +1,+1
-2,+2               +0,+1               +2,+0
          -1,+1               +1,+0
-2,+1               +0,+0               +2,-1
          -1,+0               +1,-1
-2,+0               +0,-1               +2,-2
          -1,-1               +1,-2
                    +0,-2
</code>
We can convert the axial coordinates into numbers that are congruent to the corresponding indices $\bmod{19}$ (the total number of cells in the hexagonal map) using the following function:
$$
fromAxial(x, y) = x + 8y
$$
This converts the axial coordinates into the following values (which is how we get our domain). Notice that only the values at the bottom are negative and that they mirror the values on the top:
<code>            +16
      +15         +09
+14         +08         +02
      +07         +01
+06         +00         -06
      -01         -07
-02         -08         -14
      -09         -15
            -16
</code>
We can convert these values back into axial coordinates using the following functions:
$$
\begin{align}
toAxialX(v) &= ((v + 2) \bmod 8) - 2 \\
toAxialY(v) &= \lfloor (v + 2) \div 8 \rfloor
\end{align}
$$
Now, to convert axial coordinates to the corresponding indices we use $f \circ fromAxial$ where $f$ is the function I defined in the beginning. Equivalently, we could write $fromAxial(x, y) \bmod 19$.
Similarly, to convert indices back to axial coordinates we use $toAxialX \circ g$ and $toAxialY \circ g$ respectively where $g$ is the inverse of $f$. Note that these functions are currently defined for a hexagonal map of side length $3$. For different sized hexagonal maps we'd use similar functions with only certain values changing. Hence, I'm looking for a general solution to define the inverse of $f$.
Comment: Was the domain chosen at random?  (Subject to forming a bijection of course.)  If so, there is unlikely to be any simple general answer to your question.  If there was a reason for choosing this particular domain, maybe you could give details, then you would have a better chance of getting a useful answer.
Comment: @David No, the domain was not chosen at random. I edited my answer and added details. However, I'm not sure whether it'll be useful towards answering my question. Still, I hope that it does elucidate it.
Answer: The simplest way to solve this problem is by converting to cube coordinates instead of axial coordinates:
<code>                                +0,+2,-2
                -1,+2,-1                        +1,+1,-2
-2,+2,+0                        +0,+1,-1                        +2,+0,-2
                -1,+1,+0                        +1,+0,-1
-2,+1,+1                        +0,+0,+0                        +2,-1,-1
                -1,+0,+1                        +1,-1,+0
-2,+0,+2                        +0,-1,+1                        +2,-2,+0
                -1,-1,+2                        +1,-2,+1
                                +0,-2,+2
</code>
Cube coordinates are the same as axial coordinates, except that they have a z-coordinate whose values are the negated sum of the other two coordinates (i.e. $z = -x - y$). This allows us to detect invalid coordinates easily because they will be off the map. We can use the following distance formula to test for them:
$$
distance(x, y, z) = \frac{\lvert x \rvert + \lvert y \rvert + \lvert z \rvert}{2}
$$
Converting cube coordinates to indices is the same as converting axial coordinates to indices:
$$
fromCube(x, y, z) = (x + 8y) \bmod 19
$$
Converting indices back to cube coordinates is also the same:
$$
\begin{align*}
toCube(i) &= (x, y, z) \\
\text{where}~x &= ((i + 2) \bmod 8) - 2 \\
y &= (i - x) \div 8 \\
z &= -x - y
\end{align*}
$$
However, we now include a distance check to ensure that indices are converted to the correct coordinates:
$$
fromIndex(i) = \begin{cases}
toCube(i - 19) & distance(toCube(i)) > 2 \\
toCube(i) & distance(toCube(i)) \leq 2
\end{cases}
$$
This can be generalized to hexagonal maps of different sizes by simply changing certain values.


How can I get alerted when auto-growth occurs on a SQL Server database?

Question: Our SharePoint databases are set to the (nonsensical) 1MB default autogrow out-of-the-box, and I need to "convince" our application owner that this is wrong. Is there a means to monitor the autogrow activity of SQL Server?
I would like to be able to report how frequently this activity is occuring with the 1MB setting.
Comment: Yeah, that's a drag to be sure.
Comment: o man, so your entire content database is locking up every time you need another 1MB storage?
Answer: Log file autogrowths are reported in the SQL logs or the Application event log.  You can also use things like SQL Trace or SQL Profiler to monitor SQL events.  Here's a MSDN article that discusses monitoring SQL events.
EDIT: In the Application event log look for Event ID 5144 for autogrowth cancel events and 5145 for successful/completed autogrowth events.
EDIT2: To look for db log file auogrowth events in your SQL log you can use this:
EXEC xp_readerrorlog 0,1,'autogrow'

Increment the 0 in order to have xp_readerrorlog use archived error log files.  0 to (n-1) where n is the number of error log files you have.
You can also set up event notifications for an autogrow event.  Something like this:
CREATE EVENT NOTIFICATION data_file_autogrow_notifier
ON DATABASE
FOR DATA_FILE_AUTO_GROW
TO SERVICE 'NotifyAutogrow', 'current database' ;

or for the log file:
CREATE EVENT NOTIFICATION log_file_autogrow_notifier
ON DATABASE
FOR LOG_FILE_AUTO_GROW
TO SERVICE 'NotifyAutogrow', 'current database' ;

Where NotifyAutogrow is the name of a Service Broker instance.  More info here.  You would need to set this service up for your environment.
Comment: "Autogrowths are reported in the SQL logs or the Application event log."  I don't see this happening in either place.  Do you know how to enable this logging?
Comment: It's just always enabled, you can't disable SQL logging.  If you're not seeing autogrowth events then chances are you haven't had any happen in the timeframe that your log covers.  See the edit to my answer for a sql you can use to look for the autogrowth in your SQL log.
Comment: I created a database with 2mb of space and then imported into it using ssis.  The size was increased to 84mb at 1mb autogrowths.  Thanks for the code, but it didn't return any rows.
Comment: And on our prod server the only entry I see is this (I would expect more): Autogrow of file 'templog' in database 'tempdb' was cancelled by user or timed out after 2453 milliseconds.  Use ALTER DATABASE to set a smaller FILEGROWTH value for this file or to explicitly set a new file size.
Comment: ...sorry for wasting your time on the logging of data file autogrowths there.  What I was looking at on my server log was just someone's typo in the filename and was an entry for a db log file.  I guess for data files it's up to trace events or clever use of system stored procedures to monitor file sizes over time.
Answer: As further ammunition for you, checkout this blog post I did which discusses data file auto-growth: Importance of data file size management.
Answer:
It's just always enabled, you can't disable SQL logging. If you're not
  seeing autogrowth events then chances are you haven't had any happen
  in the timeframe that your log covers. See the edit to my answer for a
  sql you can use to look for the autogrowth in your SQL log.

It depends on what you're talking about.
In my experience, SQL Server did not log autogrow to ERRORLOG as has been suggested, instead it's logged in the default trace, and the default trace can be disabled and enabled.
To check if it's enabled, see:
select name, value_in_use
from sys.configurations
where name='default trace enabled'

In case it's disabled, you can enable it:
sp_configure 'default trace enabled', 1
go

Don't forget to run RECONFIGURE afterwards.
To check for autogrow events you can use:
SELECT databaseid, filename, SUM(IntegerData*8) AS Growth, Duration, StartTime
FROM ::fn_trace_gettable('C:\SQL Server\MSSQL10_50.INSTANCENAME\MSSQL\Log\log_4.trc', default)
WHERE EventClass = 92 OR EventClass = 93
GROUP BY databaseid, filename, IntegerData, Duration, StartTime

Where the parameter to fn_trace_gettable is the name of the current (or archived) trace.
You can find the path for the current trace as follows:
SELECT path FROM sys.traces WHERE is_default = 1;

Answer: Log file autogrowths are reported in the SQL logs or the Application event log. You can also use things like SQL Trace or SQL Profiler to monitor SQL events.


My server goes offline when I start my OpenVPN service

Question: I currently have a VPS with DigitalOcean and setup a OpenVPN following this tutorial:
https://www.digitalocean.com/community/tutorials/how-to-setup-and-configure-an-openvpn-server-on-centos-6
and this:
http://www.unixmen.com/setup-openvpn-server-client-centos-6-5/
When I type "service openvpn start" in the SSH console, my server immediately goes offline. I can still access my servers SSH through DigitalOcean's online SSH client. From there I checked if openvpn is running properly and everything seems to be ok. I checked my ifconfig and that also seems to be ok. I'm kind of lost at this point. Is this normal?
EDIT:
<code>   Jul 24 04:40:53 designfully openvpn[18186]: 188.8.131.52:37556 Control Channel: TLSv1, cipher TLSv1/SSLv3 DHE-RSA-AES256-SHA, 2048 bit RSA
    Jul 24 04:40:53 designfully openvpn[18186]: 22.214.171.124:37556 [client] Peer Connection Initiated with [AF_INET]188.8.131.52:37556
    Jul 24 04:40:53 designfully openvpn[18186]: client/188.8.131.52:37556 MULTI_sva: pool returned IPv4=10.8.0.6, IPv6=(Not enabled)
    Jul 24 04:40:53 designfully openvpn[18186]: client/18.104.22.168:37556 MULTI: Learn: 10.8.0.6 -> client/126.96.36.199:37556
    Jul 24 04:40:53 designfully openvpn[18186]: client/220.127.116.11:37556 MULTI: primary virtual IP for client/188.8.131.52:37556: 10.8.0.6
    Jul 24 04:40:53 designfully openvpn[18175]: event_wait : Interrupted system call (code=4)
    Jul 24 04:40:53 designfully openvpn[18175]: SIGTERM[hard,] received, process exiting
    Jul 24 04:40:53 designfully openvpn[18186]: event_wait : Interrupted system call (code=4)
    Jul 24 04:40:53 designfully openvpn[18186]: /sbin/ip route del 10.8.0.0/24
    Jul 24 04:40:53 designfully openvpn[18186]: ERROR: Linux route delete command failed: external program exited with error status: 2
    Jul 24 04:40:53 designfully openvpn[18186]: Closing TUN/TAP interface
    Jul 24 04:40:53 designfully openvpn[18186]: /sbin/ip addr del dev tun0 local 10.8.0.1 peer 10.8.0.2
    Jul 24 04:40:53 designfully openvpn[18186]: Linux ip addr del failed: external program exited with error status: 2
    Jul 24 04:40:53 designfully openvpn[18186]: SIGTERM[hard,] received, process exiting
    Jul 24 04:40:56 designfully openvpn[18222]: OpenVPN 2.3.2 x86_64-redhat-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [eurephia] [MH] [IPv6] built on Sep 12 2013
    Jul 24 04:40:56 designfully openvpn[18222]: Socket Buffers: R=[124928->131072] S=[124928->131072]
    Jul 24 04:40:56 designfully openvpn[18223]: UDPv4 link local: [undef]
    Jul 24 04:40:56 designfully openvpn[18223]: UDPv4 link remote: [AF_INET]126.96.36.199:1194
    Jul 24 04:40:56 designfully openvpn[18226]: OpenVPN 2.3.2 x86_64-redhat-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [eurephia] [MH] [IPv6] built on Sep 12 2013
    Jul 24 04:40:56 designfully openvpn[18226]: Diffie-Hellman initialized with 2048 bit key
    Jul 24 04:40:56 designfully openvpn[18226]: Socket Buffers: R=[124928->131072] S=[124928->131072]
    Jul 24 04:40:56 designfully openvpn[18226]: ROUTE_GATEWAY 220.127.116.11/255.255.255.0 IFACE=eth0 HWADDR=04:01:20:b9:d8:01
    Jul 24 04:40:56 designfully kernel: tun0: Disabled Privacy Extensions
    Jul 24 04:40:56 designfully openvpn[18226]: TUN/TAP device tun0 opened
    Jul 24 04:40:56 designfully openvpn[18226]: TUN/TAP TX queue length set to 100
    Jul 24 04:40:56 designfully openvpn[18226]: do_ifconfig, tt->ipv6=0, tt->did_ifconfig_ipv6_setup=0
    Jul 24 04:40:56 designfully openvpn[18226]: /sbin/ip link set dev tun0 up mtu 1500
    Jul 24 04:40:56 designfully openvpn[18226]: /sbin/ip addr add dev tun0 local 10.8.0.1 peer 10.8.0.2
    Jul 24 04:40:56 designfully openvpn[18226]: /sbin/ip route add 10.8.0.0/24 via 10.8.0.2
    Jul 24 04:40:56 designfully openvpn[18234]: GID set to nobody
    Jul 24 04:40:56 designfully openvpn[18234]: UID set to nobody
    Jul 24 04:40:56 designfully openvpn[18234]: UDPv4 link local (bound): [undef]
    Jul 24 04:40:56 designfully openvpn[18234]: UDPv4 link remote: [undef]
    Jul 24 04:40:56 designfully openvpn[18234]: MULTI: multi_init called, r=256 v=256
    Jul 24 04:40:56 designfully openvpn[18234]: IFCONFIG POOL: base=10.8.0.4 size=62, ipv6=0
    Jul 24 04:40:56 designfully openvpn[18234]: ifconfig_pool_read(), in='client,10.8.0.4', TODO: IPv6
    Jul 24 04:40:56 designfully openvpn[18234]: succeeded -> ifconfig_pool_set()
    Jul 24 04:40:56 designfully openvpn[18234]: IFCONFIG POOL LIST
    Jul 24 04:40:56 designfully openvpn[18234]: client,10.8.0.4
    Jul 24 04:40:56 designfully openvpn[18234]: Initialization Sequence Completed
    Jul 24 04:40:59 designfully openvpn[18234]: 18.104.22.168:59378 TLS: Initial packet from [AF_INET]184.108.40.206:59378, sid=d3e62c34 63ae7ffd
    Jul 24 04:40:59 designfully openvpn[18223]: TLS: Initial packet from [AF_INET]188.8.131.52:1194, sid=863e093f df2c985a
    Jul 24 04:40:59 designfully openvpn[18223]: VERIFY OK: depth=1, C=US, ST=MI, L=Macomb, O=SimplyJordan, OU=server, CN=SimplyJordan CA, name=EasyRSA, email@example.com
    Jul 24 04:40:59 designfully openvpn[18223]: VERIFY OK: nsCertType=SERVER
    Jul 24 04:40:59 designfully openvpn[18223]: VERIFY OK: depth=0, C=US, ST=MI, L=Macomb, O=SimplyJordan, OU=server, CN=server, name=EasyRSA, firstname.lastname@example.com
    Jul 24 04:40:59 designfully openvpn[18234]: 18.104.22.168:59378 VERIFY OK: depth=1, C=US, ST=MI, L=Macomb, O=SimplyJordan, OU=server, CN=SimplyJordan CA, name=EasyRSA, firstname.lastname@example.com
    Jul 24 04:40:59 designfully openvpn[18234]: 18.104.22.168:59378 VERIFY OK: depth=0, C=US, ST=MI, L=Macomb, O=SimplyJordan, OU=server, CN=client, name=EasyRSA, email@example.com
    Jul 24 04:40:59 designfully openvpn[18234]: 18.104.22.168:59378 Data Channel Encrypt: Cipher 'BF-CBC' initialized with 128 bit key
    Jul 24 04:40:59 designfully openvpn[18234]: 22.214.171.124:59378 Data Channel Encrypt: Using 160 bit message hash 'SHA1' for HMAC authentication
    Jul 24 04:40:59 designfully openvpn[18234]: 220.127.116.11:59378 Data Channel Decrypt: Cipher 'BF-CBC' initialized with 128 bit key
    Jul 24 04:40:59 designfully openvpn[18234]: 188.8.131.52:59378 Data Channel Decrypt: Using 160 bit message hash 'SHA1' for HMAC authentication
    Jul 24 04:40:59 designfully openvpn[18223]: Data Channel Encrypt: Cipher 'BF-CBC' initialized with 128 bit key
    Jul 24 04:40:59 designfully openvpn[18223]: Data Channel Encrypt: Using 160 bit message hash 'SHA1' for HMAC authentication
    Jul 24 04:40:59 designfully openvpn[18223]: Data Channel Decrypt: Cipher 'BF-CBC' initialized with 128 bit key
    Jul 24 04:40:59 designfully openvpn[18223]: Data Channel Decrypt: Using 160 bit message hash 'SHA1' for HMAC authentication
    Jul 24 04:40:59 designfully openvpn[18223]: Control Channel: TLSv1, cipher TLSv1/SSLv3 DHE-RSA-AES256-SHA, 2048 bit RSA
    Jul 24 04:40:59 designfully openvpn[18223]: [server] Peer Connection Initiated with [AF_INET]18.104.22.168:1194
    Jul 24 04:40:59 designfully openvpn[18234]: 18.104.22.168:59378 Control Channel: TLSv1, cipher TLSv1/SSLv3 DHE-RSA-AES256-SHA, 2048 bit RSA
    Jul 24 04:40:59 designfully openvpn[18234]: 126.96.36.199:59378 [client] Peer Connection Initiated with [AF_INET]220.127.116.11:59378
    Jul 24 04:40:59 designfully openvpn[18234]: client/126.96.36.199:59378 MULTI_sva: pool returned IPv4=10.8.0.6, IPv6=(Not enabled)
    Jul 24 04:40:59 designfully openvpn[18234]: client/18.104.22.168:59378 MULTI: Learn: 10.8.0.6 -> client/188.8.131.52:59378
    Jul 24 04:40:59 designfully openvpn[18234]: client/184.108.40.206:59378 MULTI: primary virtual IP for client/22.214.171.124:59378: 10.8.0.6
    Jul 24 04:41:01 designfully openvpn[18223]: SENT CONTROL [server]: 'PUSH_REQUEST' (status=1)
    Jul 24 04:41:01 designfully openvpn[18234]: client/126.96.36.199:59378 PUSH: Received control message: 'PUSH_REQUEST'
    Jul 24 04:41:01 designfully openvpn[18234]: client/18.104.22.168:59378 send_push_reply(): safe_cap=940
    Jul 24 04:41:01 designfully openvpn[18234]: client/184.108.40.206:59378 SENT CONTROL [client]: 'PUSH_REPLY,redirect-gateway def1 bypass-dhcp,dhcp-option DNS 188.8.131.52,dhcp-option DNS 184.108.40.206,route 10.8.0.1,topology net30,ping 10,ping-restart 120,ifconfig 10.8.0.6 10.8.0.5' (status=1)
    Jul 24 04:41:01 designfully openvpn[18223]: PUSH: Received control message: 'PUSH_REPLY,redirect-gateway def1 bypass-dhcp,dhcp-option DNS 22.214.171.124,dhcp-option DNS 184.108.40.206,route 10.8.0.1,topology net30,ping 10,ping-restart 120,ifconfig 10.8.0.6 10.8.0.5'
    Jul 24 04:41:01 designfully openvpn[18223]: OPTIONS IMPORT: timers and/or timeouts modified
    Jul 24 04:41:01 designfully openvpn[18223]: OPTIONS IMPORT: --ifconfig/up options modified
    Jul 24 04:41:01 designfully openvpn[18223]: OPTIONS IMPORT: route options modified
    Jul 24 04:41:01 designfully openvpn[18223]: OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified
    Jul 24 04:41:01 designfully openvpn[18223]: ROUTE_GATEWAY 22.214.171.124/255.255.255.0 IFACE=eth0 HWADDR=04:01:20:b9:d8:01
    Jul 24 04:41:01 designfully kernel: tun1: Disabled Privacy Extensions
    Jul 24 04:41:01 designfully openvpn[18223]: TUN/TAP device tun1 opened
    Jul 24 04:41:01 designfully openvpn[18223]: TUN/TAP TX queue length set to 100
    Jul 24 04:41:01 designfully openvpn[18223]: do_ifconfig, tt->ipv6=0, tt->did_ifconfig_ipv6_setup=0
    Jul 24 04:41:01 designfully openvpn[18223]: /sbin/ip link set dev tun1 up mtu 1500
    Jul 24 04:41:01 designfully openvpn[18223]: /sbin/ip addr add dev tun1 local 10.8.0.6 peer 10.8.0.5
    Jul 24 04:41:01 designfully openvpn[18223]: /sbin/ip route add 220.127.116.11/32 via 184.108.40.206
    Jul 24 04:41:01 designfully openvpn[18223]: /sbin/ip route add 0.0.0.0/1 via 10.8.0.5
    Jul 24 04:41:01 designfully openvpn[18223]: /sbin/ip route add 18.104.22.168/1 via 10.8.0.5
    Jul 24 04:41:01 designfully openvpn[18223]: /sbin/ip route add 10.8.0.1/32 via 10.8.0.5
    Jul 24 04:41:01 designfully openvpn[18223]: Initialization Sequence Completed
    Jul 24 04:42:57 designfully kernel: atkbd.c: Unknown key released (translated set 2, code 0xe0 on isa0060/serio0).
    Jul 24 04:42:57 designfully kernel: atkbd.c: Use 'setkeycodes e060 <keycode>' to make it known.
    Jul 24 04:43:39 designfully openvpn[18223]: event_wait : Interrupted system call (code=4)
    Jul 24 04:43:39 designfully openvpn[18223]: /sbin/ip route del 10.8.0.1/32
    Jul 24 04:43:39 designfully openvpn[18223]: /sbin/ip route del 126.96.36.199/32
    Jul 24 04:43:39 designfully openvpn[18223]: /sbin/ip route del 0.0.0.0/1
    Jul 24 04:43:39 designfully openvpn[18234]: event_wait : Interrupted system call (code=4)
    Jul 24 04:43:39 designfully openvpn[18234]: /sbin/ip route del 10.8.0.0/24
    Jul 24 04:43:39 designfully openvpn[18223]: /sbin/ip route del 184.108.40.206/1
    Jul 24 04:43:39 designfully openvpn[18234]: ERROR: Linux route delete command failed: external program exited with error status: 2
    Jul 24 04:43:39 designfully openvpn[18234]: Closing TUN/TAP interface
    Jul 24 04:43:39 designfully openvpn[18234]: /sbin/ip addr del dev tun0 local 10.8.0.1 peer 10.8.0.2
    Jul 24 04:43:39 designfully openvpn[18223]: Closing TUN/TAP interface
    Jul 24 04:43:39 designfully openvpn[18223]: /sbin/ip addr del dev tun1 local 10.8.0.6 peer 10.8.0.5
    Jul 24 04:43:39 designfully openvpn[18234]: Linux ip addr del failed: external program exited with error status: 2
    Jul 24 04:43:39 designfully openvpn[18234]: SIGTERM[hard,] received, process exiting
    Jul 24 04:43:39 designfully openvpn[18223]: SIGTERM[hard,] received, process exiting
</code>
EDIT:
<code>#################################################
# Sample OpenVPN 2.0 config file for            #
# multi-client server.                          #
#                                               #
# This file is for the server side              #
# of a many-clients <-> one-server              #
# OpenVPN configuration.                        #
#                                               #
# OpenVPN also supports                         #
# single-machine <-> single-machine             #
# configurations (See the Examples page         #
# on the web site for more info).               #
#                                               #
# This config should work on Windows            #
# or Linux/BSD systems.  Remember on            #
# Windows to quote pathnames and use            #
# double backslashes, e.g.:                     #
# "C:\\Program Files\\OpenVPN\\config\\foo.key" #
#                                               #
# Comments are preceded with '#' or ';'         #
#################################################

# Which local IP address should OpenVPN
# listen on? (optional)
;local a.b.c.d

# Which TCP/UDP port should OpenVPN listen on?
# If you want to run multiple OpenVPN instances
# on the same machine, use a different port
# number for each one.  You will need to
# open up this port on your firewall.
port 1194

# TCP or UDP server?
;proto tcp
proto udp

# "dev tun" will create a routed IP tunnel,
# "dev tap" will create an ethernet tunnel.
# Use "dev tap0" if you are ethernet bridging
# and have precreated a tap0 virtual interface
# and bridged it with your ethernet interface.
# If you want to control access policies
# over the VPN, you must create firewall
# rules for the the TUN/TAP interface.
# On non-Windows systems, you can give
# an explicit unit number, such as tun0.
# On Windows, use "dev-node" for this.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun

# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel if you
# have more than one.  On XP SP2 or higher,
# you may need to selectively disable the
# Windows firewall for the TAP adapter.
# Non-Windows systems usually don't need this.
;dev-node MyTap

# SSL/TLS root certificate (ca), certificate
# (cert), and private key (key).  Each client
# and the server must have their own cert and
# key file.  The server and all clients will
# use the same ca file.
#
# See the "easy-rsa" directory for a series
# of scripts for generating RSA certificates
# and private keys.  Remember to use
# a unique Common Name for the server
# and each of the client certificates.
#
# Any X509 key management system can be used.
# OpenVPN can also use a PKCS #12 formatted key file
# (see "pkcs12" directive in man page).
ca ca.crt
cert server.crt
key server.key  # This file should be kept secret

# Diffie hellman parameters.
# Generate your own with:
#   openssl dhparam -out dh1024.pem 1024
# Substitute 2048 for 1024 if you are using
# 2048 bit keys.
dh dh2048.pem

# Configure server mode and supply a VPN subnet
# for OpenVPN to draw client addresses from.
# The server will take 10.8.0.1 for itself,
# the rest will be made available to clients.
# Each client will be able to reach the server
# on 10.8.0.1. Comment this line out if you are
# ethernet bridging. See the man page for more info.
server 10.8.0.0 255.255.255.0

# Maintain a record of client <-> virtual IP address
# associations in this file.  If OpenVPN goes down or
# is restarted, reconnecting clients can be assigned
# the same virtual IP address from the pool that was
# previously assigned.
ifconfig-pool-persist ipp.txt

# Configure server mode for ethernet bridging.
# You must first use your OS's bridging capability
# to bridge the TAP interface with the ethernet
# NIC interface.  Then you must manually set the
# IP/netmask on the bridge interface, here we
# assume 10.8.0.4/255.255.255.0.  Finally we
# must set aside an IP range in this subnet
# (start=10.8.0.50 end=10.8.0.100) to allocate
# to connecting clients.  Leave this line commented
# out unless you are ethernet bridging.
;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100

# Configure server mode for ethernet bridging
# using a DHCP-proxy, where clients talk
# to the OpenVPN server-side DHCP server
# to receive their IP address allocation
# and DNS server addresses.  You must first use
# your OS's bridging capability to bridge the TAP
# interface with the ethernet NIC interface.
# Note: this mode only works on clients (such as
# Windows), where the client-side TAP adapter is
# bound to a DHCP client.
;server-bridge

# Push routes to the client to allow it
# to reach other private subnets behind
# the server.  Remember that these
# private subnets will also need
# to know to route the OpenVPN client
# address pool (10.8.0.0/255.255.255.0)
# back to the OpenVPN server.
;push "route 192.168.10.0 255.255.255.0"
;push "route 192.168.20.0 255.255.255.0"

# To assign specific IP addresses to specific
# clients or if a connecting client has a private
# subnet behind it that should also have VPN access,
# use the subdirectory "ccd" for client-specific
# configuration files (see man page for more info).

# EXAMPLE: Suppose the client
# having the certificate common name "Thelonious"
# also has a small subnet behind his connecting
# machine, such as 192.168.40.128/255.255.255.248.
# First, uncomment out these lines:
;client-config-dir ccd
;route 192.168.40.128 255.255.255.248
# Then create a file ccd/Thelonious with this line:
#   iroute 192.168.40.128 255.255.255.248
# This will allow Thelonious' private subnet to
# access the VPN.  This example will only work
# if you are routing, not bridging, i.e. you are
# using "dev tun" and "server" directives.

# EXAMPLE: Suppose you want to give
# Thelonious a fixed VPN IP address of 10.9.0.1.
# First uncomment out these lines:
;client-config-dir ccd
;route 10.9.0.0 255.255.255.252
# Then add this line to ccd/Thelonious:
#   ifconfig-push 10.9.0.1 10.9.0.2

# Suppose that you want to enable different
# firewall access policies for different groups
# of clients.  There are two methods:
# (1) Run multiple OpenVPN daemons, one for each
#     group, and firewall the TUN/TAP interface
#     for each group/daemon appropriately.
# (2) (Advanced) Create a script to dynamically
#     modify the firewall in response to access
#     from different clients.  See man
#     page for more info on learn-address script.
;learn-address ./script

# If enabled, this directive will configure
# all clients to redirect their default
# network gateway through the VPN, causing
# all IP traffic such as web browsing and
# and DNS lookups to go through the VPN
# (The OpenVPN server machine may need to NAT
# or bridge the TUN/TAP interface to the internet
# in order for this to work properly).
push "redirect-gateway def1 bypass-dhcp"

# Certain Windows-specific network settings
# can be pushed to clients, such as DNS
# or WINS server addresses.  CAVEAT:
# http://openvpn.net/faq.html#dhcpcaveats
# The addresses below refer to the public
# DNS servers provided by opendns.com.
push "dhcp-option DNS 188.8.131.52"
push "dhcp-option DNS 188.8.131.52"

# Uncomment this directive to allow different
# clients to be able to "see" each other.
# By default, clients will only see the server.
# To force clients to only see the server, you
# will also need to appropriately firewall the
# server's TUN/TAP interface.
;client-to-client

# Uncomment this directive if multiple clients
# might connect with the same certificate/key
# files or common names.  This is recommended
# only for testing purposes.  For production use,
# each client should have its own certificate/key
# pair.
#
# IF YOU HAVE NOT GENERATED INDIVIDUAL
# CERTIFICATE/KEY PAIRS FOR EACH CLIENT,
# EACH HAVING ITS OWN UNIQUE "COMMON NAME",
# UNCOMMENT THIS LINE OUT.
;duplicate-cn

# The keepalive directive causes ping-like
# messages to be sent back and forth over
# the link so that each side knows when
# the other side has gone down.
# Ping every 10 seconds, assume that remote
# peer is down if no ping received during
# a 120 second time period.
keepalive 10 120

# For extra security beyond that provided
# by SSL/TLS, create an "HMAC firewall"
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
#   openvpn --genkey --secret ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be '0'
# on the server and '1' on the clients.
;tls-auth ta.key 0 # This file is secret

# Select a cryptographic cipher.
# This config item must be copied to
# the client config file as well.
;cipher BF-CBC        # Blowfish (default)
;cipher AES-128-CBC   # AES
;cipher DES-EDE3-CBC  # Triple-DES

# Enable compression on the VPN link.
# If you enable it here, you must also
# enable it in the client config file.
comp-lzo

# The maximum number of concurrently connected
# clients we want to allow.
;max-clients 100

# It's a good idea to reduce the OpenVPN
# daemon's privileges after initialization.
#
# You can uncomment this out on
# non-Windows systems.
user nobody
group nobody

# The persist options will try to avoid
# accessing certain resources on restart
# that may no longer be accessible because
# of the privilege downgrade.
persist-key
persist-tun

# Output a short status file showing
# current connections, truncated
# and rewritten every minute.
status openvpn-status.log

# By default, log messages will go to the syslog (or
# on Windows, if running as a service, they will go to
# the "\Program Files\OpenVPN\log" directory).
# Use log or log-append to override this default.
# "log" will truncate the log file on OpenVPN startup,
# while "log-append" will append to it.  Use one
# or the other (but not both).
;log         openvpn.log
;log-append  openvpn.log

# Set the appropriate level of log
# file verbosity.
#
# 0 is silent, except for fatal errors
# 4 is reasonable for general usage
# 5 and 6 can help to debug connection problems
# 9 is extremely verbose
verb 3

# Silence repeating messages.  At most 20
# sequential messages of the same message
# category will be output to the log.
;mute 20
</code>
Comment: Not really, no!  Could you edit your server's OpenVPN config file into your question, and perhaps the output from `netstat -rn` when the service is up and running?
Answer: Your problem comes from the line
<code>Jul 24 04:40:29 designfully openvpn[18223]: /sbin/ip route add 0.0.0.0/1 via 10.8.0.5
Jul 24 04:40:29 designfully openvpn[18115]: /sbin/ip route add 184.108.40.206/1 via 10.8.0.5
</code>
Each line adds a route for half the internet via the OpenVPN tunnel; the upshot is that all your network traffic will go down the VPN.
Either your VPN partner is happy to route all your traffic, in which case you should be fine, or they're not, in which case, you shouldn't add that route.
From the fact that you lose connectivity, my very strong guess is the latter.  You haven't shown us your config (as asked), so I don't know whether the routes are locally-configured or are being advertised by your OpenVPN partner.  If they're locally-configured, don't do that.  If your OpenVPN partner insists on advertising that route to you, either they need to deal with your traffic, or you need to ignore the route.
Comment: Updated with my config.
Comment: That's odd, it makes no mention of those routes at all.  The logs you posted above, those are from the **server**, not the **client**, yes?
Comment: That's correct.
Comment: Very strange.  Is there some client who's continually trying to talk to the server, who might be connecting as soon as the service starts up?
Comment: From what I can tell from your logs, I suspect that you've configured both the server and the client parts on the server. That means that the server is trying to connect to itself as soon as the OpenVPN service is started, and then tries to route default through the tunnel to itself. Can you please post a "ps axuw|grep openvpn" to confirm if this is the case?


Scraping de tabela na wikipedia com Python

Question: Estou tentando fazer scraping da tabela de classificação final do campeonato brasileiro de 1971, disponível na wikipedia. O máximo que consegui foi pegar a primeira tabela, e mesmo ela, não consegui tratar os dados. Alguém pode me ajudar?
O que eu fiz:
from bs4 import BeautifulSoup
import pandas as pd
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
import urllib3
import requests

website_url = requests.get('https://pt.wikipedia.org/wiki/Campeonato_Brasileiro_de_Futebol_de_1971').text

soup = BeautifulSoup(website_url,'lxml')
print(soup.prettify())

tabela = soup.find('table',{'class':'wikitable'})

links = tabela.findAll('a')

Times = []
for link in links:
  Times.append(link.get('title'))

print(Times)

df = pd.DataFrame()
df['Times'] = Times

df

Como resultado, tenho um dataframe da primeira tabela, e com dados desnecessários (como o estado, que vinha no 'alt' das imagens):
Times
0   America Football Club (Rio de Janeiro)
1   Rio de Janeiro (cidade)
2   Guanabara
3   Guanabara
4   América Futebol Clube (Belo Horizonte)
... ...
89  Pernambuco
90  Club de Regatas Vasco da Gama
91  Rio de Janeiro (cidade)
92  Guanabara
93  Guanabara

Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Antes de fazer uma raspagem primeiro verifique se o site alvo dessa raspagem oferece uma API provendo acesso direto ao banco da dados do site.
import pandas as pd

import urllib.request, urllib.parse, json

pd.set_option('max_columns', None)           #Configura para exibir todas as colunas do dataframe

#Configura os parâmetros da consulta
params= urllib.parse.urlencode({
  "action": "parse",
  "pageid": "201178",     #Explicado como foi obtido na reposta abaixo.
  "section": "13",        #Explicado como foi obtido na reposta abaixo.
  "prop": "text",
  "format": "json",
  "utf8": "1"
})
#Define o endpoint
endpoint = "https://pt.wikipedia.org/w/api.php?%s" % params

#Abre o documento HTML contendo a tabela Classificação final que estará localizado na chave ["parse"]["text"]["*"] da resposta.
with urllib.request.urlopen(endpoint) as url:
    html = json.loads(url.read().decode())["parse"]["text"]["*"]

df = pd.read_html(html)[0]        #pd.read_html retorna uma lista de dataframes, no caso há apenas um contendo os dados da tabela Classificação final.

print(df)

Teste o exemplo no Repl.it
No seu caso específico você quer raspar os dados duma página da Wikipédia:
https://pt.wikipedia.org/wiki/Campeonato_Brasileiro_de_Futebol_de_1971
Seu objetivo é extrair a tabela Classificação final:

Mas o seu código retorna apenas a raspagem dos dados da tabela Participantes:

Antes de fazer uma raspagem primeiro verifique se o site alvo dessa raspagem oferece uma API provendo acesso direto ao banco da dados do site.
A Wikipédia oferece aos seus usuários o serviço Wikipédia:Central de pesquisas/Portal de dados/API onde se definem como um serviço de API web que provê acesso direto ao banco da dados do MediaWiki que é a engine por detrás do Wikipédia.
Para consultar o banco de dados, você envia uma solicitação HTTP GET para o endpoint desejado, por exemplo https://pt.wikipedia.org/w/api.php? é o endpoint para Wikipédia em Português.
Podem ser consultadas as seguinte informações:

Meta informações sobre a Wiki e usuários logados.
Propriedades das páginas, incluindo revisões e conteúdo, ligações externas, categorias, modelos, etc.
Lista de páginas dentro de um certo critério.

Essas informações podem ser retornadas nos seguintes formatos:

JSON (e JSON com elementos HTML)
WDDX
XML
YAML
PHP's native serialization (também nos formatos PHP print_r(),PHP var_export(),PHP var_dump())

Inicialmente faça uma consulta no próprio navegador para obter os metadados sobre a página em questão(veja Main module e action=parse):
https://pt.wikipedia.org/w/api.php?action=parse&prop=sections&page=Campeonato_Brasileiro_de_Futebol_de_1971&utf8=1
Logo ao início já é apresentada uma informação importante:
{
    "parse": {
        "title": "Campeonato Brasileiro de Futebol de 1971",
        "pageid": 201178,
        "sections": [
            {

A chave "pageid": 201178 nos informa o id da página Campeonato Brasileiro de Futebol de 1971 dentro do banco de dados da Wikipédia em Português.
Mais adiante dentro do array "sections":
{
   "toclevel": 1,
   "level": "2",
   "line": "Classificação final",
   "number": "8",
   "index": "13",
   "fromtitle": "Campeonato_Brasileiro_de_Futebol_de_1971",
   "byteoffset": 50518,
   "anchor": "Classificação_final"
}

A chave "anchor": "Classificação_final" indica a ancora para o tópico de interesse, no caso a tabela Classificação final, e "index": "13" é o numero da seção contendo a tabela.
Munido dessas informações basta o seguinte script python para obter a informação desejada, o exemplo precisa além do módulo pandas precisa ter instalado o módulo lxml:
import pandas as pd

import urllib.request, urllib.parse, json

pd.set_option('max_columns', None)           #Configura para exibir todas as colunas do dataframe

#Configura os parâmetros da consulta
params= urllib.parse.urlencode({
  "action": "parse",
  "pageid": "201178",                 #o id da página Campeonato Brasileiro de Futebol de 1971 dentro do banco de dados da Wikipédia em Português.
  "section": "13",                    #o numero da seção contendo a tabela
  "prop": "text",
  "format": "json",
  "utf8": "1"
})
#Define o endpoint
endpoint = "https://pt.wikipedia.org/w/api.php?%s" % params

#Abre o documento HTML contendo a tabela Classificação final que estará localizado na chave ["parse"]["text"]["*"] da resposta.
with urllib.request.urlopen(endpoint) as url:
    html = json.loads(url.read().decode())["parse"]["text"]["*"]

df = pd.read_html(html)[0]        #pd.read_html retorna uma lista de dataframes, no caso há apenas um contendo os dados da tabela Classificação final.

print(df)

Resultando:
    Pos             Times  Pts   J   V   E   D  GP  GC  SG   %  /
0     1  Atlético Mineiro   34  27  12  10   5  39  22  17  63
1     2         São Paulo   30  27  10  10   7  26  23   3  56
2     3          Botafogo   28  27   8  12   7  27  27   0  52
3     4       Corinthians   31  25  12   7   6  33  21  12  62
4     5     Internacional   30  25  10  10   5  28  23   5  60
5     6            Grêmio   29  25  10   9   6  24  18   6  58
6     7         Palmeiras   28  25   9  10   6  27  20   7  56
7     8          Cruzeiro   28  25   8  12   5  28  17  11  56
8     9            Santos   27  25   9   9   7  24  16   8  54
9    10          Coritiba   26  25  11   4  10  23  25  -2  52
10   11           America   26  25   8  10   7  27  21   6  52
11   12     Vasco da Gama   23  25   7   9   9  15  22  -7  46
12   13             Bahia   18  19   5   8   6  14  16  -2  47
13   14          Flamengo   18  19   4  10   5  13  17  -4  47
14   15        Santa Cruz   17  19   3  11   5  17  23  -6  45
15   16        Fluminense   16  19   5   6   8  12  13  -1  42
16   17        Portuguesa   15  19   6   3  10  16  24  -8  40
17   18   América Mineiro   13  19   2   9   8  11  19  -8  35
18   19             Sport   12  19   4   4  11  10  27 -17  32
19   20             Ceará    9  19   2   5  12   5  25 -20  24

                   Classificação ou rebaixamento
0   Fase de grupos da Copa Libertadores de 1972.
1   Fase de grupos da Copa Libertadores de 1972.
2               Também participou da fase final.
3                  Participaram da segunda fase.
4                  Participaram da segunda fase.
5                  Participaram da segunda fase.
6                  Participaram da segunda fase.
7                  Participaram da segunda fase.
8                  Participaram da segunda fase.
9                  Participaram da segunda fase.
10                 Participaram da segunda fase.
11                 Participaram da segunda fase.
12                Participaram da primeira fase.
13                Participaram da primeira fase.
14                Participaram da primeira fase.
15                Participaram da primeira fase.
16                Participaram da primeira fase.
17                Participaram da primeira fase.
18                Participaram da primeira fase.
19                Participaram da primeira fase.

Teste o exemplo no Repl.it
Comment: Agradeço muito pela aula!


How can i put an href link in my foreach statement?

Question: For starters i am fairly new at this.
I am trying to figure out how to a href link my row 'inspection_files' and i have tried just about everything. Is there anybody who could help me?
<?php
$i = 0;
foreach ($result as $r) {
    echo "
";
    echo "" . $r['last_inspection'] . "	" . strtolower(trim(($r['inspected_by_company']))) . "	" . strtolower(trim($r['inspection_files'])) . "	";
    echo "
";

    $i++;
}
?>

Comment: A little more information and a little clearer would be nice but I think this is what you are looking for. - https://stackoverflow.com/questions/17147821/how-to-make-a-whole-row-in-a-table-clickable-as-a-link
Comment: This is basic HTML (101). An `` https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a
Answer: Hey you can directly use  tag inside the , just like below
echo "" . $r['last_inspection'] . "	" . strtolower(trim(($r['inspected_by_company']))) . "	" . strtolower(trim($r['inspection_files'])) . "	";

I hope $r['inspection_files'] this is your URL if this is not your redirect URL then just replace with your actual URL.
Comment: Not my downvote here, but I edited your answer to use ticks around (HTML) markup elements. Go into edit mode to see what I did. Edit: Not sure why you got a downvote though. Maybe the person can elaborate on it?


Continuity with directional derivatives

Question: I face a problem in my exam
If a function with two variables is there any relation between continuity and directional derivatives, please explain with example it's really helpful thankyou
Answer: There is no relation in the following sense: you can have a continuous function but whose partial derivatives do not exist, and conversely you can find a function whose partial derivatives exist but the function is not continuous. Examples for both cases can be found in the following questions:
Does existence of partial derivatives implies continuity at a point $(x_0,y_0)$?
Does continuity imply partial derivatives exist?
Comment: @user349115 Please accept answers which help you..

Continuity with directional derivatives


SQL Server Generate Scripts

Question: I need to find a way to generate insert select scripts for a set of tables. The Generate Scripts Task in SSMS 2008 seems to generate insert values statements. I could just generate them using some of the system views but would prefer to functionality for this already in SSMS
Thanks
Comment: And where do you want to insert data? Same table? Different DB?
Comment: Anyhow - something like `SELECT 'INSERT INTO ' + name + '_New SELECT * FROM ' + name FROM sys.tables` is your best option here.
Comment: thanks again Nenad. I figured I might end up using doing something like that.
Answer: What do you want to do? Generate script for Insert or Select? Right click on the table choose 'Script table as' and choose what you want to do
Comment: I need something like: insert instanceA.schema.table_A(col1,col2) select col1,col2 from instanceB.schema.table_A
Answer: In Object Explorer, pick your database, use Tasks > Generate Scripts.. and then click on the Advanced Options button:

In the dialog that comes up, you can pick what to script - schema only, data only or schema and data:
Comment: thanks Marc. I was aware of this way but it generates one insert..values statement per row (huge file for large table) and I was looking for a single insert..select command instead. I think I will have to use the sys.tables view.
Answer: You could use this script:
--assuming only the db instance differs
declare  @otherDB varchar(100) = 'instanceB'
declare @thisDB varchar(100) = db_name()

select
'INSERT INTO ' +  @otherDB + '.' + s.name + '.' + t.name +
' SELECT * FROM ' + @thisDB + '.' + s.name + '.' + t.name
from sys.tables t
inner join sys.schemas s on s.schema_id = t.schema_id
where t.is_ms_shipped = 0

SQL Server Generate Scripts


Python DB API get inserted row id

Question: I have the following code:
cursor = connection.cursor()
cursor.execute('INSERT INTO my_table (col1, col2) VALUES (?, ?)', params) # return None

Azure Synapse Analytics doesn't support @@IDENTITY and SCOPE_IDENTITY, while cursor.execute returns None.
How can I get the inserted PK (generated by IDENTITY(1,1))?
P.S. I know Synapse is columnar MPP, not an OLTP. This is needed in PoC purposes, for sake of speed development. In nearest future I will switch to appropriate RDBMs
Answer: It appears that none of the standard T-SQL methods for retrieving new IDENTITY values are supported by Azure Synapse Analytics - including (@@IDENTITY, SCOPE_IDENTITY, IDENT_CURRENT, the OUTPUT clause, and using a sequence (via NEXT VALUE FOR) to set the PK value instead of IDENTITY)
Possibly your only option is to run a second query after the insert. Depending on the uniqueness of the inserted data, this could be as simple as:
SELECT ID from my_table WHERE col1 = ? AND col2 = ?

or might need to be more complex if you have to deal with duplicates.

Python DB API get inserted row id


How to sort autocomplete results by post date?

Question: I have a content type named "News" which contains a node reference field named "Related News" in autocomplete mode.
Does anyone knows how to sort the results when i write something? I need to get the most recent nodes.
Thank you!
Answer: You should use views entity reference widget.you can custom you result like want you want.
this link is good tutorial for you achieve your job.I hope learn it and use  it in future project and issues.


NoClassDefFoundError: Could not initialize class

Question: I'm developing an Identity Provider using OpenSAML API.
I have created a java application to test OpenSAML API which was a success.
The problem is now I'm trying to use that java Application in Servlet using glassfish and I'm loosing my mind right now.
Hear me out:
before you can start using OpenSAML you have to call it's bootstrap to initiate it's components, one of those components is
    org.apache.xml.security.Init
so i added xmlsec.jar into libraries but every time I run the WebApplication it keeps on getting an exception:
"java.lang.NoClassDefFoundError: Could not initialize class org.apache.xml.security.Init"

the confusing part is if I remove the xmlsec.jar from libs, it still knows the
import "org.apache.xml.security.Init"

but when I delete that and try to rewrite the same:
import "org.apache.xml.security.Init"

now it fails because now org.apache doesn't have xml.security in it.
any idea guys?
PS: I'm using these:
                   - NetBeans IDE
                   - Glassfish 4.1.1
                   - Java EE 7
                   - JDK 1.8
glassfish output:
Warning:   StandardWrapperValve[LoginServlet]: Servlet.service() for servlet LoginServlet threw exception
java.lang.NoClassDefFoundError: Could not initialize class org.apache.xml.security.Init
at org.opensaml.DefaultBootstrap.initializeXMLSecurity(DefaultBootstrap.java:195)
at org.opensaml.DefaultBootstrap.bootstrap(DefaultBootstrap.java:98)
at opensamltest1.SAMLHelper.printSAMLObject(SAMLHelper.java:180)
at LoginServlet.processRequest(LoginServlet.java:53)
at LoginServlet.doPost(LoginServlet.java:100)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)

Comment: A `NoClassDefFoundError` with the message 'Could not initialize class SomeClass` means that the JVM has already tried and failed to load the class `SomeClass`.  Restart GlassFish and try again, and hopefully you should get a different exception (possibly an `ExceptionInInitializerError`).  If so, edit your question to include the stacktrace of that exception.
Answer: This could be due to a conflict between classes provided by JVM or your Container host, and those in the WAR file.  If the class is duplicated in both places it can play all sorts of havoc with your startup.
Answer: Turns out you should abandon glassfish and go to JBoss.
That solved my problem.
Thanks.


Champions League team distribution

Question: How does UEFA decide how many teams per league are allowed to qualify for the Champions League tournament?
Comment: The section [Association team allocation](https://en.wikipedia.org/wiki/2019%E2%80%9320_UEFA_Champions_League#Association_team_allocation) in the Wikipedia article on this season of UEFA Champions League contains some details on this.
Answer: @Martin shared a great reference in the comments.

The association ranking based on the UEFA country coefficients is used to determine the number of participating teams for each association...

It goes on...

For the 2019–20 UEFA Champions League, the associations are allocated places according to their 2018 UEFA country coefficients, which takes into account their performance in European competitions from 2013–14 to 2017–18.
Apart from the allocation based on the country coefficients, associations may have additional teams participating in the Champions League, as noted below:
(UCL) – Additional berth for UEFA Champions League title holders
(UEL) – Additional berth for UEFA Europa League title holders

In other words, countries with club that have continued success "reward" their league in the long run. For example, fans of La Liga or Spanish clubs have benefited from the success of Atletico Madrid, Barcelona, and Real Madrid for the last 6 years. This has guaranteed 4 spots for Spanish clubs in the Champions League.

Champions League team distribution


Where can I find good, reliable Drupal freelancers?

Question: I've looked on Elance, Guru, etc for skilled, reliable Drupal freelancers without any luck.  Are there any suggestions for where to look for these folks?  Remote workers are fine for what I need done.
Comment: Just out of curiosity, what is your complaint about E-lance? I have a profile on my own up there, but I'm to busy with my full-time Drupal job to be active on there.
Comment: It would be great if this site would add a feature for drop jobs/projects. But this should probably discussed in meta ;-)
Answer: A lot of generic freelancer site members may have used Drupal but usually work with anything, wordpress, joomla etc. Drupal has a fairly high learning curve and to get the best out of it you would be best with a Drupal Expert. Maybe try something closer to the Drupal community.
Using a Drupal resource for Drupal freelancers might provide more Drupal expertise...
http://drupal.org/paid-services
http://drupal.org/marketplace-preview
Answer: You can try #drupal-consultants on IRC, freenode.
Mailing list: http://lists.drupal.org/listinfo/consulting
Forum: http://drupal.org/paid-services
Drupal groups:

http://groups.drupal.org/consulting
http://groups.drupal.org/available-for-hire


Semidirect products and finding normal subgroups

Question: My question reads:
Let A, K be subgroups. Group G is called semidirect product of A and K if A  $\trianglelefteq$ G, G=AK and  A$\cap$K = < e >. Show that the groups are the semidirect product of two of its subgroups.
a) S$_3$
b) D$_4$
c) S$_4$
Now I am not sure if this is asking for a proof for each part or to directly pick two subgroups that are normal and then make sure the conditions for semidirect products are met. Also, doesn't this imply I need to show the subgroups I pick are normal? I need help picking these subgroups and from there I think it will be straightforward showing the other conditions are satisfied
For example for S3 could I pick the whole group itself?
Comment: In (a), you want $A=\{(1),(1,2,3),(1,3,2)\}$. Try and do the others yourself.
Comment: That's right, $A$ must be normal but not necessarily $K$. In fact if $K$ is normal then you get the direct product.
Comment: I think the point of the exercise is to use $\textit{proper}$ subgroups. Otherwise, this is trivial.
Comment: @KenDuna well a hint to this problem is to consider normal subgroups and I think this makes more sense given that one of the conditions is that the subgroup be normal
Comment: My point is that every group is normal in itself. So $A = G$, $K = \{e\}$ would work for every group, $G$. This would make the question a silly one. So I think it is safe to assume that your teacher wanted $A$ and $K$ to be proper subgroups. With that said, a hint for $S_3$: $A = \langle (1 \ 2 \ 3) \rangle$ and $K = \langle (1 \ 2) \rangle$.
Comment: @KenDuna ah got it, yes those choices would be to easy. I was considering <(1 2)>. I guess my question is would I need to prove these subgroups I am picking are normal or can I just directly use them?
Comment: @KenDuna then K={ (1), (1 2)} but what would A look like
Comment: @DerekHolt both subgroups do not need to be normal though, only one correct?
Comment: @DerekHolt okay, then I can simply take A and K and show that multiplying them I get G and there intersection is just < e> and I should be good? Then there is really no proof I am showing this is all just computation? I do not have to show these subgroups are normal?
Comment: But as I said before, the subgroup $K$ is not normal. For a complete proof you would need to prove that the subgroup $A$ is normal.
Comment: @KenDuna I am still confused by this problem, is there anyway you can show me how to do even just part a so I can do b and c?
Answer: Per request: In $S_3$ let $A = \langle (1 \ 2 \ 3) \rangle$ and $K = \langle (1 \ 2) \rangle$. Note that the index of $A$ in $S_3$ is $2$ so we are guaranteed that $A$ is normal in $S_3$ (if you like, you can check normality with the definition).
Now our goal is to show that $S_3 = AK$. So let's just compute $AK$. There are $6$ quantities to compute, they are as follows:
\begin{align*}
(1)(1) &= (1)\\
(1)(12) &= (1 \ 2) \\
(1 \ 2 \ 3)(1) &= (1 \ 2 \ 3)\\
(1 \ 2 \ 3)(1 \ 2) &= (1 \ 3)\\
(1 \ 3 \ 2)(1) &= (1 \ 3 \ 2)\\
(1 \ 3 \ 2)(1 \ 2) &= (2 \ 3)
\end{align*}
You see every element of $S_3$ show up there, so $AK = S_3$.
Technically, this computation is unnecessary since $|AK| = \frac{|A||K|}{|A\cap K|}$. But I thought that it would be instructive in this case.
Comment: Would you mind if I did out part b here and you told me if it looks okay? I have just been struggling with this problem for days now and I want to make sure I understand it.
Answer: In D$_4$, let A=< r>, K={e,s}. Checking that A is normal: by lagrange theorem, have index 2 thus A is normal.
Now showing D$_4$=AK We compute:
ee=e
es=s
re=r
rs=rs
r$^2$e=r$^2$
r$^2$s=r$^2$s
r$^3$e=r$^3$
r$^3$s=r$^3$s
Then, every element in D$_4$ shows up, so AK=D$_4$.
Then showing there intersection is < e > we can state it by looking at our sets.
Comment: Providing answers to your own questions is not only ok, but it is highly encouraged! With that said, $A \cap K \neq \{e\}$ in your example here ($r^2$ is in the intersection). Try using $K = \{e, s\}$.
Comment: Everything looks good.
Comment: Ok cool, I thought I wasn't allowed to do so. And yes! i just switched my K on my paper I will update it to see how it looks on paper and show you here. Thank You for the feedback.
Comment: Thank you! I am going to post c too I am just a bit unfamiliar with the elements of S4 as for my class we focus on S3. Would it be like S3 except we would have say (1 2 3 4) now?
Comment: Unfortunately that doesn't work. There are probably a number of ways to do the $S_4$ case, but I think the easiest way would be to set $A = A_4$ and $K = \langle (1 \ 2 ) \rangle$ where $A_4$ is the subgroup of all even permutations in $S_4$. In general $A_n$ is normal in $S_n$ (the index is 2).
Comment: Note that in $A_3 = \langle (1 \ 2 \ 3) \rangle \subseteq S_3$. So the approach is really the same as it was in $S_3$.
Comment: Hmm, so there is no simple way to list out the elements in S$_4$ like we did for S$_3$? What would A look like then set wise to get a sense of what elements to work with?
Comment: Writing out all the elements of $S_4$ or even $A_4$ is tedious because they have order $24$ and $12$ respectively.  Every element of $S_n$ can be written as a product of transpositions. A transposition is an permutation of order 2 that switches two numbers and that is all it does. It can be verified that for any permutation, any time you express it as a product of transpositions, there is either always an even or always an odd number of them. A permutation is called even or odd based on this. $A_n$ is the set of even permutations.


Asset prices vs. Asset pricing?

Question: How do these two tags differ?
https://economics.stackexchange.com/questions/tagged/asset-pricing
https://economics.stackexchange.com/questions/tagged/asset-prices
Answer: The tag asset pricing has its own summary:

The branch of Finance that studies and models how specific assets (such as options, bonds and stocks) are priced.

The tag asset prices just refers to asset prices.

Asset prices vs. Asset pricing?


How do I check radio buttons in Twig template?

Question: In a form, I have this field:
$form['payment'] = [
  '#type' => 'radios',
  '#title' => $this->t('Payment Mode'),
  '#options' => [
    'chk' => $this->t('by check'),
    'tfr' => $this->t('by bank transfer'),
    'crd' => $this->t('by card'),
  ],
  '#required' => TRUE,
];

In the Twig template associated to the form, I'd like to show the field and some html stuff depending on the selected option. I tried this:
<form{{ attributes }}> {{ form.form_build_id }} {{ form.form_token }} {{ form.form_id }}

    {{ form.payment }}
    {% if form.payment ==  'chk' %}
      You chose 'Check'
    {% elseif form.payment ==  'tfr' %}
      You chose 'Bank Transfer'
    {% elseif form.payment ==  'crd' %}
      You chose 'Card'
    {% endif %}

But it is nor working!
Any idea?
Comment: When do you want to show it? Upon selection or upon submission?
Comment: Upon selection.
Comment: I'm wondering what you are doing there with this Twig template. You shouldn't be using a custom template to build a form at all.
Comment: The reason why I'm doing this is that I'd like to have all my "language dependent" strings in a specific file (i.e. the Twig template) instead of embedded in the buildForm function of my form. See my other comment about your #states answer...
Answer: That's a task for #states not for Twig. I think this also could be ajaxified a little bit more elegantly but using #states on some items does the job as well.
$form['payment'] = [
  '#type' => 'radios',
  '#title' => $this->t('Payment Mode'),
  '#options' => [
    'chk' => $this->t('by check'),
    'tfr' => $this->t('by bank transfer'),
    'crd' => $this->t('by card'),
  ],
  '#required' => TRUE,
];

$form['chk'] = [
  '#type' => 'item',
  '#markup' => $this->t("You chose 'Check'"),
  '#states' => [
    'visible' => [
      ':input[name="payment"]' => ['value' => 'chk'],
    ],
  ],
];

$form['tfr'] = [
  '#type' => 'item',
  '#markup' => $this->t("You chose 'Bank Transfer'"),
  '#states' => [
    'visible' => [
      ':input[name="payment"]' => ['value' => 'tfr'],
    ],
  ],
];

$form['crd'] = [
  '#type' => 'item',
  '#markup' => $this->t("You chose 'Card'"),
  '#states' => [
    'visible' => [
      ':input[name="payment"]' => ['value' => 'crd'],
    ],
  ],
];

Comment: I know that I can do that (I already did it). But I have much more text than "You chose bla bla" for each option and I'd like to have it in the Twig template in order to use all HTML possibilities there. And I want to have the least possible of these in the code of the form. So how can I have `'#markup' => whatever` in the form and something to replace it in Twig template?
Comment: @gbmapo – This won't work in the template. It's Twig, for markup, not for listening to certain events like JavaScript can. Which is the only alternative left. Pure JavaScript.


How to develop and test B2C token enrichment with an API connector locally?

Question: I am creating a React SPA that will connect to a dotnet Web API backend. I want to use b2c to handle auth.
I want to have endpoints in the API protected based off the claims in the b2c token, also want to check claims in the frontend aswell.
Following along with token enrichment docs - https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-api-connector-token-enrichment?pivots=b2c-user-flow
I can use an API connector to enrich the token with additional claims before it is sent back to the client, presumably with a function to provide values from my database in a users table.
If my database will also be hosted in azure, how would I develop and test this locally?
Is this flow the best way to achieve the desired behaviour? If not what are alternatives?
Comment: https://medium.com/the-new-control-plane/mocking-azure-ad-b2c-rest-api-calls-a83c74252be5
Answer: I've done two methods when testing 'locally'.

Create an Azure Function echo API service in 'cold' mode to reduce cost. This will allow you to easily ping it and it will ping you back the content. You can also add test cases pretty easily. This isn't really 'local' but, it's low cost and allows you to collaborate with multiple team members.
Use a free web service like Post Test Server. With a couple clicks you are off and testing with lower effort. The problem with this solution is it is public so do not use any proprietary or confidential information. I've created very complex dot notation in body of REST-API technical profile via custom policies and this was effective testing data formatting and internal business logic.

Last option could be creating a web service locally on your device - I haven't done this end-to-end but you would follow this same process as hosting an application locally with localhost.
Answer: You can deploy an Azure database solely for development purposes. Or you can just mock the API response so that you can do some basic e2e testing: SPA -> B2C -> API.


How to increase a scheduled time using a new field and rules component scheduler

Question: I am working on Drupal 7 on a custom content type that is called Event.
Each created Event is programmed to be displayed for 1 hour before been deleted. I am using rules component scheduler for that and it works well.
Now I need to be able to increase that display duration.
I already created a numeric field called duration that take the value of the duration from the user. That value that I want to add to the initial display duration.
I need to use that duration field in the Scheduled evaluation date. But rules denied using the + with an identifier.
Can anybody help ?
How do I increase the duration of a tasks that has already been scheduled on node creation. How do I do that using a field that take the value to add?
Comment: Please include an export of the rule you already have. AND provide more details on how you defined that numeric field (what is, in your opinion, the MEANING of that "integer"). AND explain "when" the user enters that "duration", is it when the node is created, or something like a node update while the "1 hour" timeframe has already started?
Comment: Thanx for the answer @Pierre.Vriens. The field duration is an integer. The content is deleted "1 hour" after been created. So the user can only increase that duration while it is available.
Comment: Your question already said that duration was "integer", but you still did not say what its "meaning" really is, I bet it is not a dollar amount, so what is it then? And from your last phrase I "deduct" that the answer to my last question is "via an update of the node". Can you please ALSO include an export of the rule you have so far, for which you wrote "works well". That way I don't have to make a zillion of assumptions to provide an answer, instead just answer with "this is what you need to add/correct", OK?
Comment: I forgot to say that in fact I created two rules. The first one uses a component on scheduler to delete that content after one hour. The second is the one that is not finished and is supposed increase the time value (This is where I am in trouble)..
Comment: Here is the first rule : { "rules_event_hidden_behavior" : {
    "LABEL" : "Event hidden behavior",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "event" : "event" } } } }
    ],
Comment: Your "2nd" rule is probably the one to be reworked, similar to what I just described in my answer that I posted ...
Comment: "DO" : [
      { "schedule" : {
          "component" : "rules_delete_event",
          "date" : "+1 hour",
          "identifier" : "The Event [node:title] will be deleted in 1 hour time.",
          "param_node_to_delete" : [ "node" ]
        }
      }
    ]
  }
}
Comment: Please EDIT your question to also include that rule (make sure to format it as "code". Posting it as a comment (or even worse: splitting it over 2 comments ...) makes it virtually unreadable (I won't even try to digest such comment ... though I do see already you are using a dangerous "identifier" ... better use "node:nid" to make it unique ...).
Comment: Excatly. It is my second rule that need support.
Comment: I just don't know how to add some time to the initial time that I set to one hour with a new rule (when updating the duration field).
Comment: On the content, I am using conditional_field on two fields that are "Add more time (Yes/No)" and "Duration". "Duration" appears when "Add more time" is set to "Yes". I'd like to use the value in "Duration" to add it to the initial time (With my second rule).
Answer: What you'll have to do to get this to work, consists basically of these steps:

Create a new rule using event "After updating a node of content type Event, in which you add a Rules Condition to check that the value of the duration field was changed (I suppose you know how to write such Rules Condition).
The Rules Actions to be performed in this new rule to be created, consist of these 2 Rules Actions (in the order specified):

Delete the scheduled Rules Component that got scheduled when the node (Event) was created. That way the node will not get deleted as originally planned. For way more details on that, refer to my answer to "How to delete a scheduled task using Rules Scheduler?". Make sure to understand that it is extremely important, for this to work correctly, that you usve a unique identifier of the scheduled rule ... using the node title for it is asking for trouble (what if 2 nodes have the same title???), which is why I always make the node's nid part of such identifier.
Schedule the same Rules Component you already have (to delete the Event later on) AGAIN, using your "duration field".

What this really means is that your implementing logic that reads something like so "Don't delete this node (Event) after one hour yet, instead give me X more time (as indicated in your duration field) from now on (= the moment the updated node (Event) is updated with that duration field update)".
Comment: THis sounds likes wise answer @Pierre.Vriens. Let me try that and I'll give you feedback. And the "X more time" is a good idea...


correlation controlling for baseline scores

Question: I just got a review back on paper and the reviewers want me to report a correlation between the variable at time one and time two controlling for baseline scores.  Is a correlation that includes a control for baseline scores possible, or can that only be done using SEM?
Answer: I think what you are looking for is "partial correlation". See https://en.wikipedia.org/wiki/Partial_correlation - the introductory statement of that page (as of today: Aug 21, 2016) is

In probability theory and statistics, partial correlation measures the degree of association between two random variables, with the effect of a set of controlling random variables removed.
Comment: And partial correlation is usually estimated using regression models


Value of a field is getting overlapped with subreport data

Question: I am working on a jasper report in which I am adding a sub-report to my parent report. Below sub-report, I am adding a static field which contains '$' value.
When I execute my report, the  '$' value is getting overlapped with the content of sub-report. I tried with position-type ' 'FLOAT' for static field and sub-report also, but its not working.
Here I attached screenshots for reference:

and

The parent report content is in summary band and content of sub-report is in detail band. I am keeping content of main report because it contains many variables and if I put those in detail band then they are getting printed many times with different values.
Please help me to resolve this problem.
Answer: It got resolved. Actually I kept top of static field touching with base of sub-report. When I tried with keeping small space between these two elements, its working fine.


Sum of series $\sum_{n=1}^{\infty}\frac{1}{n(n+\frac{1}{2})}$

Question: $\displaystyle\sum_{n=1}^{\infty}\frac{1}{n(n+\frac{1}{2})}$ i am trying to solve an integral and this ended up being last part I need, Wolfram alpha gives $4-2\ln{4}$ but I don't know how they actually got that value. can anyone help or give a starting point? telescoping series didn't work
Answer: Hint: $a_n = \dfrac{4}{2n} - \dfrac{4}{2n + 1}$.
Comment: I tried to write it out but there is no pattern... would digamma function work