ARM Deployment Error- The request content was invalid and could not be deserialized: 'Cannot deserialize the current JSON array

Question: I had gone through the previous posts similar and not able to find any solution for my situation. So asking again. Please consider.
I am trying to deploy Azure Policy using ARM templates. So, I have created
1- Policy Definition File
2- Policy Parameter File
3- Power Shell script – Run with both Policy and Parameter file as input.
But when I trying to deploy, I am getting the error as attached. The "policyParameters" are being passed as Object type. Seems like the problem resides there. It would be great if you could look at this screen shot attached and advice.
Also the Powershell script out put shows the values expected I think but "ProvisioningState : Failed".
Thanks,
PolicyFile
Error Output
Parameter File
JSON-part1
JSON-Part2
Comment: Can you please provide your ARM JSON. I guess there's an issue in the deployment section:

e.g.:
"location": "[[parameters('location')]",
It has to be 2 '[' at the beginning:

Please find a sample here:

https://markusmeyer.hashnode.dev/configure-azure-diagnostic-settings-with-azure-policies
Comment: Please see the attachment, I have uploaded  all 3 files now.
Comment: The complete JSON would be nice. The problem might be in the "deployment section"
Comment: Do you need any more input to idenitify this issue? Been siting with this issue for while. :)
Comment: yes, I need more input. The complete JSON would be nice
Comment: attached as 2 files, JSON-Part1 and JSON-part2
Answer: You have to create a variable for policyParametars:
<code>"variables": {
    "policyParameters": {
        "policyDefinitionId": {
            "defaultValue": "[parameters('policyDefinitionId')]",
            "type": "String"
         },
...
</code>
This variable has to be passed to your parameters:
<code> "parameters": "[variables('policyParameters')]",
</code>
You can find a sample here:
Configure Azure Diagnostic Settings with Azure Policies
Comment: I had to specify the object values as below and its worked.

"policyParameters": {

        "value": {
            "listOfAllowedLocations":{"value":["West US","East US"]}
        }
    }
Comment: Thanks for the reply. But my understadning was we must pass the "policyParameters" as an Object. Am I correct? I will give this one a try and let you know the output.
Comment: Can you please make me understand why I should create another variable for policyParameters. And why the Object is not working as expected.
Comment: I did it with a variable because all the parameters have to be passed to 'parameters'.


Conformal map critical point

Question: I have read that if $f(z)$ is analytic at a point $z_0$, if $f'(z_0)=0, f''(z_0)=0, .. , f(z_0)^{k-1}=0, f(z_0)^k \ne 0$, then the mapping $w=f(z)$ magnifies the angle at the vertex $z_0$by a factor of $k$.
I cannot seem to find a proof of this - could anybody direct me to one or provide an insight themselves. Many thanks!
Answer: Introductory complex analysis books are likely to have this fact, perhaps embedded in a larger discussion of the local behavior of analytic functions.
Use the Taylor expansion at $z_0$. It has the form
$$f(z) = \sum_{j=k}^\infty  (z-z_0)^j   = (z-z_0)^k \left(c_k + \sum_{j=k+1}^\infty  (z-z_0)^{j-k}\right)$$
This implies
$$\lim_{z\to z_0}\frac{f(z)}{(z-z_0)^k} = c_k$$
Therefore, a half-line $z=z_0+te^{i\theta}$ is mapped to a curve that is tangent to the line $z=z_0+t c_ke^{ik\theta}$ at $z_0$. This is the magnification of angles by the factor of $k$.

Conformal map critical point


Saber resultado de count() em query

Question: Tenho a seguinte query em pdo:
<code>$ranking = $pdo->query("SELECT * FROM usuarios GROUP BY moedas ORDER BY count(moedas) DESC LIMIT 3");
</code>
Uso isso para fazer um ranking para saber os usuários com mais moedas. Porém, estou utilizando uma segunda query com rowCount() para saber a quantidade de moedas do usuário listado, seria possível extrair o valor do count(moedas) dessa primeira query (citada no post)?
Answer: Sim, é possível. Veja o exemplo:
<code> $results= "
 SELECT p1.*, aa.moedas AS numbers
 FROM usuarios aa
 ORDER BY aa.moedas * 1 DESC
 DESC LIMIT 3
 ";

$stmt = $pdocon->prepare($results);
$stmt->execute();
while($row = $stmt->fetch()) {
echo $row["numbers"];
}
</code>
Comment: Não é isso que quero amigo, preciso saber o valor do COUNT(moedas).
Comment: Editei a resposta. Você tem que explicar melhor a estrutura da sua tabela.
Comment: E como faço pra exibir?
Comment: Editei novamente a minha resposta.

Saber resultado de count() em query


stratified randomization in clinical trial design

Question: we have 5 treatment groups (blank control, placebo, 3 doses drugs) and want to divide the 160 patients into 20, 20, 40, 40, 40 (1:1:2:2:2) for the 5 treatment groups. So this is like 8 blocks randomization.
But we also want to control gender and marriage status, thus we have 4 strata:
male married, male unmarried, female married, female unmarried
Since the patients are to be recruited are hard to predict how many in each strata, in reality how we can balance the strata when doing the randomization?
Answer: The method you are looking for is minimisation which is breifly explained in the Wikipedia entry As each participant enters the study you calculate for all you variables for which you wish to minimise how unbalanced the current allocations are. You then allocate the next participant to minimise that imbalance. In more refined methods you allocate that pariticpant with high probability to the relevant arm to avoid the allocation being predictable in advance.


What does "the process that generates the data" mean? and How does feature selection help in recovering it?

Question: In [1], one of the motivations to use feature selection is stated to be: "to gain knowledge about the process that generated the data".
What does this "process" actually mean? and How does feature selection help in recovering it?
[1] Guyon, Isabelle, and André Elisseeff. "An introduction to feature extraction." Feature extraction. Springer Berlin Heidelberg, 2006. 1-25.
Comment: +1! Very good question! If you want to read more on the issue of Statistical Models and Data Generating Processes, I recommend Chapter 4 of Davidson's 'Econometric Theory'. It is easy to understand for anyone with a background in statistics and summarizes the issue beautifully.
Answer: A Data Generating Process is the mathematical model generating the data.
For example, if you run a regression model with regressors $X$ and dependent variable $Y$, you implicitly hypothesize a data generating process for $Y$. This data generating process can be described by the statistical model
\begin{align}
Y = X\beta + \varepsilon,
\end{align}
Where $X$ is a $1xk$ vector of random variables, $\beta \in \mathbb{R}^k$ is the $kx1$ vector of coefficients.
An example for variable selection in the case of a regression model would be where you have two sets of regressors, say $X_1$ and $X_2$ such that $X_2 \subset X_1$. Suppose that the true Data Generating Process is
\begin{align}
Y = X_1\beta + \varepsilon,
\end{align}
but that you have all regressors in $X_2$ at your disposal. Then model selection (in theory) helps you to discern the relevant regressors (i.e., $X_1$) from those that are not relevant (i.e., $X_2 \setminus X_1$). This can be done with the BIC, the AIC, or t-statistics. Note that this might affect statistical inference, see also my recent post here: Post Model Selection Inference problems - which remedies exist?
On a sidenote, the notion of a Data Generating Process is fragile. In specifying a statistical model, we impose the Axiom of correct specification. In a regression model, this happens insofar as we consider only linear combinations of the regressors we hypothesize to have an effect on $Y$. How do we know these combinations are not nonlinear? We don't! We simply have to assume it. This is why recently, a new school of statisticians operates without this axiom when doing inference. The only thing they try is to select statistical models (such as the regression model) that can approximate your true Data Generating Process well enough. To make this clearer, suppose the true Data Generating Process for our above regression model is
\begin{align}
Y = \sum_{i=1}^{\infty}X_i\frac{c}{i} + \varepsilon.
\end{align}
While there are infinitely many random variables $x_i$ that affect Y, their coefficients decay at rate $O(i)$. Hence, a good feature selection scheme would select the first $k$ to approximate the true Data Generating Process reasonably well.
Similarly, this applies to other statistical models.
Answer: The process that generated data is the "true" model. I.e., if you had perfect knowledge about the world, this would be the "equation" you'd come up with to describe the interactions and processes that cause (truly unequivocally cause) your dependent variable.
Feature selection usually involves applying some sort of "domain" knowledge (what you know about the nature of the problem, theoretically). So, for example, if you were studying some medical problem, you could use a doctor's help in trying to pick the "features" (markers, test results, measurements, diagnostic history, genetics...) that the medical science (the theory) would "blame" for the outcome. So that's how it could aid in recovering the true process - by careful feature selection, you can weed out the irrelevant variables and focus on what truly matters.
However, it does have a flip side: the theory could be wrong. And you could miss out on important variables that you wouldn't consider just because the theory of the day doesn't account for it.
(There are other approaches to feature selection obviously, from hierarchical, step-wise approaches, to factoring / PDA, to deep learning, where the features are learned by the model... )


How do I change the output of theme_comment_submitted()?

Question: How to change the default theme of comment_submitted in drupal?
Input:
$variables['submitted'] = theme('comment_submitted', $comment);
Output

My expected result is

To print the Name in first and time in second.
Should not truncate.

How can this be done?
Answer: Add a function in your template.php located in your theme's directory.
function phptemplate_comment_submitted($comment){
  return t('Submitted on @datetime by !username.',
    array(
      '!username' => theme('username', $comment),
      '@datetime' => format_date($comment->timestamp)
    ));
}

Answer: You can override any theme function implementing hook_theme_registry_alter() in a module.
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['comment_submitted'])) {
    $theme_registry['comment_submitted']['function'] = 'theme_mymodule_comment_submitted';
  }
}

In this case, as what you want is to override a string used by a module, String Overrides could help you. You just need to replace "Submitted by !username on @datetime." with "Submitted  on @datetime by !username."


Errors while migrating Qt project from Linux to Windows

Question: I have a Qt project develop on linux, but now I need to compile on windows. I'm having a couple of problems in the migration process.
The first error I'm getting it's:
C:\Qt\Qt5.5.1\Tools\mingw492_32\i686-w64-mingw32\include\c++\bits\c++0x_warning.h:32: error:
#error This file requires compiler and library support for the ISO C++ 2011 standard.
This support is currently experimental, and must be enabled with the
-std=c++11 or -std=gnu++11 compiler options.

#error This file requires compiler and library support for the \
^

and this it's how I'm putting it in the .pro of my project
QMAKE_CXXFLAGS += -std=c++11

I also try with
CONFIG += c++11

but the problem continuous.
To give a little more of information, I'm using the MinGW compiler that the Qt Creator install and the extension of my Headers and Sources are: .H and .C (Just in case this have anything to do with the problem, because I've seen that Qt always uses .cpp)
What could be the cause of the problem ?? If something it's unclear or more information it's needed please let me know.
Comment: Which version of gcc is mingw using ? In gcc 4.6, the right flag was still called c++0x.
Comment: http://stackoverflow.com/questions/11066068/how-to-program-c11-using-qt5
Comment: This problem was fixed by changing the extension of the .C files to .cc. Thanks though.
Comment: `CONFIG += c++11` should work. Did you run `qmake` after making the change?
Comment: I did, every time I change the .pro I'll clean run qmake and the build the project. But like I said this problem was fixed thanks for your contribution.
Answer: I solve the problem, for me it worked when I change the extension of my sources, I change .C for .cc


Best Lightweight HTML Parser for Delphi

