Ruby gem Mechanize with jRuby 1.6.0 (Ruby 1.9.2)

Question: When I tried to access a web site with SSL using Mechanize, I got the following error.
<code>jruby-1.6.0 :009 > page = mechanize_agent.submit(form)
NoMethodError: undefined method `read_nonblock' for #<OpenSSL::SSL::SSLSocket:0x44cae5b8>
</code>
I tried with Mechanize both 2.0.pre.2 and 1.0.0.
jRuby installed is:
jruby 1.6.0 (ruby 1.9.2 patchlevel 136) (2011-03-15 f3b6154) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_24)
I also installed the gem jruby-openssl.
Any help will be greatly appreciated.
Answer: It's a bug, and there's a monkey patch you can use to get around it. http://jira.codehaus.org/browse/JRUBY-5529
Link to monkey patch at the bottom.


Confidence interval for average treatment effect from propensity score weighting?

Question: I am trying to estimate the average treatment effect from observational data using propensity score weighting (specifically IPTW).  I think I am calculating the ATE correctly, but I don't know how to calculate the confidence interval of the ATE while taking into account the inverse propensity score weights.
Here is the equation I'm using to calculate the average treatment effect (reference Stat Med. Sep 10, 2010; 29(20): 2137–2148.):
$$ATE=\frac1N\sum_1^N\frac{Z_iY_i}{p_i}-\frac1N\sum_1^N\frac{(1-Z_i)Y_i}{1-p_i}$$
Where $N=$total number of subjects, $Z_i=$treatment status, $Y_i=$outcome status, and $p_i=$ propensity score.
Does anyone know of an R package that would calculate the confidence interval of the average treatment effect, taking into account the weights?  Could the survey package help here?  I was wondering if this would work:
library(survey)
sampsvy=svydesign(id=~1,weights=~iptw,data=df)
svyby(~surgery=='lump',~treatment,design=sampsvy,svyciprop,vartype='ci',method='beta')

#which produces this result:
  treatment surgery == "lump"      ci_l      ci_u
   No         0.1644043 0.1480568 0.1817876
   Yes         0.2433215 0.2262039 0.2610724

I don't know where to go from here to find the confidence interval of the difference between the proportions (i.e. the average treatment effect).
Comment: I cannot answer specifically, but the book "Complex Surveys: A Guide to Analysis Using R" by the author of the survey package does cover IPTW, and may be of help. https://books.google.com/books?id=L96ludyhFBsC&pg=SA9-PA11&lpg=SA9-PA11&dq=r+survey+iptw&source=bl&ots=icYv3ioDu1&sig=bqTT6kZm1pS7r49aCfJ2Tue5jqI&hl=en&sa=X&ei=7K5kVcXnB8yxsAS7uICIAw&ved=0CEkQ6AEwBQ#v=onepage&q=r%20survey%20iptw&f=false
Answer: You don't need the survey package or anything complicated. Wooldridge (2010, p. 920 onwards) "Econometric Analysis of Cross Section and Panel Data" has a simple procedure from which you can obtain the standard errors in order to construct the confidence intervals.
Under the assumption that you have correctly specified the propensity score which we denote as $p(\textbf{x}_i,\textbf{$\gamma$})$, define the score from the propensity score estimation (i.e. your first logit or probit regression) as
$$\textbf{d}_i = \frac{\nabla_\gamma p(\textbf{x}_i,\textbf{$\gamma$})'[Z_i-p(\textbf{x}_i,\textbf{$\gamma$})]}{p(\textbf{x}_i,\textbf{$\gamma$}){[1-p(\textbf{x}_i,\textbf{$\gamma$})]}} $$
and let
$$\text{ATE}_i = \frac{[Z_i-p(\textbf{x}_i,\textbf{$\gamma$})]Y_i}{p(\textbf{x}_i,\textbf{$\gamma$}){[1-p(\textbf{x}_i,\textbf{$\gamma$})]}}$$
as you have it in your expression above. Then take the sample analogues of these two expressions and regress $\widehat{\text{ATE}}_i$ on $\widehat{\textbf{d}}_i$. Make sure you include an intercept in this regression. Let $e_i$ be the residual from that regression, then the asymptotic variance of $\sqrt{N}(\widehat{\text{ATE}} - \text{ATE})$ is simply $\text{Var}(e_i)$. So the asymptotic standard error of your ATE is
$$\frac{\left[ \frac{1}{N}\sum^N_{i=1}e_i^2 \right]^{\frac{1}{2}}}{\sqrt{N}}$$
You can then calculate the confidence interval in the usual way (see for example the comments to the answer here for a code example). You don't need to adjust the confidence interval again for the inverse propensity score weights because this step was already included in the calculation of the standard errors.
Unfortunately I am not an R guy so I can't provide you with the specific code but the outlined procedure above should be straight forward to follow. As a side note, this is also the way in which the treatrew command in Stata works. This command was written and introduced in the Stata Journal by Cerulli (2014). If you don't have access to the article you can check his slides which also outline the procedure of calculating the standard errors from inverse propensity score weighting. There he also discusses some slight conceptual differences between estimating the propensity score via logit or probit but for the sake of this answer it was not overly important so I omitted this part.


Showing a Linear Transformation is invertible

Question: I have the following question:

Suppose A is a linear transformation. Show that if $A^2 - A + I = O$, then A is invertible.

To show $A$ is invertible, I can show if $Ax = 0$ then $x = 0$.
But, if $Ax = 0$, then $(Ax)^2 + (Ax) + 1 = 0 + 0 + 1 \neq 0$ so the equation in the question is not satisfied. What gives?
Comment: You surely mean $A^2-A+I=0$, not "A^2 - A + 1 = 0". From $A^2-A+I=0$ you should be able to just write down an inverse for $A$.
Comment: Rewrite $A^2-A+I=O$ in the form $AB=I$, then you have $B=A^{-1}$
Comment: You have to start knowing that $A^2-A+I=O$ and *then* prove that $A$ is invertible
Comment: That's what I mean Lord Shark. Forgive my lack of typesetting
Comment: It's not just the typesetting, it's also the confusion of $I$ with $1$.
Comment: Well in the book I'm using (Finite Dimensional Vector spaces - Halmos), "1" is defined as the identity transformation.
Answer: From $A^2-A+I=O$
You have $A-A^2=I$ which means that $A(I-A)=I$ then $A$ has an inverse which is $I-A$
Answer: From the equation $A^2-A+I=0$ we have that the minimal polynomial $m(x)|x^2-x+1$ so $m(0)\not=0 \Rightarrow 0$ is not an eigenvalue of $A \Rightarrow A$ is invertible


Policy Question: Can I Use a Submodule that Does Not Follow Drupal Code Guidelines?

Question: I have a fairly extensive plugin system that I wrote.
It uses an MVVM pattern, where the lions' share of the code is in a cross-CMS class.
I haven't submitted the Drupal plugin to the Drupal repo, because it does not follow their coding conventions.
It has extremely rigorous coding conventions; just not the ones prescribed by Drupal.
Fair enough. They have every right to dictate coding standards. That's a good idea, and I support it.
However, I can't rewrite the MVVM library to make just one of the targets happy.
Since the MVVM library is actually a submodule, can I submit the plugin to the Drupal repository if the Drupal-specific parts (just a couple of files) are set up to use Drupal standards?
For that matter, since Git is so horrible with submodules, I wonder if the Drupal repository can even handle submodules.
Comment: A decent IDE can format your code for you.
Comment: Even if a decent IDE can do the formatting, it will be a hassle to do so for every target. Excellent question. By the way, take a look at the NetBeans for PHP IDE. It's awesome to say the least. Cheers.
Comment: Thanks, but I don't use an IDE for PHP/JS/XML/HTML; only for ObjC. I'm not a huge Eclipse fan, as I have to basically reinstall all the good parts every time I update my main OS.
Comment: @Mario Awad Thanks for the suggestion. I've not looked at NetBeans before, and I'll take a gander at it. I'm pretty used to just using BBEdit and ForkLift.
Comment: @MAGNAWS I'm sure you'll love NetBeans then. Debugging, refactoring, jumping to method definitions or usages easily, find and replace, GIT support, all with keyboard shortcuts, and many other features. Cheers.
Answer:
Since the MVVM library is actually a submodule, can I submit the plugin to the Drupal repository if the Drupal-specific parts (just a couple of files) are set up to use Drupal standards?

Yes, as long as your Drupal project conforms to the GIT repo policy - where just one of terms are: "All code should comply to the coding standards." you can commit it (such projects are known as "bridge modules") to the Drupal repo (provided you have the access level required to do so - the access bar is low for sandboxes, but a lot higher for full projects). Note: You should only commit the Drupal-specific part.  The rest has to be hosted somewhere else.  Tell your users how to find it, and how it shall be combined with the Drupal-specific bridge.
However, there are other terms, and it looks like the BMLT License, as it currently appears, is a blocker:

"BMLT is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version." (my emphasis)

Drupal.org doesn't accept this license for any code in its repo.  For code to be permitted in the repo, it must be licensed under: "version 2 of the [GPL] License, or (at your option) any later version".  There are no exceptions to this rule.
Provided you can get the license right, there is nothing in the Drupal.org Git Repo Policy that prohibits a bridge module that requires other software (i.e. not packaged on Drupal.org) to be hosted on Drupal.org.

For that matter, since Git is so horrible with submodules, I wonder if the Drupal repository can even handle submodules.

When a bridge module is hosted on Drupal.org (and there are plenty of them there already), it has to be combined with other required bits and pieces manually (i.e. there must be human readable instructions in the README about where to find the other software and how to assemble the pieces).  While I can see the beauty of using Git to pull all the pieces together, that is not how it is done.  Provided you and your users can deal with a two phase install where a human is required to do the assembly, it is doable.
As noted by Alfred Armstrong in a comment, the convention is to have a directory below the libraries folder (usually sites/all/libraries) to hold files the user must download from elsewhere. Then use the Libraries API module to integrate the bridge with the other files.
Comment: good writeup, deleted 80% of what I was writing :D
Comment: The convention is to use the libraries folder (eg sites/all/libraries) for libraries. The libraries module (https://www.drupal.org/project/libraries) will help with managing this.
Comment: I really appreciate that! Great response! Yeah, kinda looks like the fox ain't worth the chase. Not really a big deal, as Drupaliers are a lot more technical than WordPrestonians or Joomlauts.
Comment: I did want to mention one other thing: The BMLT Serves a rather small, but "pithy" audience that often aren't as technically astute as I'd like, so I really need to supply the plugin as a "complete set." I don't even want to think about the "feedback" (think The Nuge, standing in front of his stacks) I'd get for not making it simple. The only reason that I'd want it in the Drupal Repository, is to remove another install step.
Answer: I recommend adjusting your coding style to fit with Drupal coding standards for your bridge module, otherwise you're not fully supporting Drupal.
I'd expect you to do the same thing for a Wordpress module, or Plone specific integration module -- follow those communities conventions.
Comment: Well, since the MVVM module is used in all plugins, then that's a showstopper. WordPress doesn't have a standard of code formatting, so that doesn't matter. I used to host in the Joomla repository, but stopped that a while back, because I wanted to use Git (I still need to use SVN for WP, which is a big fat pain).


Acessar impressora local

Question: Estou com o seguinte problema, tenho uma aplicação ruby-on-rails e preciso imprimir etiquetas em uma impressora que está instalado no computador do cliente, como faço para imprimir estas etiquetas diretamente pelo browser, enviar direto na porta?
Comment: Pode usar o dialog de impressão do browser?
Comment: Não dá pra acessar a impressora diretamente por JavaScript.
Comment: Não, é preciso enviar direto para a porta, pois a impressora só aceita arquivo .EPL e dispensa a visualização do usuário.
Comment: Existe alguma solução para enviar diretamente do browser a etiqueta que o servidor gera?
Comment: Só se você criar um plugin pro browser, e o plugin cuidar disso.
Comment: Qual impressora é essa? eu imprimo em uma Zebra GC420 direto pelo browser usando um print da página.Crio uma página em bco apenas com uma imagem gerada dinamicamente da etiqueta, chamo o método print() e o usuário já tem a impressora como padrão. Mas também temos um aplicativo que consulta uma fila de impressões e faz as impressões conforme a resposta do @AlexTakitani
Comment: É uma impressora TLP 2844, mas do seu modo, abriria o diálogo de impressão do browser e eu não gostaria disso, vou fazer como o @AlexTakitani falou, obrigado.
Answer: Você pode utilizar este plugin para fazer a impressão no cliente.
Coloque a pasta jre6 em seu public e altere o código:
<code>function deployQZ() {
    var attributes = {id: "qz", code:'qz.PrintApplet.class',
    archive:'jre6/qz-print.jar', width:1, height:1};

    var parameters = {jnlp_href: 'jre6/qz-print_jnlp.jnlp',
    cache_option:'plugin', disable_logging:'false',
    initial_focus:'false'};

    if (deployJava.versionCheck("1.7+") == true) {}
    else if (deployJava.versionCheck("1.6+") == true) {
         attributes['archive'] = 'jre6/qz-print.jar';
         parameters['jnlp_href'] = 'jre6/qz-print_jnlp.jnlp';
    }
    deployJava.runApplet(attributes, parameters, '1.5');
}
</code>
Com isso ele vai conseguir listar todas as impressoras do computador do cliente e assim poder imprimir o que quiser nelas.
Porém um requisito é que o cliente tenha instalado o jre 7, e é necessário dar permissão no painel de controle do java para que possa ser executado o seu código java.
Veja os exemplos do plugin para entender melhor.
Espero que ajude
Answer: O browser não tem acesso direto a impressora, eu resolveria da seguinte forma:
Criaria um aplicativo desktop, que seria instalado no computador do cliente.
Este app faria queries em uma fila de impressão ( banco de dados, api rest, etc. ) e imprimiria as etiquetas.

Acessar impressora local


Trying to center an unordered list

Question: On my website, I want a horizontal menu, which is centered on the page. So, the whole menu should be centred.
At this moment, I can create a horizontal list, but the list still stays at the left side. I want it centered.
Can someone please tell me what to change in my code to center it?
My HTML:

Home

Home

Home

Home

My CSS:
ul {
    text-align: center;
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

div.menu{
    display: table;
}

div.menu a {
    display: block;
    margin-left: auto;
    margin-right: auto;
    width: 60px;
    color: navy;
    background-color: #FF0000
}

li{
    float: left;
}

Comment: What is your question? Does it work? If not, why not? What are you getting, and what is the expected result? I have no idea what you're trying to ask.
Comment: try this: .menu ul {display:table; margin: 0 auto;}
Comment: Yup, sorry. Edited my question to be more clear
Comment: @shadeed9 this changes exactly nothing
Answer: Add margin:auto to your div.menu to accomplish this
div.menu{
    display: table;
    margin:auto;
}

JSFiddle: http://jsfiddle.net/0xb7j9zc/
Comment: This worked, thanks! Never thought that the answer would be this simple
Answer: Check out this fiddle http://jsfiddle.net/ByShine/33sz6nrt/4/
HTML

Home

Home

Home

Home

CSS
ul {
    text-align: center;
}
ul li {
    display: inline-block;
}

Answer: I'm assuming you wish to center the menu (align it to the middle of the page). One approach, and I'm sure there's a few out there, is to wrap the 'menu' div into another div tag and set the align attribute to center, like so:

Home

Home

Home

Home

Here's an example: http://jsfiddle.net/q9ae01qe/
Comment: I wouldn't use `align="center"` but instead `margin:auto:` or `margin:0 auto`  however yours does work :)

Trying to center an unordered list


What is an example of a second-order markov chain?

Question: I'd like to see an example of a second-order markov chain. Haven't found one over google or in any of my textbooks.
Answer: The markov property specifies that the probability of a state
depends only on the probability of the previous state.
You can "build more memory" into the states by using a
higher order Markov model.
In an $n$th order Markov model
$$P(x_i | x_{i-1}, x_{i-2},..., x_1) = P(x_i | x_{i-1},..., x_{i-n} ) $$
Example of a second order MC
Answer: There is nothing radically different about second order Markov chains: if $P(x_i|x_{i-1},..,x_1)=P(x_i|x_{i-1},..,x_{i-n})$ is a "n-th order Markov chain", we can still interpret it as a first order Markov chain, on the space of combinations of $n$ states, i.e. $S^n$, if $S$ is the set of values $x_i$ takes: just write $P(x_i|x_{i-1},..,x_1)=P(x_i|x_{i-1},..,x_{i-n})=P((x_i,x_{i-1},..,x_{i-n+1})|(x_{i-1},x_{i-2},..,x_{i-n}))$. Thus a second-order markov chain is just one which takes into account the two previous states.


ggplots not displaying in Shiny

Question: Right now I am trying to build a shinyApp from an alcohol consumption dataset from the world health organization. I've built maps from this data and gotten those outputs to work, but right now I am trying to display the top ten countries in terms of drinks consumed and two of the plots are not displaying (For beer and wine).
You can see what I mean by looking at my shiny app here:
https://mdsil11.shinyapps.io/worldMap/
The weird thing is, my code works when I use simpler plots in place of the ggplotones like hist(rnorm(100)). Another weird thing is that these plots work when I run them in a regular R script. Finally, my last plot(the plot for spirits, or mixed drinks) displays but not for wine or beer.
Here is the code:
library(shiny)
[library(rworldmap)
library(ggplot2)
library(tidyverse)

## defining datasets
wineDrinks = drinks\[ , c(2,5)\]
spiritDrinks = drinks\[ , c(2,4)\]
beerDrinks = drinks\[ , c(2,3)\]

topWine <- wineDrinks %>% arrange(desc(wine_servings))
topBeer <- beerDrinks %>% arrange(desc(beer_servings))
topSpirits <- spiritDrinks %>% arrange(desc(spirit_servings))

top10beer <- topBeer[0:10, ]
top10wine <- topWine[0:10, ]
top10spirits <- topSpirits[0:10, ]

## defining map objects
w <- joinCountryData2Map(drinksISO, joinCode = 'ISO3', nameJoinColumn = 'ISO', verbose = TRUE)
s <- joinCountryData2Map(drinksISO, joinCode = 'ISO3', nameJoinColumn = 'ISO', verbose = TRUE)
b <- joinCountryData2Map(drinksISO, joinCode = 'ISO3', nameJoinColumn = 'ISO', verbose = TRUE)

##### Shiny Application #####

ui <- fluidPage(
  titlePanel('Global Alcohol Consumption'),
  #each input should have a unique input ID
  sidebarPanel(
  radioButtons(inputId = 'Alc', label = 'Alcohol Type',
              choices = list('Beer','Wine','Spirits'))
  )
  , mainPanel(
    plotOutput('map'), plotOutput('TopTen')
    )
)

server <- function(input, output) {
  output$map <- renderPlot({
    if(input$Alc == 'Beer'){
      mapCountryData(mapToPlot = b,nameColumnToPlot = 'beer_servings', mapTitle = 'World Beer Consumption',  missingCountryCol = "grey", oceanCol = "lightblue1")
    }

    if(input$Alc == 'Wine'){
      mapCountryData(mapToPlot = w,nameColumnToPlot = 'wine_servings', mapTitle = 'World Wine Consumption',  missingCountryCol = "grey", oceanCol = "lightblue1")
    }

    if(input$Alc == 'Spirits'){
      mapCountryData(mapToPlot = s, nameColumnToPlot = 'spirit_servings', mapTitle = 'World Spirits Consumption',  missingCountryCol = "grey", oceanCol = "lightblue1")
    }

  })

  output$TopTen <- renderPlot({

     #### PROBLEM LIES HERE #####

    if(input$Alc == 'Beer'){
      ggplot(top10beer,aes(x = reorder(country, -beer_servings), y = beer_servings)) + geom_point(size = 3) + geom_segment(aes(x = country, xend = country, y = 0, yend = beer_servings)) + labs(title="Lollipop Chart", subtitle = 'Top 10 beer drinking countries') + theme(axis.text.x = element_text(angle=65, vjust=0.6)) + xlab('Countries')
    }
    if(input$Alc == 'Wine'){
      ggplot(top10wine, aes(x = reorder(country, -wine_servings), y = wine_servings)) + geom_point(size = 3) + geom_segment(aes(x = country, xend = country, y = 0, yend = wine_servings)) + labs(title="Lollipop Chart", subtitle = 'Top 10 wine drinking countries') + theme(axis.text.x = element_text(angle=65, vjust=0.6)) + xlab('Countries')
    }

   #### BUT THIS WORKS ####

    if(input$Alc == 'Spirits'){
      ggplot(top10spirits,aes(x = reorder(country, -spirit_servings), y = spirit_servings)) + geom_point(size = 3) + geom_segment(aes(x = country, xend = country, y = 0, yend = spirit_servings)) + labs(title="Lollipop Chart", subtitle = 'Top 10 spirit drinking countries') + theme(axis.text.x = element_text(angle=65, vjust=0.6)) + xlab('Countries')
    }
  }
  )

}
# Run the application
shinyApp(ui = ui, server = server)

Any help/pointers on getting the other two plots to show would be much appreciated!
Answer: Change those separate if statements to an if/else/else. Your renderPlot code block needs to return a ggplot object. If the last line of your block is an if, and that evaluates to FALSE, nothing is returned from the block. The values from previous if statements are basically ignored. Calling ggplot()doesn't actually draw the plot in the same way base graphics functions like hist do. You actually need to print the value returned by ggplot in order to trigger the plot to draw.
Here's one way to re-write your block.
output$TopTen <- renderPlot({

    if(input$Alc == 'Beer'){
      ggplot(top10beer,aes(x = reorder(country, -beer_servings), y = beer_servings)) + geom_point(size = 3) + geom_segment(aes(x = country, xend = country, y = 0, yend = beer_servings)) + labs(title="Lollipop Chart", subtitle = 'Top 10 beer drinking countries') + theme(axis.text.x = element_text(angle=65, vjust=0.6)) + xlab('Countries')
    } else if(input$Alc == 'Wine'){
      ggplot(top10wine, aes(x = reorder(country, -wine_servings), y = wine_servings)) + geom_point(size = 3) + geom_segment(aes(x = country, xend = country, y = 0, yend = wine_servings)) + labs(title="Lollipop Chart", subtitle = 'Top 10 wine drinking countries') + theme(axis.text.x = element_text(angle=65, vjust=0.6)) + xlab('Countries')
    } else if (input$Alc == 'Spirits'){
      ggplot(top10spirits,aes(x = reorder(country, -spirit_servings), y = spirit_servings)) + geom_point(size = 3) + geom_segment(aes(x = country, xend = country, y = 0, yend = spirit_servings)) + labs(title="Lollipop Chart", subtitle = 'Top 10 spirit drinking countries') + theme(axis.text.x = element_text(angle=65, vjust=0.6)) + xlab('Countries')
    } else {
        stop("unknown plot type")
    }
})

Comment: That makes so much sense. I tried what you suggested and everything works perfectly. Thank you!!!

ggplots not displaying in Shiny


SSH security

Question: For uploading and running java apps(.jars) on my server, I recently asked Server Admin to enable remote access via SSH to the server however they shot back questions to me several times to confirm whether I really needed to enable SSH access.
I was wondering if:

SSH really compromises the security of the server.
What precautions do I have to take while working with SSH?
Should I really enable SSH on the server?
What windows SSH client would be suitable for use to remote to a Linux server?
Answer: the communication with ssh protocol is secure, but i think your admins have other reasons for not granting ssh access with the first request.
when you gain ssh access to a system, you can normally copy files to the system and execute them (not only your jars). this way, you could upload files gaining root access or compromise the system in a different way.
so when granting ssh access, no matter how secure it is setup, you have direct access to the machine and this is another attack vector to the system. the philosophy should be to enable as few services as possible. but i can't imagine your admins are not already using ssh. so there should be no additional risk on enabling ssh, but perhaps on giving away a new account on the server. ask them whether they use public key authentication or password authentication. it is a good security advice to use public keys.
another reason for not granting you access, could be that they loose a bit of control over the server, because they do not know in detail what is running on the server. so tell them in detail what you want to upload and what these programs do. they might ask you some more questions or tell you you have to change something, but this way you can work together with your admins to get your jars running on the server.
as a windows client, i agree with Chris Kaufmann, putty is a very good client on windows.
Comment: Thanks is all I can give you coz I don't have the required reputation to upvote this answer.
Comment: An extension to this is that they may no longer have an accurate record of what is installed and how its configured, so they cannot reliably audit it or rebuild it correctly. Arguably backup procedures should be able to deal with this but these are factors that responsible admins need to consider when opening up access to a system.
Comment: as good as reputation is, it is better the answer helps you to solve your problem.
Answer: I agree with Aputsiaq - if configured right, it can be safe - if not it isn't.  You'll have to monitor the server more closely, I think.  Set it as tight as you can handle.
For windows,  putty is the gold standard.
Answer: One other reason that they might be reluctant to open ssh is it's ability to tunnel connections.  SSH typically allows tunnells which means that you have the potential to open up more of their network than they might want.

SSH security


$\log$ transform of the fundamental theorem of arithmetic?

Question: Taking the canonical form of the fundamental theorem of arithmetic in the form:
$$n=\prod_{j=1}^\infty p^{m_j}_j \qquad ;m_j\in \Bbb N_0$$
Does anybody know about a $\log n$ transform of this?
Note: also reference to other works are welcome
Comment: What do you mean by a "$\log n$ transform" of the theorem? There is an internal direct sum decomposition of additive groups $\sum_{n\ge1}(\log n){\bf Z}=\bigoplus_p (\log p){\bf Z}$, if that's at all relevant.
Comment: There is an answer on MSE somewhere (of Bill D) that proves $\{\log p\}$ are independent over the rationals using FToA. Otherwise I don't see any *point* in a text mentioning this form.
Comment: No, it was [this one](http://math.stackexchange.com/questions/6244/is-there-a-quick-proof-as-to-why-the-vector-space-of-mathbbr-over-mathbb/6250#6250).
Comment: What about it? What is it that you want to know that you don't already know?
Comment: I have never seen somewhere this form, although it seems so trivial. I was just wondering whether someone knows about this form elsewhere.
Comment: wasnt that post on the squares "The square roots of the primes are linearly independent over the field of rationals"?
Comment: This is great Help, anon. Many thanks.
Comment: @anon Please consider converting your comment into an answer, so that this question gets removed from the [unanswered tab](http://meta.math.stackexchange.com/q/3138). If you do so, it is helpful to post it to [this chat room](http://chat.stackexchange.com/rooms/9141) to make people aware of it (and attract some upvotes). For further reading upon the issue of too many unanswered questions, see [here](http://meta.stackexchange.com/q/143113), [here](http://meta.math.stackexchange.com/q/1148) or [here](http://meta.math.stackexchange.com/a/9868).
Comment: @JulianKuelshammer I converted my comments into an answer two hours before your comment asking me to; is yours a boilerplate comment? At any rate, thanks for the links.
Comment: @anon Sorry then. I don't know why I didn't see it, maybe a bug, or I'm just blind. My comment is from the "list of comment templates" in meta. It was made by Lord_Farin and myself.
Answer: You don't clarify what "$\log$ transform" of FTA would look like. A trivial reformulation of FTA is that the log of any positive natural can be written uniquely as a $\bf N$-linear combination of logs of primes, but there is little aesthetic appeal in this formulation. Another algebraic version is this:
$$\log\left({\bf Q}^\times_{>0}\right)=\bigoplus_p (\log p){\bf Z}.$$
One application of this log perspective though is in exhibiting an infinite $\bf Q$-linearly independent set of real numbers, thereby proving that $\bf R$ is an infinite-dimensional $\bf Q$-vector space via arithmetic.
Comment: excellent. thanks. Do you have a reference for the latter possibly where I could read further?
Comment: @al-Hwarizmi What latter possibility are you referring to? The direct sum isomorphism in the middle of this answer should be a basic exercise if you know abelian group theory and requires no reference outside of such. Using logs to show $\bf R$ is an infinite-dimensional $\bf Q$-vector space is also a pretty basic exercise, and I already linked to a reference in the comments.


How to display current time with node using express and handlebars

Question: I'm trying to display the current time (including seconds) on my page, using node, express and handlebars. Naturally I want to avoid refreshing the page every second. I thought about using socket.io, getting the time every 30 seconds from the node server, and incrementing the seconds with javascript on the client side, but this approach strikes me as rather hacky. Is there a standardized solution for this problem?
EDIT:
So I kinda figured it out, but I'm not sure if this is efficient enough. Is there any way to maybe squeeze some more out of this code?
setInterval(function() {
    var time = Moment();
    if(time.seconds() === 0 || time.seconds() === 1) {
        io.emit('time', {
            time: time.format('HH:mm'),
            date: time.format('DD.MM.YYYY')
        });
    }
},1000);

Comment: never worked with handelbars but can't you have javascript there. Settimeout or setInterval would have done the job
Comment: @sacDahal: But using setTimeout or setInterval would only work on client side, right? But if the user's machine has a wrong time set, the wrong time will be displayed on the page
Answer: After a lot of fiddling around and looking for the best way to do this, I stumbled over the concept of server sent events. Which is (explained in a very easy manner) like socket.io, but one way only - as the name suggests - from the server to the client. SSEs completely overate via HTTP, so no websockets needed.
Middleware configuration:
module.exports = function (req, res, next) {
    res.sseSetup = function() {
        res.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive'
        });
        res.connection.setTimeout(10800000);
    };

    res.sseSend = function(data) {
        res.write("data: " + JSON.stringify(data) + "\n\n");
    };

    next();
}

Now register your middleware with express (usually in your app.js):
app.use(require('./middlewares/sse'));

and add the necessary routing handler:
router.get('/time', function(req, res) {
    res.sseSetup();
    setInterval(function() {
        // create your time object - here: {time: 11:30:01}
        res.sseSend(timeObject);
    },1000);
});

Client side code:


Bracket notation convention and accepted use

Question: I'm writing an assignment right now and getting into some quite lengthy derivations, which caused me to wonder about bracket notation in math and what is best practice. There are three primary types of brackets I'm familiar with: the curly brackets {}, square brackets [], and the classic parentheses (). From what I learned, in an equation with tons of brackets, you go from outer to inner in that order e.g.
$$A\left\{\frac{2}{3}\left[B^2\left(C+4\right) + 2\right] - D^2\right\}$$
My question I suppose would be what happens if you need to add another level? i.e. What is the next bracket you would use? Or would needing to do that be considered bad notation and an indication that you should simplify/expand your expression?
What is accepted practice in literature? Is there a convention, and if so what is it? Do some people not even use different types of brackets? I could see a case being made that you just stick to the round brackets () for each level, just use different sizes maybe. I had trouble finding good and insightful answers so here I am on SO. I look forward to your answers.
Related but unanswered
Comment: it's all parentheses all the time for operation grouping in programming; there, curly braces and square brackets mean very different things!  - And, indeed, parentheses themselves collect additional meanings.
Comment: related https://math.stackexchange.com/q/1875182/889261
Comment: There is no agreed convention. I would avoid curly braces altogether to avoid confusion with set notation. I think lots of people just stick to round brackets and use layout and the size of the brackets to improve readability.
Comment: Given @QuantumMechanic's informative answer and reference, I will qualify my comment: I don't believe there is an agreed convention in pure mathematics.
Comment: @RobArthan I'm not even certain the convention is agreed upon in physics, I can simply attest to its existence
Comment: @QuantumMechanic that related thread has excellent discussion, strange it didn't come up in my search. Thank you!
Answer: One convention is to repeat again in the same order. So a nested expression can look like
\begin{equation}
\left\{f\left[e\left(d\left\{c\left[b\left(a\right)b\right]c\right\}d\right)e\right]f\right\}.
\end{equation}
Comment: In this physics style guide they prescribe my quoted rule, so perhaps it's a physics thing https://journals.aps.org/prl/authors/bracketing-mathematical-expressions-h9
Comment: Interesting. Makes sense, but I have never seen this, though.
Comment: I learned this many years ago from who knows where
Comment: @QuantumMechanic Neat -- a source like the APS is something I was actually looking for. Thanks for the insight, I had never seen that convention to repeat it.
Comment: I also found it in this ~decade-old Physical Review Style Guide (sorry I only found a pdf): https://cdn.journals.aps.org/files/styleguide-pr.pdf - there they say to put the outer set of symbols in bold!


How to create a *.crt file out of keystore? (SSL / Tomcat)

Question: to use https (ssl) with tomcat i build a keystore with this commands:
<code>$JAVA_HOME/bin/keytool -genkey -alias [youralias] -keyalg RSA -keystore [/preferred/keystore/path]

$JAVA_HOME/bin/keytool -certreq -keyalg RSA -alias [youralias] -file [yourcertificatname].csr -keystore [path/to/your/keystore]
</code>
Now i want to import a certificate into InternetExplorer (Menü->Internet Options->Content->Certificate-Import). The import function of the IE requires an *.crt file. So how can i create a *.crt file out of the keystore. I was looking aroung on the net to get some infos. I only found infos to create *.jks file or import *.crt to the keystore. But not erxport or create a *.crt out of the keystore.
Thx and kind regards
yefpie
Comment: I'm on mobile but use the `-export` and the `-rfc` options to get the base64 printable encoding format I.E. expects
Answer: Use OpenSSL for this, Tomcat keystore is a .p12 keystore type:
https://stackoverflow.com/questions/9497719/extract-public-private-key-from-pkcs12-file-for-later-use-in-ssh-pk-authentifica


css inline-blocks and bootstrap grid system output

Question: I'm trying to have a specific HTML markup of my divs using css and bootstrap 3.2. The image below demonstrates the result I want to get.
I've used the bootstrap grid system so that my page would be responsive and properly displayed in small screen devices. This is the code I've tried.  And I used http://www.bootply.com to test it.
Any ideas how to get the markup ?

This is the product name

1 230.99

Property 1

Property 2

The desired result :

EDIT : The result I get :
Answer: I've created a Bootply for you.

              This is the product name

              1 230.99

              Property 1

              Property 2

Comment: Thanks for your answer, but the space between the image and the other content is too big, that's why I didn't include the image in the bootstrap grid system.
Comment: Do you still find it to big after change `.col-md-3` to `.col-md-2`? [See my updated Bootly](http://www.bootply.com/a8vgNCTxmZ). If so, let me know. We'll add some CSS.
Comment: By fixing the width of the div cotaining the image to 185px, i've the markup wanted. Thank you.


Problem showing Newtons Laws are invariant under the Euclidean Group

Question:
I am trying to show that the equations of motions of physics are invariant under the Euclidean group $E_N$ for $N=3$. Therefore we have Newton's Laws as: $$m\frac{d^2 \mathbf{x}(t)}{dt^2}=-GmM\frac{\mathbf{x}(t)-\mathbf{y}(t)}{\left \|\mathbf{x}(t)-\mathbf{y}(t) \right \|^3},M\frac{d^2 \mathbf{x}(t)}{dt^2}=-GmM\frac{\mathbf{y}(t)-\mathbf{x}(t)}{\left \|\mathbf{x}(t)-\mathbf{y}(t) \right \|^3}$$

And so I work out; let new vectors be defined as $\mathbf{x'}(t)=A\mathbf{x}(t)+\mathbf{b}$ and $\mathbf{y'}(t)=A\mathbf{y}(t)+\mathbf{b}$, where $A\in O(3)$ is an orthogonal matrix and $\mathbf{b}$ a constant vector. Now we see if $\mathbf{x'}$ and $\mathbf{y'}$ satisfy the same equations above. Hence, $$\frac{d^2}{dt^2}\left ( A\mathbf{x}(t)+\mathbf{b}\right )=A\frac{d^2}{dt^2}\mathbf{x}(t)$$ And $$-GmM\frac{A\mathbf{x}(t)-A\mathbf{y}(t)}{\left \| A\mathbf{x}(t)-A\mathbf{y}(t)\right \|^3}=-GmM\frac{A}{A^3}\left (\frac{\mathbf{x}(t)-\mathbf{y}(t)}{\left \|\mathbf{x}(t)-\mathbf{y}(t) \right \|^3} \right )$$ Now here is the problem; I need the RHS to have a factor of $A$ not $\frac{1}{A^2}$. In order to give the conclusion that the only difference by the change of variables is a factor of $A$ and since we assume $A$ is never the zero matrix, the physical laws are invariant under the Euclidean group.
Comment: Orthogonal transformations do not change the distances, i.e.
$${\left \| A\mathbf{x}(t)-A\mathbf{y}(t)\right \|} = {\left \| A\left(\mathbf{x}(t)-\mathbf{y}(t)\right)\right \|}={\left \| \mathbf{x}(t)-\mathbf{y}(t)\right \|}$$
Answer: First of all, $A$ is a matrix, hence you can not write the line $$-GmM\frac{A\mathbf{x}(t)-A\mathbf{y}(t)}{\left \| A\mathbf{x}(t)-A\mathbf{y}(t)\right \|^3}=-GmM\frac{A}{A^3}\left (\frac{\mathbf{x}(t)-\mathbf{y}(t)}{\left \|\mathbf{x}(t)-\mathbf{y}(t) \right \|^3} \right ),$$
it is quite false.
We know that  in general case $$\|Ax \|\le \|A\|\|x  \|.$$
Nevertheless, if $A\in O(3)$, then we always have $$\|Ax\|=\|x\|.$$
Therefore
$$-GmM\frac{A\mathbf{x}(t)-A\mathbf{y}(t)}{\left \| A\mathbf{x}(t)-A\mathbf{y}(t)\right \|^3}=-GmM {A} \left (\frac{\mathbf{x}(t)-\mathbf{y}(t)}{\left \|\mathbf{x}(t)-\mathbf{y}(t) \right \|^3} \right ).$$


Imagelist always returns -1

Question: I'm designing a small game using windows forms in which there is 5 labels, each set to resemble an image of dice ( 1 - 6 ) from a specified imagelist. The game is made to be "rolled" 3 times, at the end of the roll you can select labels NOT to be rolled by changing their background color. At the end of each roll, the sum of the die faces is calculated and presented.
Now for the problem...
I know that my labels can reach the imagelist as the "rolling" function of the dice works very well. Each label is set to be run through a timer tick event that will occur 10 times in which random images are selected from the imagelist, creating the illusion of rolling dice. However, when I wish to ADD the total of the die faces at the end of the rolling cycle using the imagelist index, each index returns -1. Take note, the index of each respective die is one less than the amount of the die. Likewise, if you had a die resembling a one, it's index would be zero. I account for such by adding 1 to the index. So... although I may have a 5,5,6,4,3 - my score counter amounts to 0, rather than say 23.
Why would the imgaelist index give a value of -1 when the lowest available index is 0?
Here is my code. The actual calculation for the sum of the die faces is made in the else statement. I set m_iScore (the score counter) to zero prior to evaluating the sum because I want the sum to be representative of the faces after EACH roll.
private void timer1_Tick(object sender, EventArgs e)
        {
            Label[] labelArray = new Label[] { label1, label2, label3, label4, label5 };
            Random randnum = new Random();
            if (m_iAnimations < 10)
            {
                for (int iCount = 0; iCount < labelArray.Length; iCount++)
                {
                    if ((labelArray[iCount]).BackColor == Color.Lime)
                    {
                        (labelArray[iCount]).Image = imageList1.Images[randnum.Next(0, 6)];
                    }
                }
                m_iAnimations++;
            }
            else
            {
                timer1.Enabled = false;
                m_iAnimations = 0;
                m_iScore = 0;
                for (int iCount = 0; iCount < labelArray.Length; iCount++)
                {
                    m_iScore = m_iScore + ((labelArray[iCount]).ImageIndex + 1);
                }
                scoreval.Text = m_iScore.ToString();
            }

        }

If I don't add 1 to the image index, scoreval.Text shows -5.
Answer: Setting the Image property doesn't change the ImageIndex property -- they're more-or-less completely unrelated.
In general, UI should display program state, not hold it. Do all your computation, then push the results of that computation into the UI; don't use the UI elements as if they're variables.

Imagelist always returns -1


Font is abstract ; Cannot be instantiated

Question: Im trying to make some text bold in a JTable with
jtable.setFont(new Font("Serif", Font.BOLD, 12));

However its throwing an error saying "Font is abstract ; Cannot be instantiated"
Im literally following a tutorial and its saying it should work
What else in my program could be affecting it?
Thanks
Answer: You are not importing java.awt.Font but another Font class.
The constructor for java.awt.Font should allow your initialization.
Comment: Thank you very much. Live and learn.


Unable to compile Electron App due to incorrect parser

Question: So I'm trying to get a simple electron app up and running with Vue 3 and Typescript. Currently, I have run the following commands that allow an electron + Vue 3 app to run successfully:
vue create app_name
cd .\app_name\
vue add electron-builder
npm run electron:serve

After that, things go downhill when I try to implement typescript. I tried to change the


Bootstrap and randomization tests to compare paired data sets

Question: I have 50 values set as "true" in a simulation and attempts to recover these "true" parameters using 2 different models.  Here's 3 (instead of 50) runs just to show the data layout (these are made up for illustration).
<code>Run ,  "true" parameter ,  estimate model 1  , estimate model 2
1   ,       10          ,      9.5           ,      9.6
2   ,        8          ,      7.5           ,      8.1
3   ,        7          ,      7.1          ,       7.2
</code>
For each of the two models, I have calculated root mean squared error (error is difference between "truth" and estimate), mean absolute error, and Pearson correlation (correlation between 50 "truth" measures and 50 estimates).  For each accuracy measure, I would like to compare the performance between the two models.  Normality assumptions are not satisfied, so I would like to use bootstrap methods.
Since the data is paired, I've thought I could resample by runs (with replacement, 50 draws, and as many replications as feasible).  I would then calculate the statistic of interest for each model and save the ratio of these for each run (RMSE model 1/RMSE model 2 for instance) and then determine confidence intervals using a percentile (or other) method.
I would also like to use a direct hypothesis testing approach via resampling.  For this, I would shuffle the model outputs within pairs (so the estimated values for model 1 and model 2 would be switched, for instance) at random and then calculate my various ratios as before.  This would give a range expected given a null hypothesis of interchangeability to compare to my observed values in order to attain a p-value.
I have ordered Efron and Tibshirani's Intro to the Bootstrap and will read parts that apply, but I have not found much literature on what I would like to attempt.  Perhaps I am looking in the wrong place or it is an obvious dead end.
I am open to any advice or obvious flaws in my approach.
Thank you
Comment: Sounds good to me. For your second approach (permutation test), a standard reference seems to be [Good, PI (2005) Permutation, Parametric, and Bootstrap Tests of Hypotheses](http://www.springer.com/statistics/statistical+theory+and+methods/book/978-0-387-20279-2). Is there a specific reason for choosing the ratio of your performance measures as a test statistic instead of their difference? WRT boostrap CIs: BCa intervals are supposed to be more accurate when the bootstrap-distribution exhibits skew and bias.
Comment: This is my first post.  Sorry that I did not format the toy example so that it would not be "destroyed".  I think clarity is still retained.
Comment: Formatting is easy to do using the tools just above the edit textbox.
Comment: Thanks.  I was perhaps following the shadow of the F-test when thinking to use ratios, is using differences defensible?
Comment: That's why I was asking: writing the ANOVA or regression F-ratio from the model-comparison point of view, the numerator is the difference in RSS of the restricted and the full model (divided by the difference in their df). I.e., the comparison between two models is done by taking the difference of a performance measure that is almost your RMSE. Of course you don't have two nested models, but I think the idea is natural to carry over. Perhaps not to correlations though, these are normally compared using Fisher's Z-transormation.
Comment: wvguy8258: what sort of "accuracy" do you care about in your case? stats mostly uses mean squared error (MSE; same as Bias squared plus Variance), but sometimes minimax loss functions are more appropriate (to get best "worst case" performance). also, what range of the true value do you care about? unless you have analytic results that say otherwise, MSE (or minimax, etc.) can depend on the true value; e.g. [bias of maximum likelihood sample variance](http://en.wikipedia.org/wiki/Bias_of_an_estimator#Sample_variance). do you have any analytic results?  hope we can help more after clarification!
Answer: Your permutation test is correct for testing if there is a difference in the quality of the 2 models.  I don't understand enough about your bootstrap approach to know if it is correct or not.  Another book to consider is "Bootstrap Methods and their Application" by Davison and Hinkley.  It is a bit more recent and I believe more applied than Efron and Tibshirani.
Comment: Thanks.  For permutation test, I would be respecting the paired nature of the data.  So, I would switch values within runs, between models.  So, in run 1 I may switch values so that model estimate 1 would then be 9.6 (not 9.5).  I hope that was clear and the correct approach for a paired randomization/permutation test.
Comment: As far as the bootstrap approach, it is an extension of selection with replacement to get a distribution for a test statistic.  In the one sample approach, I would just select from model 1 estimates and calculate a summary stat for each draw. Since I am interested in the difference between the summary stats, and the data is paired, I would select runs at random.  I would then summarize the data separately for each model among the selected runs.  I would then calculate the ratio or difference between these two summarized samples.  No shuffling of the values between the two models would occur.


Hostname won't resolve correctly if apache ServerName isn't localhost

Question: We have a lamp centos 7 server in a datacenter, behind some sort of a Nginx proxy. We only have control over our centos server, we don't know anything about the proxy/firewall or anything. We have installed SSL.
In httpd.conf, ServerName, the one that is not in <VirtualHost>, line 97
if  ServerName localhost then the website loads correctly, HTTP only, you get this SSL error
 RSA certificate configured for example.com:443 does NOT include an ID which matches the server name

if ServerName example.com then SSL loads correctly but if you try to access it either over HTTP or HTTPS you get  access denied, just that, probably this error is from Nginx or something not sure
If we omit ServerName, line 97 we get
httpd: Could not reliably determine the server's fully qualified domain name
The datacenter support says

We tested port 80 & 443 for the server and they are open; it looks like a web configuration issue.
Comment: `ServerName` must match the name in the SSL certificate. The hostname of the server is irrelevant. `Access Denied` is a different issue, you need to provide the relevant configuration parts to get help with this.
Comment: You can ignore the warning about "Could not reliably determine the server's fully qualified domain name". You have to fix the ServerName as @GeraldSchneider has mentioned. Then you can work on fixing the other error.
Answer: Servername must match with the common name of the ssl certificate. Regarding access denied error you need to provide the correct document path that must have the complete rights to access.


MySQL indexes and OR operator

Question: Ok so I have a table over here and I've set a primary index on the auto incremented column id. However occasionally I will need to search by another column named owner, since multiple items can have the same owner I can't put a unique index so I went ahead and just put an index index. I ran a query
EXPLAIN SELECT * FROM table WHERE owner = 15 OR owner = 16
Then for possible keys I get owner as expected, and for used keys I get NULL. Which is I guess because I have too little rows, however if I run
EXPLAIN SELECT * FROM table WHERE owner = 15
For possible keys I get owner and for used keys I also get owner, with the same amount of rows.
So this made me unsure whether this index is going to be useful or not in a larger scale and in case this index will not be useful in an OR condition, can you guys please tell me how I must index the table so that it won't go through all records in case of an OR.
Thank you for your attention.
Answer: The MySQL optimizer doesn't use an index if the values you search for occur in a significantly large portion of the table. In my experience, "significantly large" means about 20% of the table.
So it could be that owner 15 is somewhat rare, but owners 15 and 16 together cross the threshold, so they represent a large part of the table, and the optimizer decides to do a table-scan or an index-scan instead.
For example, looks at what's reported in the rows field of your EXPLAIN. If the optimizer thinks that number of rows examined is over 20% of the size of the table, then that's what's going on. Remember that the rows reported here, and in SHOW TABLE STATUS, are only a rough estimate.
I have seen cases where this behavior of the optimizer is not the right choice, and it would be better to use the index. In that case you can make the optimizer think of a table-scan as prohibitively costly:
SELECT * FROM table FORCE INDEX(owner) WHERE owner = 15 OR owner = 16

Comment: If the query uses an index, `OR` makes it a *range* query instead of a *ref* query, so yes it's different but still benefits from the index.
Comment: Basically what I was asking was if `OR` made any difference to the way the index is used, and particularly if it would cause the index to not be used, since I'm not looking for one value
Answer: I suspect the index will be quite useful when the table is larger.
I suggest adding a enough test data so that the entire table doesn't fit in memory then retest.

MySQL indexes and OR operator


Mathematical term for "opposite" in this context?

Question: A friend wanted to play a game where we would roll a die, and if it landed even then the wish would come true, but if it landed odd then the opposite of the wish would come true. So let's say I have five dollars and my wish is to gain five dollars.
I know the negation of gaining five dollars is not gaining five dollars. But that is not the 'opposite' of my wish in this context. The opposite would be losing five dollars. What is the operation called that's being applied to "gaining five dollars" such that it becomes "losing five dollars"?
Comment: There's no meaningful notion of the opposite of a thing happening. Suppose you wish for a red cube. What's the opposite of that? Losing a red cube? What if you don't have one?
Comment: Hmmm... I don't think there is a symbol in symbolic logic for the "opposite", since this concept can get a bit sticky when talking about non-numerical things.
Comment: I wish for the die to come up odd.
Comment: Wish for the dice to be even: Infinite cycle!
Comment: Well I meant to include the premise that I have five dollars, so to make it an equal analogy we should include the premise that I have a red cube.
Comment: Gaining $-5$\$? So the operation being negation
Answer: Change the rules of the game. The game costs \$5 to play and you can gain $10 by winning.


nginx: browser rewriting http request to https when not wanted

Question: So I have an nginx config that looks like this:
## Redirects all HTTP traffic to the HTTPS host
server {
  listen *:80;
  server_name me.example.com;
  server_tokens off;
  return 301 https://me.example.com:443$request_uri;
  access_log  /var/log/nginx/access.log;
  error_log   /var/log/nginx/error.log;
}

server {
  listen *:443 ssl;
  ...
}

server {
  listen *:9080;
  location / {
    root /var/www;
    index index.html index.htm;
  }
}

The intention is to direct http traffic on port 80 to https (443). Works like a champ. The problem is that my request to port 9080 are causing my browser to switch to https and then failing (since I'm not using ssl on 9080, nor do I want to).
In Safari or Chrome: http://me.example.com:9080/index.html -> https://me.example.com:9080/index.html Can't establish secure connection.
With CURL:
curl -v http://me.example.com:9080/index.html
* Hostname was NOT found in DNS cache
*   Trying x.x.x.x...
* Connected to me.example.com (x.x.x.x) port 9080 (#0)
> GET /index.html HTTP/1.1
> User-Agent: curl/7.37.1
> Host: me.example.com:9080
> Accept: */*
>
< HTTP/1.1 200 OK
* Server nginx/1.4.4 is not blacklisted
< Server: nginx/1.4.4
< Date: Thu, 09 Apr 2015 18:32:02 GMT
< Content-Type: text/html
< Content-Length: 157
< Last-Modified: Thu, 09 Apr 2015 18:19:42 GMT
< Connection: keep-alive
< ETag: "5526c2be-9d"
< Accept-Ranges: bytes
<

<title>Test Server</title>

Welcome to the Test Server!"

* Connection #0 to host me.example.com left intact

Is this a browser issue? Is there something I can do to make the browser happy?
UPDATE
In Chrome, you can remove a site from HSTS by navigating to this URL:
chrome://net-internals/#hsts
h/t to this site that has instructions for other browsers as well.
Comment: I'm fairly certain this relates to the "Strict-Transport-Security" header. http://superuser.com/a/662424/51803 Perhaps there is nothing I can do in the nginx config.
Comment: Not sure about that, as your curl output does not show an STS header? Can you make the request in Chrome, and inspect the network requests from the Network tab in Chrome developer tools.
Comment: It's a security feature, chrome and firefox for example will remember the STS setting and all subsequent surfing to that domain will, before sending it to the server, add a s to http before retrieving the page.This is for  man in the middle protection and so an attacker can not remove the setting and force http://
Answer: I'm guessing you are sending an HTTP Strict-Transport-Security (HSTS) header from the HTTPS server block.
The purpose of the HSTS header is to be bound to the domain name it was received from. It is then known as an HSTS host by the User-Agent (UA) and held in its cache for max-age seconds.
During this time further HTTP requests to the domain, or a valid subdomain if told by the includeSubDomains directive, will get through a special processing described by RFC 6797 section 8.3 :

      The UA MUST replace the URI scheme with "https" [RFC2818], and

      if the URI contains an explicit port component of "80", then
      the UA MUST convert the port component to be "443", or

      if the URI contains an explicit port component that is not
      equal to "80", the port component value MUST be preserved;
      otherwise,

      if the URI does not contain an explicit port component, the UA
      MUST NOT add one.

     NOTE:  These steps ensure that the HSTS Policy applies to HTTP
            over any TCP port of an HSTS Host.

NOTE:  In the case where an explicit port is provided (and to a
       lesser extent with subdomains), it is reasonably likely that
       there is actually an HTTP (i.e., non-secure) server running on
       the specified port and that an HTTPS request will thus fail
       (see item 6 in Appendix A ("Design Decision Notes")).

This means that if you are trying to send an HTTP request to a known HSTS host with a matching domain name (section 8.2 for the details) then as long as the HSTS host entry in the UA cache has not expired, HTTP traffic will transparently switch to HTTPS either :

on port 443 if the HTTP port was 80 (explicitely or implicitely) in the target URI
on the same port otherwise
Comment: HSTS is disabled by default and enabled with `add_header Strict-Transport-Security "";` so if you don't see that in your nginx configuration, then it isn't enabled. Among other methods, you can see what is going on with your SSL configuration using the Qualys SSL Labs [SSL Server Test](https://www.ssllabs.com/ssltest/index.html).
Comment: Thanks, great explanation. Can nginx be configured to not send this header?


Relative increase between two pairs of samples

Question: Consider the following samples from four distributions:
$a = \{20, 2, 200\} \qquad\qquad c = \{1, 10, 100\}$
$b = \{22, 2.2, 220\} \qquad\quad\:\,d = \{1.2, 12, 120\}$
I would like to say that the relative increase from $a$ to $b$ is significantly less than the relative increase from $c$ to $d$.

If the samples are assumed to be paired, with the $n$th element of $a$ corresponding to the $n$th element of $b$, this can be done with a Mann-Whitney U test on the element-wise ratios of the distributions:
$\frac{b}{a} = \{1.1, 1.1, 1.1\}$ vs $\frac{d}{c} = \{1.2, 1.2, 1.2\}$
giving a p-value of 0.02 (tending towards 0 with larger samples).

But what if the samples are not assumed to be paired, or have different sizes?  A 'ratio bootstrapping' test could be used instead: randomly select numbers $a_i$, $b_j$, $c_k$, $d_l$ with replacement from each distribution and see how often $b_j / a_i < d_l / c_k$.
For this example, 31 of the 81 possible selections have $b_j / a_i > d_l / c_k$, giving a p-value of $\frac{31}{81} \approx 0.38$.  Ratio bootstrapping is inconclusive here because the variance within each distribution is larger than the variability (e.g. difference in means or medians) between the pairs of distributions.
Is there a statistical test which accomplishes the same thing as ratio bootstrapping, but is insensitive to intra-distribution variance and only focuses on the variability between distributions?
Comment: You seem to be saying "what if the data aren't paired?". If values are positive, you could consider shifts in the mean of the logs, perhaps (since on the log scale the mean difference of pairs and the difference of unpaired means should both estimate the same location difference).
Comment: @Glen_b Yes, paired rather than ordered is a better way of putting it.  Neat idea!  However, if I am only using the mean of the logs of each distribution (4 numbers), how can I get a reliable p-value?
Comment: You compare the means of the logs; that doesn't mean you *only use the means of the logs*. I simply meant compare locations via a standard location test, such as a t-test.
Comment: Alright, but a t-test only compares two distributions.  How are you suggesting using it with four?
Comment: Ah, yes, I see. You could look at a specific contrast in ANOVA.
Answer: Converting my comments to an answer:
One possibility is to work on the log-scale (since on the log scale the mean difference of pairs and the difference of unpaired means should both estimate the same location difference).
Since you have quadruplets of observations that share a "position", you could consider either 'pairs of pair-differences' or an ANOVA, with the position as a blocking factor and test a contrast that corresponds to the comparison of ratios. The advantage of the ANOVA approach is that you can do more general things (e.g. treat the positions as a random effect rather than fixed effect, or test other form of hypothesis relatively easily).
Comment: Is it actually valid to use Anova in this situation, when the data are not normally distributed?  Is [nparcomp](http://artax.karlin.mff.cuni.cz/r-help/library/nparcomp/html/nparcomp.html) with a user-defined contrast matrix applicable here?  Also, if I am correct, this compares medians rather than means, which is preferable for me.
Comment: Note that (i) what's assumed to be normal is the conditional distributions (equivalently, the error term) on the log scale; (ii) ANOVA is still best linear unbiased, so if you're after estimates it still does quite well any time a linear estimator is reasonable; (iii) as far as CIs and tests go, ANOVA is fairly robust to moderate deviation from normality (if the conditional distribution on the log scale is still a problem, you can use permutation/randomization approaches, or the bootstrap, or robust methods); ... (ctd)
Comment: (ctd) ... (iv) if the conditional distribution on the log scale is approximately normal you can estimate the mean on the original untransformed scale pretty well by an adjustment (multiply by $\exp(\frac{_1}{^2}\hat{\sigma}^2)$), but if you're interested in the ratio, the adjustment term cancels out (that is, a ratio of means will be the same as a ratio of medians). Even if it's only close to normal, you can derive a similar term as an expansion which will also cancel; (v) if you are prepared to make some other parametric assumption, you may be able to derive what you need. Lots of options...


Select por grupo

Question: Bom dia pessoal, gostaria de sabe como fazer o seguinte SELECT no mysql:
Tendo a tabela à seguir, preciso selecionar as 3 ultimas compra de cada Nome:

Desde de já, Obrigado
Comment: `select * from table group by nome order by data asc limit 3`
Comment: Desta forma ele pega os 3 últimos valores porem 1 de cada Nome
Comment: Rone, você tem um ID único em cada registro?
Comment: Desculpa não ter informado, mas tenho sim.
Answer: Rone,
uma opção é essa:
<code>SELECT A.* FROM COMPRAS A
WHERE (SELECT COUNT(*) FROM COMPRAS B WHERE B.NOME = A.NOME AND B.DATA >= A.DATA) <= 3
ORDER BY NOME, DATA;
</code>
Comment: Se eu entedi bem, acredito que seja necessário apenas colocar o LIMIT 20 no final da consulta ordenada apenas pela data. Assim:

SELECT
 A.*
FROM
 COMPRAS A
WHERE
 (SELECT COUNT(*) FROM COMPRAS B WHERE B.NOME = A.NOME AND B.DATA >= A.DATA) <= 3
ORDER BY
 DATA
LIMIT 20;
Comment: Funcionou perfeitamente. Também tenho a seguinte situação:
Comment: O select seria com um limite de 20 resultados, porem se o Nome aparece mais de 3 vezes ele elimina as vezes excedentes, dando oportunidade para outro nomes aparecer nesta lista de 20. Também ordenado por data.
Comment: Coloquei assim: ORDER BY data DESC LIMIT 20, ai ficou perfeito, Muito Obrigado Davy pela ajuda...
Comment: Isso mesmo Rone!

Select por grupo


Prove that if $\gcd(m,n)=1$ then every divisor $d|mn$ has a unique form $d=ab$ such that $a|n$ and $b|m$.

Question: I can see why this is true. I have a problem with formality or with explaining certain things properly.
An attempt: suppose there are two forms $d=a_na_m=b_nb_m$ such that $a_n,b_n|n,a_m,b_m|m$ but $a_i\ne b_i$. Therefore, in $d'$s prime factorization, WLOG, there is a prime $p$(not 1) dividing n that is in $b_n$'s prime factorization but not in $a_n$'s. However, $a_m$ divides $m$.
$p$ could not be excluded as being a factor in $d'$s prime factorization. Therefore it is in $a_m$'s prime factorization, contradicting that facts that $(m,n)=1$ and $p\ne 1$.
I would appreciate your criticism. I would accept it as an answer as well.
Comment: You've successfully proven uniqueness, but you have to still prove existence.
Comment: You're correct. I shall try proving existence.
Comment: Assume that $d$ is a divisor of $mn$ and $d=ab$ with $a$ dividing $m$ and $b$ dividing $n$, what are $gcd(d,m)$ and $gcd(d,n)$?
Answer: Your proof is correct. For existence, observe that $d=(d,mn)$ and since $(m,n)=1$ you know $d=(d,mn)=(d,m)(d,n)$.
By definition of $\gcd$ we have $(d,m)\mid m$ and $(d,n)\mid n$.
Comment: I never knew this lemma. I will try to prove it.
Thank you.
Answer: That's enough to observe that $a=(n,d),b=(m,d)$.


How to customize Schema.org at node level?

Question: I am using the Schema.org module for schema tags, which allows me to customize schema tags at content type.
How can I customize schema tags at node level?
Answer: As I understand your question, you would like to be able to override the Schema.org types per each node separately.
This is not possible at least out of the box. You would have to write custom code to display a tab on each node form, store it somewhere and then load it when the node is about to be viewed.
This is because content types are generally used for storing the content of the same kind. For example: an article, a blog post, a static page, a webform and so on. This means that all nodes of certain type will need the same Schema.org declarations, and that's why it was implemented this way.
You are probably storing different kinds of nodes using one "generic" content type. This is not the most common use case. Unless you have strong reasons for doing this, I suggest migrating the content to separate content types. It will benefit you in case you want to use other similar modules as well, such as Metatag.
Hope I managed to explain it.


SimpleXML não retorna os dados do arquivo

Question: Estou usando simplexml do php para pegar os dados de um arquivo xml, mas não retorna nada.
O que pode ser ?
<?php

@header('Content-Type: text/html; charset=utf-8');

$xml = simplexml_load_file("http://www.multicinecinemas.com.br/webservice/?chave=c99e34ed77750774417e5a9d2a2f5135&tipo=cinema");

foreach($xml->filme as $filme)
{
 echo $filme->codigo;
 echo $filme->nome;
 echo $filme->horario;
 echo "
";
}
?>

Comment: A forma q vc está iterando o xml que está errada. Repare que na estrutura do arquivo vc não começa com filme, começa com cinemas > cinema > filmes
Comment: Como eu faço isto funcionar? Não manjo desses "subníveis"
Answer: Para chegar a imprimir somente o filme precisa navegar até o ponto correto:

$xml->CINEMAS->CINEMA->FILMES->FILME

Por exemplo:
<?php

    $url = 'http://www.multicinecinemas.com.br/webservice/'
    $url .= '?chave=c99e34ed77750774417e5a9d2a2f5135&tipo=cinema';

    $xml = simplexml_load_file($url);

    foreach($xml->CINEMAS->CINEMA->FILMES->FILME as $filme)
    {
        echo $filme->CODIGO;
        echo ' ';
        echo $filme->NOME;
        echo ' ';
        echo $filme->HORARIO;
        echo ' ';
        echo "
";
    }

Para repetir o mesmo processo para varios arquivos use uma função como está:
function toPrint(array $array = array())
{
    foreach($array as $items)
    {
        foreach($items->CINEMAS->CINEMA->FILMES->FILME as $filme)
        {
            echo $filme->CODIGO;
            echo ' ';
            echo $filme->NOME;
            echo ' ';
            echo $filme->HORARIO;
            echo ' ';
            echo "
";
        }
    }
}

$url = 'http://www.multicinecinemas.com.br/webservice/'
$url .= '?chave=c99e34ed77750774417e5a9d2a2f5135&tipo=cinema';
$xml = simplexml_load_file($url);

toPrint(array($xml1, $xml2));

Comment: Deu certo.
No caso, eu preciso pegar imprimir dados de 2 arquivos xml. Como eu faria para inserir dentro de uma variáriavel $xml2 os dados do outro arquivo, dentro do foreach? Tipo: foreach($xml->CINEMAS->CINEMA->FILMES->FILME as $filme, $xml2->FILMES->FILME as $filme2)
Comment: @LeoAmaral repita o mesmo procedimento para o `xml2`, pode construir uma função para imprimir e passe os dois arquivos, vou editar e propor uma função.


How to assign nodes to an organic group in code

Question: How can I assign a node to an organic group in code?
After consulting following page

http://www.barnettech.com/content/adding-node-organic-group-programmatically
Programmatically assign a node to an organic group

And de OG API I ended up with this code, but it throws an error 'The website encountered an unexpected error. Please try again later.'
<code>$node = node_load(5827);
$values = array('entity type' => 'node', 'entity' => $node, 'field_name' =>'og_group_ref');
og_group('node', 3, $values);
node_save($node);
</code>
More info:
OG-7.2.7
Comment: Check the watchdog, it will contain the real error message
Comment: Thanks for the advice. It seems like it want to add it to a user type instead of a node group type.
   OgException: OG membership can not be created in entity user and bundle user using the field og_group_ref as the field does not exist. in OgMembership->save() (line 50

I've tried the code on a clean install, but it gave me an identical error

More info, but no success:
https://www.drupal.org/node/1734526
https://www.drupal.org/node/1421478
Comment: Ok, the issue was caused by type error in the values array. 'entity type' must be 'entity_type'.
Now the code is error free but the nodes aren't assigned to group. Any suggestions?
Answer: Found out removing the last line from the snippet 'node_save($node)' and the above type error was the reason for my problem. Thanks for the support.


how to simplify this function in terms of x?

Question: I have the following equation:
$y=\frac{3x}{x^{2}+1}$
and I want to obtain x in terms of y, so far what I have done is the following:
$3x=y(x^{2}+1)$
$3x=x^{2}y+y$
$3x-x^{2}y=y$
and at this point I got stucked, because that cuadratic term would not allow me to just get one x in one side of the equation. Any advice? Thanks
Comment: you have a polynomial of degree 2 in $x$. Apply quadratic formula and you will get 2 values for $x$.
Comment: It is not possible to express $x$ as a function of $y$ because the given function is not injective.
Comment: thank you @user376343, is that because the square term appears in x, so that a positive and a negative number could me mapped to the same y?
Comment: $x^2(-y) + x(3) + (-y) = 0$.  This is a quadratic equation in $x$, of form $Ax^2 + Bx + C = 0$, where $A = -y, B = 3, C = -y$.  Simply apply the formula $\displaystyle x = \frac{1}{2A} \times \left[ -B \pm \sqrt{B^2 - 4AC}\right].$  This will yield (potentially) $2$ **candidate specifications for $x$ in terms of $y$.  You must then manually check each candidate specification against the original expression of $y$ in terms of $x$, to determine which candidate specification(s) (if any) satisfy the original expression.
Comment: @Lila I added an answer not a comment, because the graph helps (I do not know to enclose a picture in the comment).
Answer: Set $f(x)=\frac{3x}{x^2+1}.$ For any $x\in\mathbb{R}$
$$f(-x)=-f(x)$$ Therefore, the function is odd and there is no difficulty due to positive or negative values of $x.$ But the function is not injective, as can be seen on its graph

The function is differentiable on $\mathbb{R}.$ With the help of analysis we can verify that $f(-1)=-3/2$ is a minimum, $f(1)=3/2$ a maximum, the limits at $\pm \infty$ are zero, and each value $y\neq 0$, $y\in (-3/2, 3/2)$ is obtained for two different values $x_1, x_2.$
Comment: Thank you for your answer, do you think that I can safely said that the function is not injective also because of the presence of the x^2 term?
Comment: No. As a counterexample: $f(x)=x^3+x^2+x$ is injective, but has $x^2$ in its expression.
Answer: From the last equation, you get $$x^2y -3x +y=0$$ and using quadratic equation, while treating $x$ as the variable, and the $y$ terms as coefficients, you get $$x = \frac{3 \pm \sqrt{ 9 - 4y^2}}{2y}$$ if $y\neq 0$. (In $y=0$ case also, we can easily get that $x=0$.)
Also, note that strictly speaking, this is not a function as $x$ can attain two different values for the same $y$, but this does give a way to compute $x$ in terms of $y$.
Comment: Thank you, but in this case I think that this function pass the vertical line test or am I wrong? I think that is not one-to-one.


Visual representation of the Mandelbrot set

Question: I want to generate a PNG photo of the Mandelbrot set using Java, the output should be easily found on a google images search.
The set is defined as the following sequence:
z_n+1 = z_n^2 + c

where c and z are complex numbers, and z always has a modulus smaller than 2.
I started by defining a class for complex numbers, which also contains the basic complex operations needed.
public class ComplexNumber {
    private double real;
    private double imaginary;

    public ComplexNumber(double real, double imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }

    public ComplexNumber add(ComplexNumber z1, ComplexNumber z2) {
        ComplexNumber sum = new ComplexNumber(0, 0);
        sum.real = z1.real + z2.real;
        sum.imaginary = z1.imaginary + z2.imaginary;
        return sum;
    }

    public ComplexNumber square(ComplexNumber z) {
        ComplexNumber squared = new ComplexNumber(0, 0);
        squared.real = Math.pow(z.real, 2) - Math.pow(z.imaginary, 2);
        squared.imaginary = 2 * z.real * z.imaginary;
        return squared;
    }

    public double abs() {
        double absolute = Math.sqrt(Math.pow(this.real, 2) + Math.pow(this.imaginary, 2));
        return absolute;
    }
}

I have then defined the Mandelbrot class which gets a number of a complex numbers c (based on pixels) check if these numbers are in the mandelbrot set using the mandelbrot method, and tranfers the output of this method to a color to be displayed.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Mandelbrot {

    public static int mandelbrot(ComplexNumber c, ComplexNumber z, int i, int n) {
        if (i < n) {
            if (c.abs() > 2.0) {
                return i;
            } else
                return 0;
        }
        return mandelbrot(c, z.square(z).add(z, c), i, n);
    }

    // Create the Mandelbrot image, fill it and save it as PNG file.
    public static void createMandelbrotImage(int tileSize, int maxRecurse) throws IOException {
        int height = 2 * tileSize;
        int width = 3 * tileSize;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        ComplexNumber z0 = new ComplexNumber(0, 0);
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                // Construct a complex number from the pixel coordinates
                float xPos = (x + 0.5f - 2 * tileSize) / tileSize;
                float yPos = (y + 0.5f - tileSize) / tileSize;
                ComplexNumber c = new ComplexNumber(xPos, yPos);

                // Check the Mandelbrot condition for this complex number
                int mb = mandelbrot(c, z0, 0, maxRecurse);

                // Translate the result to number in a reasonable range and use it as color.
                double mbl = mb > 0 ? Math.log(mb) / Math.log(maxRecurse) : 0;
                image.setRGB(x, y, (int) (mbl * 255));
            }
        }

        // Save the image as PNG
        String OS = System.getProperty("os.name").toLowerCase(); // different for win and unix
        String filePath = System.getProperty("user.dir") + (OS.indexOf("win") >= 0 ? "\\" : "/") + "mandelbrot.png";
        System.out.println("Writing mandelbrot image to: " + filePath);
        ImageIO.write(image, "png", new File(filePath));
    }

    public static void main(String[] args) throws IOException {

        createMandelbrotImage(500, 2 ^ 24);

    }
}

The problem is that this code always outputs a black empty image, and I don't seem to find the error.
Comment: During debugging are you seeing the values you think you should?
Comment: Are you starting with a black empty image or are you drawing a black empty image?
Comment: I am not sure which the correct values are, but I am not seeing anything that looks like correct
Comment: I am starting with the black empty image and drawing pixels on it
Comment: `z0` always contains `0+0i`.  Was that your intent?
Comment: @VGR Setting z0 to 0+0i is perfectly valid. If you set z0 to c, the whole computation is just one iteration ahead: z0 = c → z1 = c² + c or z0 = 0 → z1 = 0² + c → z2 = c² + c.
Answer: It looks like your recursive mandelbrot function has an incorrect termination condition.
You want the mandelbrot function to return, when either

the absolute value of z exceeds 2 or
the maximum recursion depth is reached.

Also, you are never incrementing i.
So the updated function would look something like:
public static int mandelbrot(ComplexNumber c, ComplexNumber z, int i, int n) {
    if (i >= n) {
        // mandelbrot function does not diverge after n iterations.
        // Returning -1 as a magic value to indicate that the point c is in the mandelbrot set.
        // Values may already be outside of the mandelbrot set in the 0th iteration, so returning -1 makes more sense.
        return -1;
    } else if (z.abs() >= 2.0) {
        // mandelbrot function is diverging after i iterations.
        return i;
    } else {
        // recursively call mandelbrot function with an updated z and an incremented i.
        return mandelbrot(c, z.squared().add(c), i + 1, n);
    }
}

Finally, if you choose to return -1 for a point inside the mandelbrot set, you have to update your color computation to set these points to black.
int mb = mandelbrot(c, z0, 0, maxRecurse);

if (mb == -1) {
    image.setRGB(x, y, 0);
} else {
    // set the color of your image as usual
}


Exchange 2019 IIS trying to connect to the wrong Server

Question: The server is ASI-EX01 but exchange keeps trying to connect to to ASI-EX1
Comment: Has the server been renamed?
Comment: There was EX1 with a install of Exchange but the changed to EX01 with an install of Exchange trying to remove EX1.
Answer: According to your error message in the EMS, I found a thread Get-OwaVirtualDirectory failed with error "The task wasn't able to connect to IIS on the server" about the similar issue on the OWAVirtualDirecotry, you could try to change the Physical Path of PowerShell Virtual Directory from " %ExchangeInstallPath%\FrontEnd\HttpProxy\PowerShell " to " %ExchangeInstallPath%\ClientAccess\PowerShell " in the IIS of your CAS Server:

 Then please restart IIS by clicking the "Restart" button and wait a while to check whether the issue still exists:

Comment: I made the change and its still saying the same thing.
Answer: Did you encounter the same issue when you run the commands of other Virtual Directories? Were there any issues when you login EAC or OWA?
Comment: The other server was deleted so I cant access it


Could not find solver for: http-01 when set up docker registry with lets encrypt?


Greatest number of own goals in Europe

Question: Which player has scored the greatest number of own goals in the top five European Leagues (as measured by UEFA coefficient: La Liga, Serie A, Premier League, Bundesliga, Ligue 1)?
Answer: For the Premier League it is Richard Dunne Source
For the Bundesliga there are two players who are tied: Manfred Kaltz & Nikolce Noveski Source from the Bundesliga Website
For La Liga the top own goal scorer is Fernando Caceres La Liga Source
In Serie A there are two players who are tied with 8 own goals: Riccardo Ferrari and Franco Baresi Source for Serie A
In Ligue 1 there are a couple of players who are tied for being #1 in own goals. Here are some: Aly Cissokho, Anthony Weber, Damien Da Silva all with 4 own goals. Source for Ligue 1
If you are looking who the Top Own goal scorer is between these 5 leagues, it would be Richard Dunne with 10 own goals.
Comment: It would be helpful if you also mentioned how many own golas scored every player you named.

Greatest number of own goals in Europe


Simple Javascript "or" statement?

Question: For an assignment in class we're tasked with getting user input using the prompt(). I only want the prompt to accept 1 of 3 values.
Here is my code:
ounce = prompt ( "What size would you like your drink?\n8oz, 12oz, 16oz are the available sizes." );

    while ( ounce!= "8oz" || ounce != "12oz" || ounce != "16oz")
{
        alert ( "Please select a proper size: 8oz, 12oz, 16oz" );
        prompt ( "What size would you like your drink?\n8oz, 12oz, 16oz are the available sizes." );
}

My intention is that when the user enters anything else but 8oz, 12oz, or 16oz it will tell them that that size is not available and them prompt them asking for their size again until they enter in one of those values. However my code as it stands is not working. Even if I enter in 8oz it says that is incorrect and asks me for my size again. I am a beginner in a beginner level course as you can tell so any help is appreciated.
Comment: || means it's true if it meets ANY of those conditions. It can't equal all three at once, right?
Comment: Try `&&` instead of `||`. Also, you're not resetting the `ounce` variable on the second call to `prompt`.
Answer: You need to use AND condition... you need to enter the loop only if the entered value is not one of the three, if you use OR then even if you enter a valid value two of the comparison operation will  be turn out to be true... like if you enter 8oz then both ounce != "12oz" and ounce != "16oz" will be true.. since OR operation will return true of any one of the condition turn out to be true it will enter the loop.
If you use AND condition then the loop will be executed only if all the three conditions are met, so if you enter a valid value like 12oz then the condition ounce != "12oz" will return false resulting in the overall condition to fail thus exiting the loop.
ounce = prompt ( "What size would you like your drink?\n8oz, 12oz, 16oz are the available sizes." );

while ( ounce!= "8oz" && ounce != "12oz" && ounce != "16oz")
{
        alert ( "Please select a proper size: 8oz, 12oz, 16oz" );
        ounce  = prompt ( "What size would you like your drink?\n8oz, 12oz, 16oz are the available sizes." );
}

Demo: Fiddle
Comment: You also need to set `ounce` in the second prompt.
Comment: Would you mind explaining the logic behind using the AND?
I read it as:
"While ounce does not equal 8oz and ounce does not equal 12oz and ounce does not equal 16oz"
It works, but if ounce is equal to 8oz, how can it then also be equal to 12oz and 16oz.
Comment: @user3068364 just added an example
Answer: The simple answer is to use AND instead of OR but I think it's worth to explain why that is.
What you're seeing here is an application of De Morgan's theorem which states:
!(A && B) === !A || !B

!(A || B) === !A && !B

So, if you do:
ounce!= "8oz" || ounce != "12oz" || ounce != "16oz"

what you're saying is:
! ( ounce == "8oz" && ounce == "12oz" && ounce == "16oz" )

which is never true because ounce can not be "8oz" and "12oz" and "16oz" all at the same time.
What I believe you want instead is:
! ( ounce == "8oz" || ounce == "12oz" || ounce == "16oz" )

which when we apply De Morgan's transformation we get:
ounce != "8oz" && ounce != "12oz" && ounce != "16oz"

Answer: As a side note, this is a perfect situation for a do-while.
var ounce = undefined;

do {
    alert("Please select a proper size: 8oz, 12oz, 16oz");
    ounce = prompt("What size would you like your drink?\n8oz, 12oz, 16oz are the available sizes.");
} while ( ounce != "8oz" && ounce != "12oz" && ounce != "16oz");

Simple Javascript "or" statement?


Rule for capturing SYN-scanning

Question: I need to write a rule that captures the SYN-scanning.
I tried this: alert tcp any any -> any any (flags:S,12; msg:"SYN"; sid: 1231213;)
then try to scan: nmap -sS myIP but this does not output "SYN"
How to write a correct rule? Thanks.
Comment: Why? Just write what I'm doing wrong
Comment: For one, this isn't a programming question and probably belongs on superuser.  For another, what exactly is the use case for this? responding to a SYN flood? nmapping every address that sends you a SYN will do nothing but bake your connection more in that case, and your ISP will probably see you port scanning hundreds of IPs and knock you offline.  That's implying the source address isn't spoofed anyway, which it frequently is.  Also, if you're behind a router you won't see SYN flood traffic at all, and the only SYNs you get will be from legitimate sources.
Comment: Nmap and snort running on local computer. I just want print "SYN" to each packet with a flag S.
Answer: Try to change flags:S,12 to flags:S as the Snort manual states:

The reserved bits '1' and '2' have been replaced with 'C' and 'E', respectively, to match RFC 3168, "The Addition of Explicit Congestion Notification (ECN) to IP". The old values of '1' and '2' are still valid for the flag keyword, but are now deprecated.

So 12 will check if the two reserved bits are set which is probably not what you want. Also as I understand the documentation flags:S will match packets with only SYN set which should be correct in your case I guess. If you want to match some flags regardless of other flags you can use *.

Rule for capturing SYN-scanning


Incorrect credentials for pushing to git repository with netbeans8

Question:
I've just upgraded to netbeans 8. I have a git repository on bitbucket.org  when I try to push to it with netbeans 7.4 it works fine. If I close Netbeans 7.4 , open NB8 and try to push to the same repository I get:
Incorrect credentials for repository at bitbucket.org:MYACCOUNT/MYPROJECT.git.

How can I fix this?
Answer: I know this is a bit old but it comes up when I search every time so I'm going to put the fix here for next time.
To fix this edit your PROJECT/.git/config file where PROJECT is the path of your project.
Change the url line under the [remote "origin"] section:
url = https://email@example.com/YOURUSERNAME/REPO.git

Be sure to replace YOURUSERNAME with your bitbucket username and REPO with your bitbucket repository which should have already been there.


Non-revealing maximum

Question: How can a group of people find out their maximum age without revealing any other information to each other?
(Is there a book or web site about such non-revealing algorithms?)
Preferably I'm looking for a solution which works for large (e.g. 64-bit or 1024-bit) age values as well. (Even though using the word age is not intuitive for such large numbers.)
I'm looking for a low-cost pencil-and-paper solution, or a solution in which each pair of people has a secure bidirectional communication channel (i.e. the digital equivalent of: anyone can write any message to a sheet of paper, fold it, and pass it to anyone else). I'm not looking for solutions which require building other kind of physical devices.
This a problem belongs to the group of secure multi-party computation.
Yao's Millionaires' Problem is similar but different problem. The linked article also contains its solution.
Comment: The solution suggested by Kundor can be easily employed using pencil-and-paper, specifically a single pencil and two sheets of paper, one of which is ruled, particularly assuming that all participants are honest. Just have people mark their age on the ruled paper, sliding the other sheet sideways over their marks, and after the last person does her mark, just lower the paper until the first mark appears. There is one problem though: it will reveal *how many* people have the maximal age.
Comment: Does the "revealing any other information to each other" mean that "one person alone cannot figure out the maximum age", or "if all but one person cooperate, they still cannot figure out the maximum age"?
Comment: @HenrySwanson: "one person alone" would be good enough for me, but "all but one person cooperate" sounds more interesting. So if you have a solution for either, I'm interested.
Comment: @tomasz: Great adaptation: cheap and simple, thanks! I'm more interested now in a solution with a digital equivalent (see in the question).
Answer: Construct a device in which participants insert pegs at a height corresponding to their age.  Participants take turns entering a closed room with the device.  The peg is inserted through an aperture which only allows access to one column of peg holes.  After inserting the peg, the participant rotates the aperture to the next column.  Construct the device with ratchets such that the aperture can only advance, and can only go around once, never coming back to the first column (this is a one-use-only device.)  Then the participant leaves the room and the next takes his turn.
After everyone is done, the lid of the device is lowered as far as it will go.  Its height corresponds to the maximum age of the group.
Afterwards, destroy the device.  (Or put in a reset button which ejects all the pegs and resets the ratchet.)
If you are worried, make it so that many handles must be used simultaneously to lower the lid, to prevent an untrustworthy participant from lowering the lid prematurely to discover the maximum age so far.
Comment: Thank you for the idea. I was looking for a low-cost pencil-and-paper solution. Clarifying the question...
Answer: If the group consists of only 2 people, we can use the solution for Yao's Millionaires' Problem to solve this one. With that solution we can figure out who is older. Then the older person tells his age to the younger person. This doesn't reveal too much information, because for any good protocol the younger person gets to know the age of the other person, because he got to know the maximum age.
If the group size is larger than 2, and we can relax the requirements a bit, then I have a solution protocol. The relaxed requirements are: there is a chairman outside the group, and the group trusts this chairman with some aggregate information about the ages of some people (but they don't trust the chairman with their individual age).
The protocol consists of rounds. In each round at least one group member, who is not of the maximum age, is secretly eliminated. Every group member knows whether he has already been eliminated, but he doesn't know about the status of others. After each round the chairman announces a number, or he announces that the protocol is over. The last number announced is the answer (i.e. the maximum age). Each round goes like this: 1. The group (including eliminated members) and the chairman sit down to a round table in any random order. 2. The chairman picks two large random integers, writes them to a slip of paper, folds it, and passes it to the next person on the right. 3. This step is repeated for each group member. The next person reads the 2 numbers from the slip he has received. If the person is already eliminated, then he copies the numbers to a new slip of paper, folds it, and passes it on. Otherwise he picks a random positive integer coefficient, and adds his age multiplied by the coefficient to the first number, and adds the coefficient to the second number, writes the resulting two numbers to a new slip of paper, folds it, and passes it on. 4. The chairman receives the final slip, subtracts his own original random numbers, and divides the first result by the second result. The resulting ratio is a weighted average of the ages of the non-eliminated group members. 5. The chairman announces this weighted average, and declares that everybody not older than that is now eliminated. (This eliminates at least one person, the youngest of the non-eliminated ones.) 6. This is the end of the round. The protocol ends when the chairman has to divide by zero in step 4. The answer is the ratio he computed (and announced) in the previous round.
Having a chairman is indeed necessary. For example, if there was no chairman, but the first group member assumed that role (in addition to his normal duties in the protocol), too much information could be revealed. For example, let's assume that there are 3 people in the group, with the first one being the oldest, everybody has a different age, and the division-by-zero happens in the 4th round. In this case the first person can think like this: I got eliminated after the 3rd round, so in each round exactly one person was eliminated. So at the end of the 2nd round a single other person was eliminated. Based on the information I received as the chairman at the end of the 2nd round, I can compute both the coefficient and the age of that other person. I don't know who he is, but I know a non-maximal age value in the group. And that's too much information.

Non-revealing maximum