Question: I need to parse out the values from some data from select boxes.
Example:  <option value="1">Apple</option><option value="2">Chicken</option>
Usage: If option = apple then get value.
Any suggestions?
Answer: DIHtmlParser?  I'm not sure how "lightweight" it is, but Ralf's components always seemed to be well put together.  He's also normally active and response on Embarcadero's Forums.
If it's a one-off and not too complex, you could probably split on symbols manually.
Answer: Another option would be the standard XML Parsers...that is if your document meets the XHTML standards.
Answer: Had searched for a while useful html-parsers for Delphi.
Got lucky with htmlp and HTMLParserEx.
Answer: To parsing small html, use regular expressions.
Comment: For the love of god, never use regular expressions to parse HTML

Best Lightweight HTML Parser for Delphi


Removing variance in $y$ explained by $x$

Question: If I have three variables:

$x$
$y$
$z$

...how would I go about calculating an "adjusted $z$" measure that has the variation in $z$ that is explained by $x$ and $y$ removed?
Comment: Welcome to CV!  This is called the "residual."  See https://stats.stackexchange.com/questions/17336 or https://stats.stackexchange.com/questions/46151 for instance.
Comment: @whuber Right, but how would I use the residuals to get a measure on the same scale as y? Subtract it from the average or real values for example?
Comment: That wouldn't make any sense, because there is no reason why z should even be in commensurate units with y.  Consider, for instance, a regression of income (z) against age (x) and educational attainment (y): you can't put educational attainment on the same scale as income!  The residuals are *income differences:* namely, the differences between the observed and fitted values.
Comment: so sorry man, I meant to say on the same scale as z! Thanks for bearing with me
Answer: It depends on what exactly you mean by the variance of $Z$ after you account for the variance explained by $X$ and $Y$. However, a pretty reasonable interpretation of this relates to the $R^2$ of a linear regression. Use your $X$ and $Y$ to predict $Z$, as in the following model.
$$
\mathbb E[Z_i] = \beta_0 + \beta_1X_i + \beta_2 Y_i
$$
Then use ordinary least squares to estimate the $\beta$ coefficients.
Next, calculate the $R^2$ of this model. Under these conditions with a linear model estimated with ordinary least squares, $R^2$ is interpreted as the porportion of variance of $Z$ that is explained by the regression, so by your predictor variables $X$ and $Y$. This is explained in a standard regression book like Agresti (2015). Consequently, $\left(1-R^2\right)$ is the proportion of variance in $Z$ that is not explained by the regression. You have $Z$, so you can calculare $\text{var}(Z)$. Now multiply $\left(1-R^2\right)\text{var}(Z)$ to get the variance of $Z$ that remains unexplained.
This can be performed in software. I get that the unexplained variance of $Z$ is $0.9792228$.
set.seed(2023)
N <- 100                      # Sample size
x <- rnorm(N)                 # Varible X
y <- rnorm(N)                 # Varible Y
z <- x - y + rnorm(N)         # Variable Z
L <- lm(z ~ x + y)            # Fit the linear model, estimated via
                              # ordinary least squares
r2 <- summary(L)$r.squared    # Calculate R-squared of the regression
var(z) * (1 - r2)             # Variance of Z that is not explained by X and Y

However, this is equal to the variance of the residuals, calculated via var(resid(L)). This is because $R^2$ involves the variance of the the residuals term (estimated variance of $Z$, conditional on $X$ and $Y$) divided by the unconditional (marginal or pooled) variance of $Z$.
$$
R^2 = 1-\dfrac{
\text{var}(Z\vert X, Y)
}{
\text{var}(Z)
}
$$
Since the fraction has the same units in the numerator and denominator, the units cancel and give a unitless $R^2$. Then then math of what I described and simulated in my code is:
$$
(1-R^2)\times(\text{var}(Z))=\\
\left[
1 -\left(
1-\dfrac{
\text{var}(Z\vert X, Y)
}{
\text{var}(Z)
}
\right)
\right]\times(\text{var}(Z))=\\
\dfrac{
\text{var}(Z\vert X, Y)
}{
\text{var}(Z)
}\times(\text{var}(Z))=\\
\text{var}(Z\vert X, Y)
$$
REFERENCE
Agresti, Alan. Foundations of linear and generalized linear models. John Wiley & Sons, 2015.
EDIT
Some issues to consider:

What if the true relationship between $Z$ and $X$ or $Y$ (or both) is not linear, say $Z = X^2 + Y$, but you only fit the regression to $X$ and $Y?$ You are getting at the variance of $Z$ that is or is not explained by $X$ and $Y$ as they enter the regression, yes, but it could be argued (I think strongly) that you aren't really accounting for the entire way in which $X$ explained the variance of $Z$. Dealing with this sort of situation is what leads to regression-strategies like spline basis functions.

If you want to draw inferences to something greater than your observed $Z$, such as a population, there's more to the story, even if fiddling with $R^2$ and the residual variance is the beginning of that story.


Rules for Orange and Purple Caps in IPL

Question: In IPL, Orange and Purple caps are awarded to the highest run scorer and highest wicket taker.
I have three questions on this topic.

If more than one player has equal stats (highest runs or wickets), what will they do?
Consider the following situation,
A player in the field is wearing orange cap for most runs, but in the middle of the innings (it may be first or second) a batsman from the batting side overtakes his runs.
Will he allowed to wear it anymore in that innings?
I didn't see anyone wearing at the time of batting.
Is it permitted to wear these caps while batting?
Answer:
In case of a tie, the Orange cap would be given to the one who has faced lesser balls to achieve this tied score. The Purple cap, in case of a tie at the top, is given to the one who has taken the wickets in the least amount of balls. This can be seen on the official IPL site Purple Cap standings 2013 (the link gets updated at the end of each game. Refer to the screenshot below for the standings as of 14th April where there is a tie) where Vinay Kumar (Royal Challengers Bangalore) and Kevon Cooper (Rajasthan Royals) have the same number of wickets but the purple cap is with Cooper as he has bowled 5 overs fewer than Kumar to get those 8 wickets.

Yes, the Orange cap owner who is fielding will be allowed to wear the orange cap till the end of the innings even if an opposition batsman has overtaken his runs. At the end of the innings, the batsman who has overtaken the said fielder's score will be presented with the orange cap and he can wear that when he comes out to field, assuming he still is the highest scorer. A scenario where a batsman wins the orange cap in the second innings of the game may not have the orange cap when this team runs out to field the next game.

Wiki says that the orange and purple caps are to worn only during fielding. There is no hard and fast rule about these caps while batting. Anyways, there are very few batsmen who bat with caps these days as they almost always come out with helmets, even to spinners. So, if the orange cap holder comes out to bat with a cap, I would assume it is his prerogative to either come out wearing his team cap or the orange/purple cap.
Answer:
If more than one player has equal stats (highest runs or wickets), what will they do?

The player with the better strike-rate wins.

A player in the field is wearing orange cap for most runs, but in the middle of the innings (it may be first or second) a batsmen from the batting side overtakes his runs.

The current highest scorer should have the Orange Cap . In case if it is in the middle of the innings , then one has to wait till the completion of the innings .

Will he allowed to wear it anymore in that innings?
  Is it permitted to wear these caps while batting?

Yes , absolutely . The batter has to decide whether he needs a protective headgear or a cap.
Answer: See answers in points as in questions.

If more than one player has equal stats (highest runs or wickets), what will they do?
A. The player with the better strike rate will get the cap.
Consider the following situation,
A player in the field is wearing orange cap for most runs, but in the middle of the innings (it may be first or second) a batsman from the batting side overtakes his runs.
Will he allowed to wear it anymore in that innings?
A. He will be allowed to wear the cap at the end of the innings and not during it.
I didn't see anyone wearing at the time of batting.
Is it permitted to wear these caps while batting?
A. He cannot wear cap while batting. Orange and Purple caps are only for fielding.
Comment: First two answers are same as already answered. But Do you have any reference to support your last answer. (i.e. wearing caps while batting?)
Comment: The Orange Cap will be awarded to the batsman with the most cumulative runs to his name on each day of the season, and will be worn by that batsman in the field.

Read more at: http://www.thatscricket.com/news/2008/04/25/2504ipl-introduces-orange-cap-award.html
Answer:
If more than one player has equal stats (highest runs or wickets), what will they do?

If some batsmen have same stat then the orange cap holder is the man which played least balls or highest strike rate or most percentage of boundaries then the other one. Same is the case with a best bowler who hold purple cap which have delivered least balls then the other one.

Consider the following situation,
A player in the field is wearing orange cap for most runs, but in the middle of the innings (it may be first or second) a batsman from the batting side overtakes his runs.
Will he allowed to wear it anymore in that innings?

Yes it's allowed to wear that cap in a complete innings rather then taking it off and gave to the other man.
For example
Batsman A is a orange cap holder having 192 runs.
Batsman B is a one step away from that orange cap having 190 runs.
Both the batsmen is playing in alternate ground and playing round match.
Suppose Batsman A is going to play with orange cap and batting on a crease and at the same time Batsman B is playing at crease in some other city.
Batsman B is playing on 40* runs ahead of another one and Batsmen A is playing on 10* runs. So according to rule at the time Batsman B have cap holder but after some time or at the end of an innings Batsmen A scores 60 and Batsmen B scores 50 then Batsmen A can worth their cap and logically it would be unfair to take away cap during the match innings.

I didn't see anyone wearing at the time of batting.
Is it permitted to wear these caps while batting?

Yes its permitted to wear the cap during batting.
Most of the times players remove their helmets and wear cap when any spinner came to crease for bowling. At the time batsman can wear the orange cap ahead of teams uniform cap which will be okay and allowed.
Answer:
In case of a tie the batsman better  strike rate & the bowler with better economic rate will win the orange and purple cap respectively.
Yes,he is allowed till the end of that innings.
Both the caps are allowed to wear at the time of fielding.
Comment: Welcome to Sports.SE, provide some references for your answers, and care should be taken in formatting the answer.
Answer: From IPL Awards 2018:

Match Awards
...
Orange Cap
The Orange Cap will be worn while fielding by the batsman who has scored the most runs in the league (including the Playoffs) during the season to date. It is first awarded once each team has played at least one match and then changes hands when another batsman becomes the highest run scorer in the league to date.  The Orange Cap is presented to the batsman at the end of the innings in which he achieves this feat (either at one of the flash interviews or at the post-match presentation).  In the circumstance where two or more batsmen have scored the same number of runs during the season to date, the Orange Cap will be retained or awarded, as appropriate, to the batsman (of those who are tied) who has the higher strike rate during the season to date.
Purple Cap
The Purple Cap will be worn while fielding by the bowler who has taken the most wickets in the league (including the Playoffs) during the season to date. It is first awarded once each team has played at least one match and then changes hands when another bowler becomes the highest wicket taker in the league to date.  The Purple Cap is presented to the bowler at the end of the innings in which he achieves this feat (either at one of the flash interviews or at the post-match presentation).  In the circumstance where two or more bowlers have taken the same number of wickets during the season to date, the Purple Cap will be retained or awarded, as appropriate, to the bowler (of those who are tied) who has the lowest economy rate during the season to date.

So, the answers to the above questions are,

If more than one player has equal stats (highest runs or wickets), what will they do?

A. In the circumstance where two or more batsmen have scored the same number of runs during the season to date, the Orange Cap will be retained or awarded, as appropriate, to the batsman (of those who are tied) who has the higher strike rate during the season to date. And, when two or more bowlers have taken the same number of wickets during the season to date, the Purple Cap will be retained or awarded, as appropriate, to the bowler (of those who are tied) who has the lowest economy rate during the season to date.

A player in the field is wearing orange cap for most runs, but in the middle of the innings (it may be first or second) a batsman from the batting side overtakes his runs.

Will he allowed to wear it anymore in that innings?

A. As the Orange Cap is presented to the batsman at the end of the innings in which he achieves this feat (either at one of the flash interviews or at the post-match presentation). A player in the field will wear it till the end of innings.

Is it permitted to wear these caps while batting?

A. The Orange Cap will be worn while fielding by the batsman who has scored the most runs in the league (including the Playoffs) during the season to date. And, the Purple Cap will be worn while fielding by the bowler who has taken the most wickets in the league (including the Playoffs) during the season to date. So, it is not permitted to wear these caps while batting.

Rules for Orange and Purple Caps in IPL


Como buscar a impressora padrão e imprimir texto simples em uma impressora matricial no .NET?

Question: Temos uma impressora térmica que não suporta a impressão de elementos gráficos - neste caso, terei que enviar textos simples para ela.
Considerando que nosso aplicativo rodará em diversos computadores diferentes, cada um deles conectado a uma impressora distinta e que por sua vez poderão estar configuradas em portas diferentes em cada máquina (COM1, COM2, etc.), teremos que adotar a impressora padrão como destino da saída do texto a imprimir.
Portanto: No .NET, como posso buscar a impressora padrão e imprimir textos "crús" nela?
Answer: Para pegar a impressora padrão use a classe PrinterSettings(em inglês). Exemplo:
var configImpressora = new PrinterSettings();
Console.WriteLine(configImpressora.PrinterName);

Note que desta forma você está usando o gerenciador do Windows para obter essa informação. E o que você precisa fazer para enviar os dados é justamente o oposto.
Pegar qual é a impressora padrão não vai ajudar muita coisa porque isso não garante que a impressora que está lá é adequada para o que você deseja. E mesmo que mande para ela, enviará para o gerenciador do Windows que é justamente o que você NÃO quer fazer.
Salvo eu não saber de algo sobre o assunto, duvido que essa parte te ajude em alguma coisa.
Quanto a segunda parte da pergunta:
Essencialmente você precisa escrever diretamente na porta, normalmente PRN ou LPT1 ou COM1. mandando diretamente para a porta você evitar passar pelo gerenciador de impressão do Windows,
Exemplo simplificado (não tem a qualidade que um código em produção deveria ter):
var impressora = new System.IO.StreamWriter(@"\\.\PRN");
impressora.Write((char)15); //inicia negrito na maioria das impressoras matriciais
impressora.Write("Teste");
impressora.Flush();
impressora.Close();

Quando precisei mandar para uma impressora padrão, foi basicamente isso que eu fiz.
Se você precisa escolher onde a impressora está em cada máquina, receio que você deverá que ter uma configuração local indicando onde está a impressora. Pode ser um simples arquivo de texto, mas pode ser um banco de dados local, o registro do Windows ou simplesmente permitir que o usuário escolha no momento de mandar imprimir, o que pode ser suficiente em muitos casos.
Coloquei no Github para referência futura.
Answer: Depois de algumas buscas, segue a forma que conseguimos fazer: Não é tão elegante (tivemos que apelar para chamadas P/Invoke1), mas funcionou muito bem.
using System.Drawing.Printing;
(...)
public void ImprimeConteudoDiretamenteNaImpressoraPadrao(string conteudo)
{
    string nomeImpressoraPadrao = (new PrinterSettings()).PrinterName;
    RawPrinterHelper.SendStringToPrinter(nomeImpressoraPadrao, conteudo);
}

Método RawPrinterHelper.SendStringToPrinter está definido no código retirado deste artigo (Passo 8).


How do I set up nginx-debug on Ubuntu 14.04 server?

Question: I'm reading this guide on enabling a debugging log in nginx: https://nginx.org/en/docs/debugging_log.html
I have a Ubuntu 14.04 server. In which directories must I run these commands
./configure --with-debug
error_log /path/to/log debug;
configure arguments: --with-debug

Answer: Nowhere. The nginx version provided by Ubuntu already is compiled with the debug option. The steps shown in that guide are meant to be used when compiling your own version of nginx, which you definitely should not do if you have to ask the question you asked.
Comment: Where can I find the debug file? Or at least find out where to find it?
Comment: @Username You find it wherever you _specified_ its location to be.
Comment: @Username when you add `error_log /path/to/log debug;` to `nginx` config, you will get debug log at `/path/to/log` file.
Answer: Apparently reading a guide can be interpreted in several ways. Worth to mention here is that not everything written in fixed-width blocks are commands, and the bread text in between those blocks is essential to read, too, in order to know the context. The fixed-width block could represent

commands (service nginx stop)
partial commands (./configure --with-debug ...)
configuration file content (error_log /path/to/log debug;)
output of a command (configure arguments: --with-debug ... from nginx -V)
script (while $log->writer != ngx_log_memory_writer) or source code
something malicious you could copy-paste to your command line with this attitude.

Now that you've learned how to read all manuals, guides and tutorials, everything you need is in the NGINX debugging log guide:

Pre-built Linux packages provide out-of-the-box support for debugging
  log with the nginx-debug binary (1.9.8) which can be run using
  commands
service nginx stop
service nginx-debug start

and then set the debug level. Note that redefining the log without
  also specifying the debug level will disable the debugging log. In the
  example below, redefining the log on the server level disables the
  debugging log for this server:
error_log /path/to/log debug;

http {
    server {
        error_log /path/to/log;
        ...

This means that with the packages from NGINX repository (since version 1.9.8) you'd have the nginx-debug service, but nginx-common in trusty doesn't seem to provide it as it's build to the default binary. All you need to do is to modify your configuration.
Now seek for the error_log directives through your configuration (/etc/nginx/nginx.conf). With syntax error_log file [level]; you should add (or alter) the level debug, the file being your path. If there's no level specified, default level error gets used.
Answer: https://docs.nginx.com/nginx/admin-guide/monitoring/debugging/#debug-log-for-selected-ips
Debug Log for Selected IPs
error_log /path/to/log;
...
events {
    debug_connection 192.168.1.1;
    debug_connection 192.168.10.0/24;
}


Another proof of reflexive Hilbert spaces

Question: Here is the proof that every Hilbert space is refexive:
Let $\varphi\in\mathcal{H^{**}}$ be arbitrary. By Riesz, there is a unique $f_\varphi\in\mathcal{H^*}$ with
$\varphi(f)=\langle\,f,f_\varphi\rangle$ for all $f \in\mathcal{H^*} $.
Using the same notation and theorem, we have
$\hat{y}_{f_\varphi}(f)= f(y_{f_\varphi})=\langle\,y_{f_\varphi},y_f\rangle=\langle\,f,f_\varphi\rangle=\varphi(f)$
This implies $\hat{y}_{f_\varphi}=\varphi$, thus $\mathcal{H}$ reflexive.
I understood all the steps except for the last implication. Basically, we just showed that $2$ functionals from bi-dual space $\mathcal{H^{**}}$ are the same, why would it imply that $\mathcal{H}$ is reflexive? Any explanation would be highly appreciated!
Comment: Remember that $\mathcal H$ is reflexive if the canonical injective map from $\mathcal H$ to $\mathcal H^{**}$ is also surjective
Comment: @Omnomnomnom I'm awared of that, but can't still get the idea somehow .. Could you please give more precise explanation? This is not an exercise by the way, just preparation for the exam :)
Comment: There's a missing item in the last equation. The leftmost term should be $\hat y_{f_\varphi} {\bf(f)} =f(y_{f_\varphi})=\dots$.
Comment: @Berci yes, you're right! I've just edited. Thanks!
Answer: Let $\Phi:\mathcal H \to \mathcal H^{**}$ denote the canonical injection, AKA the evaluation map (in the notation of the proof, $\Phi(x) = \hat x$)t.  We want to prove that $\Phi$ is surjective.  In other words: we want to prove that for any $\varphi \in \mathcal H^{**}$, there exists a $y \in \mathcal H$ such that $\Phi(y) = \varphi$.
So, begin with any $\varphi$.  By the RRT, there exists a unique $f_{\varphi}$ such that for all $f \in \mathcal H^*$, $\varphi(f) = \langle f, f_{\varphi}\rangle$.
Note that this requires that requires an inner product on $\mathcal H^*$. Recall how such an inner product is defined: RRT says that there exists a $y_f$ for every $f \in \mathcal H^*$ such that for $y \in \mathcal H$, we have $f(y) = \langle y,y_f\rangle$. With this established, we define
$$
\langle f,g \rangle := \langle y_f,y_g\rangle.
$$
We claim that $\Phi(y_{f_{\varphi}}) = \varphi$ (that is, $y_{f_{\varphi}}$ is "the $y$ that we're looking for").  Indeed, we note that for any $f \in \mathcal H^*$, we have
$$
[\Phi(y_{f_{\varphi}})](f) = f(y_{f_{\varphi}}) = \langle y_{f_\varphi},y_f \rangle
= \langle f, f_{\varphi}\rangle = \varphi(f)
$$
Comment: @jasmine Note that $f_{\varphi} \in \mathcal H^*$. If $f \in \mathcal H^*$, then what does $f_\varphi(f)$ mean? $f_{\varphi}(x)$ only makes sense for $x \in \mathcal H$.
Comment: ..@Ben Grossmann  I have   some confusion in ur third paragraph that we have $f(y_{f_{\varphi}}) = \langle f, f_{\varphi}\rangle$.

I think it should be  $f(y_{f_{\varphi}}) = \langle y_{f_{\varphi}}, f_{\varphi}\rangle$.
My doubts is that why written $f(y_{f_{\varphi}}) = \langle f, f_{\varphi}\rangle?$.
Comment: @jasmine It is not clear why you think that. Note that your equation $f(y_{f_{\varphi}}) = \langle y_{f_{\varphi}}, f_{\varphi}\rangle$ implies that $f(y_{f_{\varphi}})$ is the same for *every* $f \in \mathcal H^*$.
Comment: @jasmine Do you understand the Riesz Representation Theorem (which I refer to as "RRT")?
Comment: yes i understand @Benn Grossmann and **My thinking** : RRT say that "for every $f \in H^*$ there exists a unique $v_f \in H$ such that $f(u)=\langle u,v_f \rangle$ for all $u \in H$....continue  next comment
Comment: ..@Benn Grossmann  acoording to the ur answer  Now, $f_{\varphi} \in \mathcal H^*$. By the RRT, there exists a unique $y_{f_{\varphi}}$ such that for all $f \in \mathcal H^*$, we have $f(y_{f_{\varphi}}) = \langle f, f_{\varphi}\rangle$.

According RRT its should be   $f_{\varphi}(f) = \langle f, y_{f_{\varphi}}\rangle$ but not $f(y_{f_{\varphi}}) = \langle f, f_{\varphi}\rangle$.

So im not understanding  why you written $f(y_{f_{\varphi}}) = \langle f, f_{\varphi}\rangle?$.
Comment: .@Ben Grossmann let me think more ...actually i didn't read the RRT Throughly
Comment: .@Ben Grossmann if u have time   u can see  this post :https://math.stackexchange.com/questions/3986297/why-fy-f-varphi-langle-f-f-varphi-rangle
Comment: oks  got its now   thanks  u @Ben  Grossmann
Answer: The point is that $\varphi \in \mathcal{H}^{**}$ was arbitrary, and your proof shows that it agrees with another element of $\mathcal{H}^{**}$ which has a particular form, thus showing that every element of $\mathcal{H}^{**}$ has that special form.  To see why that is a proof of reflexivity, let's review the general situation:
Let $X$ be a Banach space.  For any $y \in X$, we have a functional $\varphi_y \in X^{**}$ defined by $\varphi_y(f) = f(y)$.  The map $y \mapsto \varphi_y$ is always an isometric linear embedding of $X$ into $X^{**}$, so the issue is to check that this map is surjective.
Proving surjectivity is exactly this: Given any $\varphi \in X^{**}$, find a $y \in X$ such that for all $f \in X^*$, $\varphi(f) = f(y)$.  The proof you've given here is exactly finding such a $y$.


Adding gray line b/w paragraph in iText 7

Question: I am not sure how to add the gray line like in the image b/w paragraphs in Itext 7.
Should I use rectangle for this with very small width and the whole page length?
Rectangle rect= new Rectangle(1, 400);

How to get whole page length as opposed to hard code the same?
Answer: You can use the following piece of code:
Document document = new Document(pdfDocument);

document.add(new Paragraph("Hello"));
document.add(new Div().setHeight(5).setBackgroundColor(ColorConstants.LIGHT_GRAY));
document.add(new Paragraph("World"));

document.close();

To achieve the result as displayed on the image:
Comment: Could you please help with https://stackoverflow.com/questions/63878140/itext-7-adding-border-for-the-page?
Comment: @user1578872 I posted an answer to that question 22 hours ago


Asymptotic expansion of $a_1=1$, $a_n=a_{n-1}-\frac{a_{n-1}^2}2$

Question: Given the function $f(x)=x-\frac{x^2}2$ and $a_1=1$, $a_n=f(a_{n-1})$. Find the asymptotic expansion of $a_n$ to the $O(1/n^3)$ term as $n\to\infty$.
Attempt (to the $O(1/n)$ term)

Step 1
  $$a_n=o(1)$$

As $|f(x)|<x$, $x\in(0,1]$, $\lim\limits_{n\to\infty}a_n=0$.

Step 2
  $$a_n=\frac 2n+o(\frac 1n)$$

This step is equivalent to finding the value of $\lim\limits_{n\to\infty}n a_n$.
$$\lim_{n\to\infty}n a_n=\lim_{n\to\infty}\frac n{\frac 1{a_n}}=\lim_{n\to\infty}\frac{n-(n-1)}{\frac 1{a_n}-\frac 1{a_{n-1}}}=\lim_{x\to0}\frac 1{\frac1{x-x^2/2}-\frac1x}=2$$

Step 3 & 4 (only a guess)
  $$a_n=\frac 2n-\frac{2\ln n}{n^2}+o(\frac{\ln n}{n^2})$$
  $$a_n=\frac 2n-\frac{2\ln n}{n^2}+\frac{\text{a constant}}{n^2}+o(\frac 1{n^2})$$

This is equivalent to finding the limit $\lim\limits_{n\to\infty}\frac{n^2}{\ln n}(a_n-\frac2n)$ and $\lim\limits_{n\to\infty}n^2(a_n-\frac2n+\frac{2\ln n}{n^2})$
I can't go further. I think the condition $a_n=1$ should be used well in Step 3.
Comment: Your $+$ turns to a $-$. This makes a big difference. Make up your mind.
Comment: @YvesDaoust thanks about pointing out the typo. It is fixed now. :)
Comment: This is very close to [MSE question 2861768](https://math.stackexchange.com/q/2861768) "Calculate $\lim_{n\to\infty} n(1-na_n)/\log n$". where there $a_{n+1}=a_n-a_n^2.$
Comment: @Somos Thanks, that helps, but some of the terms the answers give is implicit. I don't know how to find the terms related to $a_1$.
Comment: The dependence on $a_1$ is a numerical constant $c$. Read my answer to the linked question.
Comment: @Somos Yes, I want to find the exact value of $c$ with given $a_1$. (But probably there's no closed form?)
Answer: One starts with $a_n=o(1)$ which follows from the facts that all $a_n$ are in $[0,1]$,
$a_n\leq a_{n-1}$ and $f(x)=x$ has only the zero solution in $[0,1]$. Then the trick is to expand $$\tag1\frac1{a_{n+1}}=\frac1{a_n(1-\frac{a_n}2)}=\frac1{a_n}+\frac12+\frac14a_n+O(a_n^2).$$
This implies that $\frac1{a_{n+1}}-\frac1{a_n}$ tends to $\frac12$. By Cesaro's theorem
$\frac1{n-1}\sum_{j=1}^{n-1}(\frac1{a_{j+1}}-\frac1{a_j})=\frac1{n-1}(\frac1{a_n}-\frac1{a_1})$ also tends to $\frac12$ and therefore $a_n=\frac2n+o(\frac1n)$.
Inserting into (1) gives
$$\frac1{a_{n+1}}-\frac1{a_n}=\frac12+O(\frac1n)$$
and by summing as above we obtain that $\frac1{a_n}=\frac n2+O(\log(n))$. Hence $a_n=\frac2n+O(\frac 1{n^2}\log n)$. Inserting into (1) again gives
$$\frac1{a_{n+1}}-\frac1{a_n}=\frac12+\frac1{2n}+O(\frac 1{n^2}\log n).$$
Now the sequence $b_n=\frac1{a_n}-\frac n2-\frac12\log n$ satisfies $b_{n+1}-b_n=O(\frac 1{n^2}\log n).$ (Just use the Taylor expansion of the logarithm).
As $\sum_{n=1}^\infty \frac 1{n^2}\log n$ converges, $b_n$ tends to a limit we call $\beta$. Since $\beta-b_n=\sum_{k\geq n}(b_{k+1}-b_k)$, we find that $b_n=\beta+O(\frac1n\log n)$ that is $\frac1{a_n}=\frac n2+\frac12\log n+\beta+O(\frac1n\log(n))$. This means that
$$a_n=\frac2n-\frac 2{n^2}\log n-\frac{4\beta}{n^2}+\frac 2{n^3}\log^2 n+O(\frac 1{n^3}\log n)$$
with the above constant $\beta$. This does not solve the problem to the $O(\frac1{n^3})$ term, but the last necessary step is analogous: Inserting into (1) again to refine the asymptotic behavior of the above $b_n$ and sum from $k=n$ to infinity again. I do not want to do that.
The constant $\beta$ can be determined numerically. It is the equivalent of the Euler constant in the present context. I doubt that there is an explicit form of this constant.
Edit:  1.I calculated $\beta=0.38399...$.
2. The recursion $a_{n+1}=\sin(a_n)$ can be treated similarly. Only here,
$\frac1{a_{n+1}^2}-\frac1{a_n^2}$ has to be expanded...


Imap to imap migration?

Question: I am currently migrating a website, and my usual method is working with mail clients, and copy the old mailbox to the new server mailbox.
But, if you have a website, with multiple mailboxes, and those mailboxes have numerous folders, the work usually takes all day.
I have searched the Internet for a far more easy and faster way, preferably open-source, but most tools are ancient, and the Q/A here are years old.
Wat is the faster and easier way of migrating mailboxes?
Paid tool:

imapsync

Free Tool

imapfw

Note:

I have root access on the destination server, and not on the source.
I downloaded the e-mails with the following settings

mail.DONAINNAME.com: IMAP (for receiving)
smtp.DOMAINNAME.com: SMTP (for sending)
Comment: What tools? What Q/A? You've not specified the IMAP server and the mailbox format.
Comment: Still no IMAP server and mailbox format. The reason I ask is if it's Dovecot that ships a `dsync` tool for synchronising mailboxes. Also some mailbox formats lend themselves quite well to just using archiving tools like `tar` or `rsync`, etc.
Comment: @bodgit I just checked, `file`  says they are `SMTP mail, ASCII text`. And I have founded `dovecot` process. Right now playing around with `imapcopy`.
Comment: @RyanBabchishin `asked    5 years ago`
Comment: @blade19899 It's not helpful?
Comment: @RyanBabchishin some or no longer in development, and other are proprietary software. Might look at that when all my other options are exhausted.
Comment: @blade19899 imapsync, imapcopy, etc... many links still work in that question and goto projects that are currently maintained. Seems your answers are there.
Comment: If you're migrating a website why are you touching email?
Comment: Imapsync is also gratis at https://imapsync.lamiral.info/dist/ or https://github.com/imapsync/imapsync
Answer: Are both IMAP daemons the same? Do they have the same mailbox format?
If you have administrative control over these servers and their mailbox format is the same, you do not need special tools as noted by bodgit in the comments. You can just tar/compress the data and transfer it or rsync it, etc... just like any other data.
There's no need for special tools
I do suggest using compression as email is generally highly compressible. That should save you some time. Those imap tools you're using may not use compression.
If you have special requirements, please update your question for further assistance.
Comment: I think they are the same. I don't have root access on the other server. Whit the information I have can't seem to find out. But, I think they are exactly they same. Also, I cant access the dir where the emails are stored on the server, so can't rsync the data. @bodgit
Comment: @blade19899 You can't access the mailboxes? You must use the IMAP protocol? If that's true, you should put it in your question. That changes everything. Also please specify which server you do have root access on and which you don't.

Imap to imap migration?


Apache Proxypass redirects "localhost:port" as url string instead of local service of the port

Question: Environment
Server version: Apache/2.4.6 (CentOS)

I have two servers which are almost duplicates.
aaa.com. and bbb.com.
They have almost same Apache rulesets.
aaa.com. config
<Location "/serviceEndpoint/">
  ProxyPass http://localhost:8100/serviceEndpoint/
  ProxyPassReverse http://localhost:8100/serviceEndpoint/
</Location>
<Location "/fruit/apple">
  ProxyPass "/fruit/apple" "http://localhost:8100/serviceEndpoint/fruit/apple"
  ProxyPassReverse "/fruit/apple" "http://localhost:8100/serviceEndpoint/fruit/apple"
</Location>

So /serviceEndpoint is a service using 8100 port, and /fruit/apple  is a servlet of it.
bbb.com. config
<VirtualHost _default_:80>
  ProxyPass "/serviceEndpoint/" "http://localhost:20100/serviceEndpoint/"
  ProxyPassReverse "/serviceEndpoint/" "http://localhost:20100/serviceEndpoint/"

  ProxyPass "/fruit/apple" "http://localhost:20100/serviceEndpoint/fruit/apple"
  ProxyPassReverse "/fruit/apple" "http://localhost:20100/serviceEndpoint/fruit/apple"
</VirtualHost>

Looks the same, but it's inside VirtualHost:80, if that makes anything different.
(*edit I tested using the same config, but the result was same)
Problem
Both aaa.com/fruit/apple or bbb.com/fruit/apple works well.
But, when the service use response.sendRedirect()(java) and redirects the browser to /fruit/apple,
only aaa.com. works and bbb.com. tries to connect literal http://localhost:20100/fruit/apple from the client browser.
aaa.com redirect response header
HTTP/1.1 302
Date: Mon, 09 May 2022 08:01:29 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=63072000; includeSubDomains
Location: /fruit/#!/some_controller
Content-Length: 0
Set-Cookie: JSESSIONID=4EA61F0E6031621E540DBDC9F6C54D64; Path=/serviceEndpoint; HttpOnly
Set-Cookie: JSESSIONID=4EA61F0E6031621E540DBDC9F6C54D64; Secure; HttpOnly; SameSite=Strict
X-XSS-Protection: 1; mode=block
Keep-Alive: timeout=15, max=95
Connection: Keep-Alive

bbb.com redirect response header
HTTP/1.1 302
Date: Mon, 09 May 2022 08:01:29 GMT
Server: Apache-Coyote/1.1
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=63072000; includeSubDomains
Location: http://localhost:20100/fruit/#!/some_controller
Content-Length: 0
Set-Cookie: JSESSIONID=4EA61F0E6031621E540DBDC9F6C54D64; Path=/serviceEndpoint; HttpOnly
Set-Cookie: JSESSIONID=4EA61F0E6031621E540DBDC9F6C54D64; Secure; HttpOnly; SameSite=Strict
Keep-Alive: timeout=15, max=95
Connection: Keep-Alive

Question
From Apache settings, what can cause this behavior and how should I fix this?
Comment: The redirect does not come from Apache. Configure your Backend service with the proper URL to redirect to.
Comment: @GeraldSchneider The redirect path is `/fruit/apple` and service works fine with `aaa.com.` What could causes this discrepancy?
Comment: @GeraldSchneider `aaa.com` operates on Tomcat 8.5, and `bbb.com` operates on Tomcat 8.0. Would it affect how `response.sendRedirect()` behave?
Answer: That ProxyPassReverse directive defines the scope of the URL path(s)  that Apache most correct for in back-end responses to ensure that site vistors are presented with a correct URL that matches their requests to the Apache
ProxyPassReverse "/fruit/apple" "http://localhost:20100/serviceEndpoint/fruit/apple"

The bbb.example.com response redirects to
 Location: http://localhost:20100/fruit/#!/some_controller
                                       \
                                        `- "apple" is missing .

and therefor the Location header is not corrected for by the ProxyPassReverse directive.
That seems like either the back-end application does not create correct self-referential URL's and you need to solve that in the back-end application, or you have made an incorrect assumption and your apache config should be:
ProxyPass "/fruit/" "http://localhost:20100/serviceEndpoint/fruit/"
ProxyPassReverse "/fruit/" "http://localhost:20100/serviceEndpoint/fruit/"

Comment: `aaa.com.` redirects normally to `https://aaa.com/apple/#!/some_controller`. What could make this difference?
Answer: It was Tomcat difference. Tomcat 8.0 redirects to localhost, whereas 8.5 redirects normally.


Angular 2 - hide bootstrap navbar on nav click

Question: In mobile, clicking bootstrap navbar item does't hide the menu.
My menu button, which shows for mobiles:
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

Searching for this issue returned results unreleated to angular 2 and I have no idea how to implement them.
How I can I hide my navbar when user clicks a link?

Click this should hide nav

Answer: Pretty nice and easy way to do it within Angular 2/4 template only:

      <button type="button" class="navbar-toggle collapsed" (click)="isCollapsed = !isCollapsed">

      </button>

Home

About

Portfolio

Contacts

Comment: I had to change [ngClass]="{collapse: isCollapsed}" to {collapse: !isCollapsed} else the menu was shown each time the page was loaded.
Answer: You could add a custom directive that does it for you
import { Directive, ElementRef, Input, HostListener } from "@angular/core";

@Directive({
    selector: "[menuClose]"
})
export class CloseMenuDirective {
    @Input()
    public menu: any;

    constructor(private element: ElementRef) { }

    @HostListener("click")
    private onClick() {
        this.menu.classList.remove("show");
    }
}

Don't forget to add this to your app.module in the declarations array
import { CloseMenuDirective } from './directives/close-menu.directive';
@NgModule({
    declarations: [
        ...declarations,
        CloseMenuDirective
    ]
})
export class AppModule { }

And then in your HTML you create a reference to your menu and pass that to your link element.

                    My Link

Comment: How does it not work? If you are interested in help you need to specify the details. Do you get an error?
Comment: I think the reason is I am using bootstap 3.3.7 and there is no `show` class for navbar; it is `in`
Comment: I believe the correct class may be "open" in that case
Answer: This code simulates a click on the burguer button to close the navbar by clicking on a link in the menu, keeping the fade out effect. Solution with typescript for angular 7. Avoid routerLink problems.
ToggleNavBar () {
    let element: HTMLElement = document.getElementsByClassName( 'navbar-toggler' )[ 0 ] as HTMLElement;
    if ( element.getAttribute( 'aria-expanded' ) == 'true' ) {
        element.click();
    }
}

    link1

Comment: I would rename it to closeNavBar
Answer: This is a limitation of navbar (https://github.com/valor-software/ngx-bootstrap/issues/540). So you need to manipulate the DOM element.

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
        Toggle navigation

    </button>

Home

About

And on .ts file your minimal code shoul be:
import { Component, ElementRef, Renderer } from '@angular/core';

export class HeaderComponent {
    constructor(private el: ElementRef, private renderer: Renderer) {
    }
    onMenuClick() {
        //this.el.nativeElement.querySelector('.navbar-ex1-collapse')  get the DOM
        //this.renderer.setElementClass('DOM-Element', 'css-class-you-want-to-add', false) if 3rd value is true
        //it will add the css class. 'in' class is responsible for showing the menu.
        this.renderer.setElementClass(this.el.nativeElement.querySelector('.navbar-ex1-collapse'), 'in', false);
    }
}

Answer: On the recent version of bootstrap (4.0) you achieve what you need by using data-target=".show". "show" is a class attached to the collapsible element, to make it visible.
Example:
<button class="btn btn-primary" data-toggle="collapse" data-target=".show">Link_1</button>


Check whether names(df) is in other character list giving both true and false values back

Question: I have the following
structure(list(id = c(14, 15, 16, 17, 18), a = c(1, 2, 3, 5,
6), b = c(3, NA, 2, 5, 7), c = c(1, 2, 3, 4, 5)), row.names = c(NA,
-5L), class = "data.frame")

  id a  b c
1 14 1  3 1
2 15 2 NA 2
3 16 3  2 3
4 17 5  5 4
5 18 6  7 5

library(caret)
corr <- cor(na.omit(df))
highcorr <- findCorrelation(corr, cutoff = 0.9, names=TRUE)

highcorr
[1] "a"  "id"

I would like to get a new data frame where if the col name is in highcorr returns true, else false. New data frame would look like this
  col   result
1 id    TRUE
2 a     TRUE
3 b     FALSE
4 c     FALSE

I think I'm thinking way too difficult. I tried things with %in% but then you only get the TRUE values. Any suggestion would be appreciated :)!
Comment: `data.frame(col=names(df), result=names(df) %in% highcorr)`
Answer: You can use below code:
library(reshape2)
library(dplyr)
a<-melt(corr,value.name = "corr")
a<-a[!duplicated(a$corr),]
a<- a %>% select(Var1, corr)%>% mutate(result = ifelse(corr > 0.9,T,F )) %>% select(Var1, result)

  Var1  result
1   id  TRUE
2    a  TRUE
3    b FALSE
4    b FALSE


Alternatives to population pyramids

Question: In a comment thread relative to another question, Nick Cox says:

Population pyramids are over-rated. Subtle shifts in the ratio females
to males, or its reciprocal, are important and common and expected but
very hard to read off pyramids. (Bigger shifts are those you can spot
easily.)

I then asked him what would be a good alternative to population pyramids (my initial idea was to use overlapping bars with some transparency). He replied:

Plot male and female frequencies on the same axis as dots or lines.
Log scale optional, but consistent with the idea that the ratio of
either is of central interest.

I learned something thanks to these comments, but now I have additional questions:

What are some other advantages of dot/line plots over population pyramids, besides identifying small shifts more easily?

When using a dot/line plot as described above, are there situations where a log scale would be a bad idea?

What are some other good alternatives to population pyramids, besides dot/line plots?

Thank you.
Answer: I can offer comments on #1 and #2. My concrete comments focus on population pyramids for human (or even other) populations with various age groups and conventionally two genders or sexes(*). The simplest examples compare the numbers of people of different age groups and sexes, but the idea can be extended to say numbers of cases of, or deaths from, different diseases or conditions.
Further, it should be clear, or at least you may want to consider, whenever comments also apply to other set-ups with two sets of quantities that are being compared, say imports and exports, votes for and against, and so forth.

What are some other advantages of dot/line plots over population
pyramids, besides identifying small shifts more easily?

To compare frequencies of two sexes, as conventionally distinguished, population pyramids require the reader to look at pairs of bars that are juxtaposed and assess whether they are about the same length. The task of comparison would be much easier if the same information were superimposed. It's then a matter of judgment whether you continue to use bars, or switch to dots (point symbols) or lines.
There is also scope to use (e.g.) logarithmic scale.
The advantages of this proposal go further. Often you can see small frequencies more easily too, usually but not always those for much older people.
Dot and line plots can be extended more easily to comparing e.g. the same country in different years or different countries in the same year. Many comparisons of this kind entail looking at small but nevertheless interesting or important changes. Comparing two or more population pyramids placed side by side is even more difficult than comparing bars on left and right sides of one pyramid. (It's not an accident that we're echoing standard critiques of pie charts, and even of bar charts in general.)
There is an extra dimension. If information is available for other gender categories, the use of paired bars can't be sustained easily or effectively, In practice, in societies I know about, numbers identifying or identified as non-binary, transgender, or other categories are likely to be much smaller, a further argument for logarithmic scales.

When using a dot/line plot as described above, are there situations
where a log scale would be a bad idea?

Log scales might be unfamiliar to the intended audience. They might seem awkward if some of the frequencies were very small and variations in those were more evident than variations between the more frequent categories. More generally, some people might think that logarithmic scales distort the data. (I have heard this objection even from experienced scientists who seemingly don't have difficulty in thinking about percent changes in prices or wages.)
Otherwise, it is standard that zeros cannot be shown on logarithmic scales. That constraint can be important for small populations.
Turn and turn about, for any society with some of each gender, but very different numbers, say some prisons, monasteries, convents, scientific  laboratories, or parliaments, log scale might make the imbalance easier to see.
Various alternatives include square root or cube root scales, or plotting separately total population and a measure such as (# females MINUS # males) / (# females PLUS # males), which is defined for all situations with two genders.
Brinton (1914) had cogent criticisms of population pyramids in this vein. See also Cliff and Haggett (1988).
Brinton, W.C. 1914. Graphic Methods for Presenting Facts. New York: Engineering Magazine Company.
Cliff, A.D. and Haggett, P. 1988. Atlas of Disease Distributions: Analytic Approaches to Epidemiological Data. Oxford: Blackwell.
See this thread on Statalist for some data and an example graph. It doesn't go as far as logarithmic scale, but play (experiment!) should be trivial in your own favourite software. (If not, you need new favourite software.)
EDIT
I downloaded some data from an official source with populations for the United States. For simplicity I ignored the highest age-group of 85 years up.
Here is one of many possible graphical takes. It's conservative in using bars and a little radical in superimposing them. It's a little adventurous in showing sex imbalance as a linked panel.
An advantage of bars is that they do make explicit the age intervals to which they apply.

(*) I am aware of, and attempt to be sensitive to, views and arguments about the words that are best to use in this context. I am focusing on what to do with what is presented as data, while recognising that that raises a whole bundle of other issues.

Alternatives to population pyramids


Expressing infinite elements each equivalence class in First Order logic

Question: I was going through some FO-logic ideas for my logic exam revision and came across some problems...
Equivalence relations can be expressed in FO-logic by the set of axioms:
$\{\forall x Rxx, \forall x \forall y(Rxy \rightarrow Ryx), \forall x \forall y \forall z (Rxy \wedge Ryz \rightarrow Rxz)\}$, where $R$ is a congruence relation
How can we then express the additional requirement that every equivalence class has infinitely many elements? I believe this axiomatic system is infinite but nonetheless axiomatizable.
A similar requirement would be that a universe has infinitely many equivalence classes. How do we generally go about formulating an axiomatic system for such expressions?
Answer: We assume that your system is the usual first-order logic with equality.
For $n\ge 2$, let $S_n$ be the sentence that says $\forall x\exists y_1\exists y_2\cdots \exists y_n\phi(x,y_1,y_2,\dots, y_n)$. Here $\phi$ is the conjunction of (i) formulas $R(x,y_i)$, where $i$ ranges over the integers from $1$ to $n$ and (ii) formulas of the shape $\lnot(y_i=y_j)$, for all $i,j$ where $1\le i\lt j\le n$.
Adding all the $S_n$ to your axiom system forces all the equivalence classes to have infinitely many elements.
Forcing infinitely many equivalence classes is simpler. Let $T_n$ be the sentence that says that $\exists x_1\exists x_2\cdots \exists x_n\psi(x_1,x_2,\dots,x_n)$. Here $\psi$ is the conjunction of all $\lnot R(x_i,x_j)$, where $i,j$ ranges over all $1\le i\lt j\le n$. Adding $T_n$ for all $n\ge 2$ forces the existence of infinitely many equivalence classes.


Admob close button is upper the safe area on iPhone 12

Question: Using Google-Mobile-Ads-SDK 7.68, users can't close GADInterstitial, the close button is upper the safe area (user interaction is not permitted here) :

It's happening at least on iPhone 12 pro and iPhone 12 pro max.
What I tried :
<code>GADInterstitial *interstitial = [[GADInterstitial alloc] initWithAdUnitID:@"xxx"];
GADRequest *request = [GADRequest request];
[interstitial loadRequest:request];
</code>
Comment: same issue here
Answer: Hiding status bar let the user click on the close button. Ugly deprecated method, but it's working for now.
<code>/// Tells the delegate that an interstitial will be presented.
- (void)interstitialWillPresentScreen:(GADInterstitial *)ad {
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

/// Tells the delegate an ad request failed.
- (void)interstitial:(GADInterstitial *)ad didFailToReceiveAdWithError:(GADRequestError *)error {
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

/// Tells the delegate the interstitial is to be animated off the screen.
- (void)interstitialWillDismissScreen:(GADInterstitial *)ad {
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

/// Tells the delegate that a user click will open another app
/// (such as the App Store), backgrounding the current app.
- (void)interstitialWillLeaveApplication:(GADInterstitial *)ad {
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}
</code>
Comment: Thank you for providing this solution. It's bit quick and dirty but this is the best solution we have until Google fixes this issue.


Getting path of images from the model in Rails

Question: I'm working on a mapping application which uses a module called Gmaps4Rails.  Using this gem I define the path to images from within my model and can have it based on some data which image I'm using.
It's working fine in development environment but it breaks on production because it can't find the image folder.  This is how the code looks like inside the model:
  def gmaps4rails_marker_picture

    {
    "picture" => "/images/oilpumpjack.png",
    "width" => "32",
    "height" => "32"
    }
  end

Is there any easy way of getting the correct path from within the model (I don't want to hardcode it)?
Regards,
Johann
Comment: How are you accessing the image in the template? Is your asset directory somewhere else in production?
Comment: The asset directory is on same location (relative to the app) as on development.  I'm using a built in gem function to access the map:  =gmaps({"map_options" => { "zoom" => 6,"center_latitude" => 65, "center_longitude" => -19},"markers" => { "data" => @json }})
Answer: If you are using Sprockets for serving images, try this:
def gmaps4rails_marker_picture
    {
    "picture" => ActionController::Base.helpers.asset_path('oilpumpjack.png'),
    "width" => "32",
    "height" => "32"
    }
end

Answer: Give this a go, it might work:
change
"picture" => "/images/oilpumpjack.png"

to this
"picture" => "#{Rails.root}/public/images/oilpumpjack.png"

i was having a similar problem with another gem.hope it helps
edit
In config/environments/production.rb set
config.serve_static_assets = true

Comment: I'm getting closer.  This creates the correct path but now I'm getting a route error:  Started GET "/var/app/public/images/oilpumpjack.png" for x.x.x.x at Sat Sep 10 20:52:56 +0000 2011

ActionController::RoutingError (No route matches "/var/app/public/images/oilpumpjack.png"):
Comment: No, I'm using rails 3.0.  I have gone through the instructions and I'm doing the correct thing.  Thanks so much for your help, I will use the default markers until I have time to look closer at this.
Comment: Thanks Hishalv, I had already set the config.serve_static_assets to true but it has not effect (I restarted apache after the change earlier today).


I think I'm misunderstanding how variables from other functions can be called

Question: I'll try with words first. Using Python 3, and I have a main function that sets arg as a variable. When the main() is run, it calls a copy function which calls other functions. After these other functions run, copy() needs that arg variable set by main() at the beginning to finish and allow the main() to complete.
From what I understand, the arg variable is local to main(). Calling arg from outside the function returns a NameError.
I am looking at this thinking "I should be able to call the arg variable from copy() because I am running main() which is calling copy().
I keep arriving at a NameError. The final function I call before I want the main function to end wants to know what arg holds but doesn't recognize arg as defined.
Assuming all other necessary stuff is working, what must one do to get the copy() to recognize arg as defined.
...

def copy():
    x = destination()
    if os.path.isdir(x):
        y = backup_destination()
        if not os.path.isdir(y):
            shutil.copytree(arg.source, backup_destination)
            shutil.rmtree(x)
            shutil.copytree(arg.source, x)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--source', type = str)
    arg = parser.parse_args()

    if os.path.isdir(arg.source):
       copy()

    ...

if __name__ == '__main__':
    main()

Comment: Functions do not share local variables. You need to pass them to each other when needed.
Comment: Do you want to define a global variable?
Answer: The variable is local to the main function, to use it in copy you have to pass it as an argument, or make it a global variable. try to avoid the latter at all costs except you're sure that you need it, using global variables can lead to a lot of problems that are hard to debug, because a function that you forgot about altered the variable.
def copy(arg):
    x = destination()
    if os.path.isdir(x):
        y = backup_destination()
        if not os.path.isdir(y):
            shutil.copytree(arg.source, backup_destination)
            shutil.rmtree(x)
            shutil.copytree(arg.source, x)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--source', type = str)
    arg = parser.parse_args()

    if os.path.isdir(arg.source):
       copy(arg)

if __name__ == '__main__':
    main()

Read this for more information on variable scopes in python.
Comment: Thank you. I had a feeling I could have done it with globals but I do understand why they shouldn't be used.
Answer: Each function runs in a different frame. Try printing locals() in each of your functions to see the local variables.
There are 2 ways to access args:
First, the normal and correct way to do things: Give it to copy() as an argument:
def copy(arg):
    ...
def main():
    copy(arg)

Second, the bad way to do things: Analyze the top frame using sys._getframe(1):
def copy():
    args = sys._getframe(1).f_locals["args"]
    print(args())

def main():
    args = 1234
    copy()

>>> main()
1234

Regarding getting a variable from a different scope, I believe you're mistaken with this code:
def main():
    arg = 1234
    def code():
        print(arg)
    code()

In here, since the function was defined inside another function, it gets access to it's local variables.


Displaying data from database  dynamic class

Question: I am stuck on a certain code and i have no idea how to sort it out.. the thing is i have a box which contains 2  first one has  and second ul has class="list3 floatrt"> .. when i use foreach loop the data is displayed vertically, but according to the design the html has 2 ul i.e

Hard Drive 40 GB SATA

OS Windows/Linux

RAM 512 MB RAM

Hard Drive 40 GB SATA

OS Windows/Linux

RAM 512 MB RAM

and my code
<?php
            $count = 1;
             if($count <=3){
         ?>

              <?php

              foreach($planValues as $pl1) {

                  if($pl1['vlue']!="") {
                      ?>

<?php echo $pl1['feature'];?>  <?php echo $pl1['vlue']; ?>

                  <?php
                  }
              }?>

              <?php }

         elseif ($count >3) {
             ?>

                 <?php

                 foreach ($planValues as $pl1) {

                     if ($pl1['vlue'] != "") {
                         ?>

<?php echo $pl1['feature']; ?>  <?php echo $pl1['vlue']; ?>

                     <?php
                     }
                 }?>

         <?php

         }?>

but i am getting the same display .. all li are displayed in one ul which has the class list3 and no other ul containing list3 floatrt is created..
Answer: first of all you are using <?php way to many times.. just declare it once <?php and ?> put your code between those tags.
Try:
<?php
    $count = 1;
    if($count <=3){
        echo "
";

        foreach($planValues as $pl1) {
          if($pl1['vlue']!="") {
             echo "
".$pl1['feature']."  ".$pl1['vlue']."
";
          }
        }

        echo "
";
    }
    elseif ($count >3) {
        echo "
";

        foreach ($planValues as $pl1) {
          if ($pl1['vlue'] != "") {
            echo "
".$pl1['feature']."  ".$pl1['vlue']."
";
          }
        }

        echo "
";
    }
?>

also if you declare $count = 1; it will never run you code inside the elseif, so you class floatrt will never be applied. Make sure your count is dynamic for example an array count() from the array you create from your database. otherwise your $count will always be 1.
Comment: In the code above it will always be 1 maybe you are working with other code?


How can I let my React app treat each component instance separately?

Question: I am trying to test how TinyMCE handles multiple editors inside React.
In this small example, I just have 3, but there could be up to 100 of them.
My problem is, that I don't think each are being treated as separate instances, but rather one instance.
I don't get any errors, but when I edit one, the edits appears in all 3.
Is there a way to let TinyMCE know which editor is which?
import React from 'react';
import TinyMCEComponent from './TinyMCEComponent';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

export default function BasicExample() {
  return (
    <Router>

            <Link to="/editor_1">Editor One</Link>

            <Link to="/editor_2">Editor Two</Link>

            <Link to="/editor_3">Editor Three</Link>

        <Switch>
          <Route exact path="/editor_1">
            <TinyMCEComponent />
          </Route>
          <Route path="/editor_2">
            <TinyMCEComponent />
          </Route>
          <Route path="/editor_3">
            <TinyMCEComponent />
          </Route>
        </Switch>

    </Router>
  );
}

And this is where TinyMCE is:
import React from 'react';
import { Editor } from '@tinymce/tinymce-react';

const TinyMCEComponent = () => {

const handleEditorChange = (content, editor) => {
    console.log('Content was updated:', content);
}

return (
    <Editor
        apiKey="abc123"
        initialValue="
This is the initial content of the editor
"
        init={{
            height: 500,
            menubar: false,
            plugins: [
                'advlist autolink lists link image charmap print preview anchor'
            ],
            toolbar:
                'undo redo | formatselect | bold italic backcolor | help'
        }}
        onEditorChange={handleEditorChange}
    />
);
}

export default TinyMCEComponent;

Thanks!
Answer: The simplest solution is to give each a key.
import React from 'react';
import TinyMCEComponent from './TinyMCEComponent';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

export default function BasicExample() {
  return (
    <Router>

            <Link to="/editor_1">Editor One</Link>

            <Link to="/editor_2">Editor Two</Link>

            <Link to="/editor_3">Editor Three</Link>

        <Switch>
          <Route exact path="/editor_1">
            <TinyMCEComponent key="ed1" />
          </Route>
          <Route path="/editor_2">
            <TinyMCEComponent key="ed2" />
          </Route>
          <Route path="/editor_3">
            <TinyMCEComponent key="ed3" />
          </Route>
        </Switch>

    </Router>
  );
}

Comment: The `key` prop just tells react that the two are different. See the react [docs on the subject](https://reactjs.org/docs/lists-and-keys.html). In the `TinyMCEComponent` you'll need to pass another prop like an `id` to load different data.
Comment: Thanks but what does the TinyMCEComponent do with the key?  I mean, how can I use that key in TinyMCE?  thanks!


Set condition based on inner text of node?

Question: (function() {
  var i=0;
  var f=function() {
    let l=document.querySelector("*[data-control-name=withdraw_single]");
    if (!!l) {
      setTimeout(function() {
        l.click();
      }, 100);
      setTimeout(function() {
        document.querySelector(".artdeco-modal .artdeco-button--primary").click();
      },1500);
      setTimeout(function() {
        f();
      },2500);
    }
  };
  f();
})()

The above javascript bookmarklet works well for automating the invitation withdraw process on LinkedIn. However, there is a value in this element that I am hoping to factor in:
<time class="time-badge time-ago">
  1 day ago
</time>

Any idea on how to add a condition to only move forward with the process ONLY if this 'time-ago' value is greater than [X] days ago, otherwise STOP the process just provide an alert like 'All invites older than [X] days ago withdrawn.'
Answer: Ciao, you could try to do this:
...
let val = parseInt(document.querySelector(".time-badge").innerText.split(' ')[0]);
if (val > [X]){
   // go forward
}
else {
   // stop
   alert('All invites older than [X] days ago withdrawn.');
}

Answer: var str = "<time class=\"time-badge time-ago\"> 1 day ago </time>";
  var patt = /\> (.*?) day ago \<\/time>/i;
  var result = str.match(patt);
  if(result !== undefined  && result !== null){
      var day = parseInt(result[1]);
      if(day <= 10){
          // include results upto 10 days
      } else {
         // exclude results
      }
  }


Quebrar resultado de query em 2 linhas

Question: Boa tarde! Estou com a seguinte duvida
A minha query esta retornando uma unica linha, mas necessitaria que ela retornasse duas linhas, onde a primeira linha seria o retorno de "B" e a outra o retorno de "C"
Alguma ideia de como resolver?
select b.*,c.* from portal_sega_user a -- perfil
inner join portal_sega_user b  -- secretaria secundaria
on b.USUARIO = a.SECRETARIAPRINCIPAL
inner join portal_sega_user c -- secretaria secundaria
on c.USUARIO = a.SECRETARIASECUNDARIA
where a.USUARIO = 'Willian'

Obrigado.
Comment: Isso pode te ajudar: https://stackoverflow.com/questions/5641423/how-to-return-multiple-columns-of-the-same-row-in-t-sql-using-group-by ........
Answer: Divida a query em duas consultas e junte com UNION
select b.* from portal_sega_user a -- perfil
inner join portal_sega_user b  -- secretaria secundaria
on b.USUARIO = a.SECRETARIAPRINCIPAL
where a.USUARIO = 'Willian'

UNION

select c.* from portal_sega_user a -- perfil
inner join portal_sega_user c -- secretaria secundaria
on c.USUARIO = a.SECRETARIASECUNDARIA
where a.USUARIO = 'Willian'

Obs: O número, nome e tipo das colunas deve ser o mesmo nos dois resultados do select, se necessário adicione alias nos selects com nome de colunas.
Comment: Opa! Obrigado, Era exatamente isso que estava tentando fazer, mas me fugiu utilizar o union.
grato!
Answer: Faça um UNION ALL com duas consultas:
SELECT b.*
  FROM portal_sega_user a -- perfil
 INNER JOIN portal_sega_user b -- secretaria secundaria
    ON b.usuario = a.secretariaprincipal
 INNER JOIN portal_sega_user c -- secretaria secundaria
    ON c.usuario = a.secretariasecundaria
 WHERE a.usuario = 'Willian'
UNION ALL
SELECT c.*
  FROM portal_sega_user a -- perfil
 INNER JOIN portal_sega_user b -- secretaria secundaria
    ON b.usuario = a.secretariaprincipal
 INNER JOIN portal_sega_user c -- secretaria secundaria
    ON c.usuario = a.secretariasecundaria
 WHERE a.usuario = 'Willian'

Um detalhe, o uso do UNION não garante que sua consulta retorne duas linhas, o UNION ALL sim.
Answer: Separe suas junções e faça uma união de dois SELECTs:
select b.* from portal_sega_user a -- perfil
inner join portal_sega_user b  -- secretaria secundaria
on b.USUARIO = a.SECRETARIAPRINCIPAL
where a.USUARIO = 'Willian'
UNION
select c.* from portal_sega_user a -- perfil
inner join portal_sega_user c -- secretaria secundaria
on c.USUARIO = a.SECRETARIASECUNDARIA
where a.USUARIO = 'Willian'

Quebrar resultado de query em 2 linhas


Determining unitary matrices

Question: Suppose you have $A \in \mathbb{C}^{n \times n}$ that is upper triangular with eigenvalues along the main diagonal. My question is, can we explicitly construct a unitary matrix $U \in \mathbb{C}^{n \times n}$ so that we can permute the eigenvalues on the diagonal anyway we like? Let $n=2$ for simplicity. Here
$$A = \begin{pmatrix}
\lambda_1 & x \\
0 & \lambda_2
\end{pmatrix}.$$
And we want to find $U$ such that $U \in \mathbb{C}^{2 \times 2}$ such that
$$U^*AU = \begin{pmatrix}
\lambda_2 & y \\
0 & \lambda_1
\end{pmatrix}.$$
Now, I know this has to be true by Schur's Theorem, but the construction seems a bit challenging. Multiplying the matrices and equating term-by-term is what I initially had in mind, but this led nowhere. Any help is appreciated.
Thanks :)!
Answer: An explicit construction for the general case is probably not worth the trouble. However, the explicit construction for the $n = 2$ case is simple enough. I assume that $\lambda_1 \neq \lambda_2$; if the eigenvalues are equal, there is no real "permutation" to make and we could simple choose $U = I$.
As in the proof of Schur's theorem, we note that the first column of $U$ should be an eigenvalue of $A$ associated with $\lambda_2$. Note that
$$
A - \lambda_2 I = \pmatrix{\lambda_1 - \lambda_2 & x\\ 0 & 0}.
$$
We can see that one eigenvector associated with $\lambda_2$ is given by
$$
v = (x, \lambda_2 - \lambda_1).
$$
In order to make this a column of $U$, this vector must be normalized. Accordingly, we can take the first column of $U$ to be
$
u_1 = v/\|v\|.
$
With that, we have
$$
u_{11} = x/\sqrt{|x|^2 + |\lambda_1 - \lambda_2|^2}, \quad
u_{21} = (\lambda_2 - \lambda_1)/\sqrt{|x|^2 + |\lambda_1 - \lambda_2|^2}.
$$
From there, the second column must be a unit vector orthogonal to the first column. So, there must be an $\alpha \in \Bbb C$ with $|\alpha| = 1$ such that
$$
u_{12} = \alpha (\overline{\lambda_1 - \lambda_2})/\sqrt{|x|^2 + |\lambda_1 - \lambda_2|^2} = -\alpha \bar u_{21}, \\
u_{22} = \alpha \bar x /\sqrt{|x|^2 + |\lambda_1 - \lambda_2|^2} = \alpha \bar u_{22}.
$$
In order to find a suitable value of $\alpha$, note that the $1,2$ entry of $U^*AU$ is given by
$$
x = \pmatrix{\bar u_{11} & \bar u_{21}} A \pmatrix{u_{12}\\ u_{22}} = \\
\alpha \cdot \pmatrix{\bar u_{11} & \bar u_{12}} A \pmatrix{-\bar u_{21}\\\bar u_{11}} =\\
\alpha \cdot \frac{1}{|x|^2 + |\lambda_1 - \lambda_2|^2} \cdot
\pmatrix{\bar x & \overline{\lambda_2 - \lambda_1}} A \pmatrix{\overline{\lambda_1 - \lambda_2}\\\bar x}.
$$
In other words, if $x$ is non-zero, then $\alpha$ must be taken to be $\alpha = e^{-i \theta}$, where $\theta$ is the argument of the number
$$
\frac{1}{x(|x|^2 + |\lambda_1 - \lambda_2|^2)} \cdot
\pmatrix{\bar x & \overline{\lambda_2 - \lambda_1}} A \pmatrix{\overline{\lambda_1 - \lambda_2}\\\bar x}.
$$

Determining unitary matrices


Complex manifolds and Hermitian metrics

Question: I've been trying to learn some complex geometry, and was getting
confused in thinking about Hermitian metrics.  In this post, I've
written up my current understanding, in hopes that someone can look it
over and verify/clarify where I have gone
right/wrong. $\newcommand{\pp}[1]{\frac{\partial}{\partial #1}}$
I'll start with definitions, to fix notation and for practice.
Let $M$ be a complex manifold of dimension $n$, and let us fix a point
$p \in M$.  Around $p$ we can find a holomorphic coordinate chart: an
open set $U \subset M$ and holomorphic coordinates $z_1, \dots, z_n :
M \to \mathbb{C}$.  If $x_j, y_j$ are the real and imaginary parts of
$z_j$, then $x_1, y_1, \dots, x_n, y_n : U \to \mathbb{R}$ give us a
smooth coordinate chart.  So $M$ is also a differentiable manifold of
real dimension $2n$, and thus we can define a tangent space $T_p M$ in
the usual way as a real vector space of dimension $2n$; a basis for
$T_p M$ is given by $\pp{x_1}, \pp{y_1}, \dots, \pp{x_n}, \pp{y_n}$.
Now $T_p M$ carries a natural almost complex structure; namely, the
linear map $J$ defined by $J \pp{x_j} = \pp{y_j}$ and $J \pp{y_j} =
-\pp{x_j}$.  If the differentiable manifold $M$ carries a Riemannian
metric $g$, so that $g_p : T_p M \times T_p M \to \mathbb{R}$ is a
bilinear symmetric positive definite form, then we say this metric is
Hermitian if it respects the almost complex structure: $g_p(J v, J
w) = g_p(v,w)$ (and the same holds for every other point $p$).  So
far, so good?
We may also consider the complexified tangent space $T_p M \otimes
\mathbb{C}$, which is a complex vector space of complex dimension
$2n$.  As I understand it, we typically extend $g_p$ to $T_p M \otimes
\mathbb{C}$ by bilinearity; in particular, for $\alpha, \beta \in
\mathbb{C}$, we have $g_p(\alpha v, \beta w) = \alpha \beta
g_p(v,w)$.  So $g_p$ is now a bilinear symmetric form on $T_p M
\otimes \mathbb{C}$.
In particular, $g_p : (T_p M \otimes \mathbb{C})^2 \to \mathbb{C}$ is no longer positive definite: indeed, $$g_p\left(\pp{x_i} - i \pp{y_j}, \pp{x_i} - i \pp{y_j}\right) = 0.$$
This confused me for a while, because the more usual notion of an inner
product on a complex vector space is a positive definite sesquilinear symmetric form:
i.e., $\langle \alpha v, \beta w \rangle = \alpha \bar{\beta} \langle
v,w \rangle$.  Indeed, the word "Hermitian" is often used to describe
such a form.  So I would naively ask: Why is it better to take $g_p$
to be bilinear on $T_p M \otimes \mathbb{C}$, rather than
sesquilinear?  If we took the sesquilinear extension instead, would
we still get a reasonable theory, or would something bad happen?
I think part of the reason I was confused is that $T_p M \otimes
\mathbb{C}$, considered as a real vector space of dimension $4n$ (with
basis $\left\{ \pp{x_j}, i \pp{x_j}, \pp{y_j}, i \pp{y_j} \right\}$)
actually carries two distinct almost complex structures.  First is the
obvious one: multiplication by $i$, sending $\pp{x_j}$ to $i
\pp{x_j}$ and so on.  The other one is the complex linear extension of
$J$, which sends $\pp{x_j}$ to $\pp{y_j}$, sends $i \pp{x_j}$ to $i
\pp{y_j}$ and so on.  And the point is that we take our extension of
$g_p$ to be Hermitian with respect to the latter, not the former.
Have I understood all this correctly?
Answer: Let me try to clarify the point that is bothering you. I think it's best to look at it in the simplest perspective: linear algebra, because it all boils down to linear algebra.
Here's our situation: we have a real vector space $V$ with a linear complex structure $J : V \to V$.

Definition 1. An inner product $g$ on $V$ is said to be compatible with the linear complex structure $J$ if $J$ is orthogonal with respect to $g$ (i.e. $g(Jx,Jy) = g(x,y)$ for all $x,y \in V)$.

Note that this is what you call a Hermitian inner product but I prefer to avoid this terminology for the sake of clarity. Instead:

Definition 2. A Hermitian inner product on $(V,J)$ is a real bilinear map $h : V \times V \to \mathbb{C}$ which is sesquilinear in the sense that $h(Jx, y) = -h(x, Jy) = ih(x,y)$ for all $x,y \in V$ and Hermitian-symmetric in the sense that $h(y,x) = \overline{h(x,y)}$ for all $x, y \in V$.

Now, the point is that these two notions are essentially the same:

Proposition. If $h$ is a Hermitian inner product on $(V,J)$, then $g := \operatorname{Re}(h)$ is a compatible inner product on $(V,J)$. Conversely, is $g$ is a compatible inner product on $(V,J)$, then there is a unique Hermitian inner product $h$ on $(V,J)$ such that $g = \operatorname{Re}(h)$.

As you can see, this has absolutely nothing to do with the complexification of $V$. It's true that $g$ extends to a symmetric complex bilinear map $g^\mathbb{C} : V^\mathbb{C} \to V^\mathbb{C}$ where $V^\mathbb{C} = V \otimes_{\mathbb{R}} \mathbb{C}$, but it's a different subject (and has nothing to do with the complex structure $J$).
Comment: Thanks for your answer. However, it is the extension of $g$ to the complexified tangent space that specifically interests me. (I'm reading a paper that makes use of it.)
Comment: Am I correct that we usually consider the bilinear, rather than the sesquilinear, extension (in the sense I describe in my question)? And why is this the "correct" choice?
Comment: Okay, but what do you wish to know about it?
Comment: I don't think it really matters, since they are so easily related. The complex bilinear extension is slightly easier to define. In any case I want to stress again that this story ($g$ gives rise to $g^\mathbb{C}$) is unrelated to $J$, in other words it doesn't matter that you are on a complex manifold.
Answer: I guess the main point of passing to complexifications is to get rid of conjugate linearity properties and have erverything complex (multi)-linear. The main issue that is missing in your description of the whole situation is the decomposition of the complesified tangent bundle into a holomorphic and an antiholomorphic part. (In fact, one would not even need to do this is the setting of manifolds, it is a pure linear-algebra-gadget, but I'll stay in the manifold setting.)
You have correctly observed that $T_pM\otimes\mathbb C$ carries two distinct almost complex structures, namely the one coming from $J_p$ and the one coming from multiplication by $i$ in the second factor. But this gives rise to a decomposition $T_pM\otimes\mathbb C=T^{1,0}_pM\oplus T^{0,1}_pM$, with the summands being the complex subspaces on which the two structures coincide respectively are negatives of each other (and both spaces have complex dimension $n$). from the bases built up from $\tfrac{\partial}{\partial x_i}$ and $\tfrac{\partial}{\partial y_j}$ you mention, one can build up a complex basis $\{\tfrac{\partial}{\partial z_i}\}$ for $T^{1,0}_pM$ (the "holomorphic tangent space") and a complex basis $\{\tfrac{\partial}{\partial\bar z_i}\}$ for $T^{0,1}_pM$ (the "anti-holomorphic tangent space").
Now the fact that a metric on $g$ on $T_pM$ is Hermitian is equivalent to the fact that its complex bilinear extension to the complexified tangent space vanishes on $T^{1,0}_pM\times T^{1,0}_pM$ and on $T^{0,1}_pM\times T^{0,1}_pM$, so it actually defines a paring $T^{1,0}_pM\times T^{0,1}_pM\to\mathbb C$.
The whole technique is more familiar in the setting of differential forms. Here one first looks at real linear maps $T_pM\to\mathbb C$, which can be canonically identified with complex linear maps $T_pM\otimes\mathbb C\to\mathbb C$, and such a map is complex linear (with respect to $J_p$) if and only if it restricts to zero on $T^{0,1}$ and conjugate linear if and only if it restricts to zero on $T^{0,1}$. This can be viewed as a decomposition of the complexified cotangent space and the induced decomposition of exterior powers gives the decomposition of differential forms on an almost complex manifold into $(p,q)$-types.
So as I said initially, the whole issue is to arrive at a setting in which one only deals with complex multilinear maps, but has the possibility to encode linearity and conjugate linearity properties of underlying objects or natural analogs of such properties as vanishing on certain subspaces.
Comment: I gave this answer the bounty since I think it was closer to an answer than the other response.    However, I have gained a (I think) deeper understanding which I will write up an post in the next few days.
Comment: @StevenGubkin: I'll be happy to add to the answer if you can give me more details on what you are interested in.

Complex manifolds and Hermitian metrics


cogroup like operation for pandas

Question: I was trying to using pandas to analysis a fairly large data set (~5GB). I wanted to divide the data sets into groups, then perform a Cartesian product on each group, and then aggregate the result.
The apply operation of pandas is quite expressive, I could first group, and then do the Cartesian product on each group using apply, and then aggregate the result using sum. The problem with this approach, however, is that apply is not lazy, it will compute all the intermediate results before the aggregation, and the intermediate results (Cartesian production on each group) is very large.
I was looking at Apache Spark and found one very interesting operator called cogroup. The definition is here:

When called on datasets of type (K, V) and (K, W), returns a dataset of (K, Iterable, Iterable) tuples. This operation is also called groupWith.

This seems to be exactly what I want. If I could first cogroup and then do a sum, then the intermediate results won't be expanded (assuming cogroup works in the same lazy fashion as group).
Is there operation similar to cogroup in pandas, or how to achieve my goal efficiently?
Here is my example:
I want to group the data by id, and then do a Cartesian product for each group, and then group by cluster_x and cluster_y and aggregate the count_x and count_y using sum. The following code works, but is extremely slow and consumes too much memory.
# add dummy_key to do Cartesian product by merge
df['dummy_key'] = 1

def join_group(g):
    return pandas.merge(g, g, on='dummy_key')\
    [['cache_cluster_x', 'count_x', 'cache_cluster_y', 'count_y']]

df_count_stats = df.groupby(['id'], as_index=True).apply(join_group).\
    groupby(['cache_cluster_x', 'cache_cluster_y'], as_index=False)\
    [['count_x', 'count_y']].sum()

A toy data set
   id cluster  count
0  i1       A      2
1  i1       B      3
2  i2       A      1
3  i2       B      4

Intermediate result after the apply (can be large)
     cluster_x  count_x cluster_y  count_y
id
i1 0         A        2         A        2
   1         A        2         B        3
   2         B        3         A        2
   3         B        3         B        3
i2 0         A        1         A        1
   1         A        1         B        4
   2         B        4         A        1
   3         B        4         B        4

The desired final result
  cluster_x cluster_y  count_x  count_y
0         A         A        3        3
1         A         B        3        7
2         B         A        7        3
3         B         B        7        7

Comment: Could you give a small self-contained example with fake data to show what you want?  (E.g. I don't see why you can't move a summation into the apply to avoid expanding more than one group at a time, but maybe that doesn't work in a real case for some reason.)
Comment: @DSM I have attached an example. The summation in one group won't reduce the size of the result, the summation I want to do is across different groups. I actually did another `groupby`.
Comment: Is that the right frame under "toy data set"? It doesn't have an id column, and looks just like your final result.
Comment: My bad. Just updated.
Answer: My first attempt failed, sort of: while I was able to limit the memory use (by summing over the Cartesian product within each group), it was considerably slower than the original.  But for your particular desired output, I think we can simplify the problem considerably:
import numpy as np, pandas as pd

def fake_data(nids, nclusters, ntile):
    ids = ["i{}".format(i) for i in range(1,nids+1)]
    clusters = ["A{}".format(i) for i in range(nclusters)]
    df = pd.DataFrame(index=pd.MultiIndex.from_product([ids, clusters], names=["id", "cluster"]))
    df = df.reset_index()
    df = pd.concat([df]*ntile)
    df["count"] = np.random.randint(0, 10, size=len(df))
    return df

def join_group(g):
    m= pd.merge(g, g, on='dummy_key')
    return m[['cluster_x', 'count_x', 'cluster_y', 'count_y']]

def old_method(df):
    df["dummy_key"] = 1
    h1 = df.groupby(['id'], as_index=True).apply(join_group)
    h2 = h1.groupby(['cluster_x', 'cluster_y'], as_index=False)
    h3 = h2[['count_x', 'count_y']].sum()
    return h3

def new_method1(df):
    m1 = df.groupby("cluster", as_index=False)["count"].sum()
    m1["dummy_key"] = 1
    m2 = m1.merge(m1, on="dummy_key")
    m2 = m2.sort_index(axis=1).drop(["dummy_key"], axis=1)
    return m2

which gives (with df as your toy frame):
>>> new_method1(df)
  cluster_x cluster_y  count_x  count_y
0         A         A        3        3
1         A         B        3        7
2         B         A        7        3
3         B         B        7        7
>>> df2 = fake_data(100, 100, 1)
>>> %timeit old_method(df2)
1 loops, best of 3: 954 ms per loop
>>> %timeit new_method1(df2)
100 loops, best of 3: 8.58 ms per loop
>>> (old_method(df2) == new_method1(df2)).all().all()
True

and even
>>> df2 = fake_data(100, 100, 100)
>>> %timeit new_method1(df2)
10 loops, best of 3: 88.8 ms per loop

Whether this will be enough of an improvement to handle your actual case, I'm not sure.
Comment: You are right. For this particular problem I could have simplified using `new_method1`. Generally though I don't know if `pandas` can handle two `groupby` or more complicated operations lazily (without expanding all the intermediate results. I am looking at Apache-Spark and it seems to solve the issue. But I hope `pandas`  can also support arbitrary lazy expressions (currently it only supports one groupby and aggregate, if I am not mistaken).
Comment: Still after 7 years the cogroup operator is missing from pandas.

cogroup like operation for pandas


Erlang record expression ignored warning stopping answer

Question: I have following code:
M =list:sort([X|Y]), list:sort(length) / 2,io:format("The median of the items is", [M]),

But I get warning when I try to compile it:
Warning: the result of the expression is ignored (suppress the warning by assigning the expression to the _ variable)

What's wrong? How can i fix it?
This is it within my surrounding code and its the only problem with my program. Everything else works.
answer([ ]) -> io:format(" There are no items in the list");

answer([X|Y]) ->
   M =list:sort([X|Y]), list:sort(length) / 2,io:format("The median of the items is", [M]),

Comment: This is the only way I know how to find the median of a list...If anyone else knows how to in Erlang Id love to know!!
Answer: in your code, list:sort(length) will fail as length is an atom and the function is looking for a list, and the io:format/2 format string is missing a place holder to print the result.
the following code works, al least it prints the results, but it always return ok.
answer([ ]) -> io:format("There are no items in the list~n");
answer(L) when is_list(L) -> io:format("The median of the items is ~p~n",
                                [lists:nth((length(L)+1) div 2,lists:sort(L))]);
answer(_) -> io:format("error,the input parameter is not a list~n").

some example of use directly entered in the console. You can see that it will give an answer which can seem weird, while technically correct, when the list contains other element than numbers.
1> Answer = fun([ ]) -> io:format("There are no items in the list~n");
1> (L) when is_list(L) -> io:format("The median of the items is ~p~n",
1>                                 [lists:nth((length(L)+1) div 2,lists:sort(L))]);
1> (_) -> io:format("error,the input parameter is not a list~n") end.
#Fun<erl_eval.6.80484245>
2> L1 = [6,9,5,7,8].
[6,9,5,7,8]
3> Answer(L1).
The median of the items is 7
ok
4> L2 = [4,6,3].
[4,6,3]
5> Answer(L2).
The median of the items is 4
ok
6> L3 = [4,6,3,8].
[4,6,3,8]
7> Answer(L3).
The median of the items is 4
ok
8> L4 = [hello, 5,[1,2]].
[hello,5,[1,2]]
9> Answer(L4).
The median of the items is hello
ok
10> Answer("test_string").
The median of the items is 114
ok
11> Answer(test_atom).
error,the input parameter is not a list
ok
12> Answer("").
There are no items in the list
ok
13>

Comment: Ahhhh...I see....How does it work if the list is even though? if it is I have to add the two middle numbers together and then divide them by 2.
Comment: The list is sorted inside the intricate io:format call, and I have used the formula `(length + 1) div 2` to get a correct value in all cases of length (odd or even)