Erro de PHP com MySQL

Question: Estou com um erro e não entendi porque.
O erro:
Fatal error: Call to a member function fetch_assoc() on boolean
o trecho do erro:
require 'conecta.php';
    $sql = "SELECT `nomep`, `endereco` FROM `cadastropn` WHERE `cidade` = Caxias do Sul";
    $result = mysqli_query($mysqli, $sql);
    while($linha = $result->fetch_assoc()) {
        echo '
' . $linha['nomep'];
        $nome = $linha['nomep'];
        echo '
';
    }

O estranho é que o erro só acontece quando eu coloco o WHEREcidade= Caxias do Sul";
Comment: Ahh, sim agora eu vi o erro e já corrigi. Obrigado amigo!
Comment: Um `if( !$result ) die( mysqly_error( $mysqli ) );` basta para testar erros, mas não use o código em produção. Mais detalhes aqui: http://pt.stackoverflow.com/a/141797/70
Answer: O erro é porque mysqli_query FALSE, por isso no erro aparece BOLEAN (que não é o tipo esperado para fetch_assoc).
A causa é que Caxias do Sul é uma string e tem que está entre aspas. Deveria estar assim: 'Caxias do Sul'.
Altere de:
$sql = "SELECT `nomep`, `endereco` FROM `cadastropn` WHERE `cidade` = Caxias do Sul";

Para:
 $sql = "SELECT `nomep`, `endereco` FROM `cadastropn` WHERE `cidade` = 'Caxias do Sul'";

Erro de PHP com MySQL


Trying to use CDI on Glassfish 4 results in javax.el.PropertyNotFoundException: Target Unreachable, identifier 'indexMB' resolved to null

Question: I am getting an error on a single page, and the only error occurs after I click the SUBMIT button.

javax.el.PropertyNotFoundException: Target Unreachable, identifier 'indexMB' resolved to null

I followed the recommendations of the topic JSF2 form submit " Target Unreachable, identifier 'myModel' resolved to null ONLY on submit but did not help me.
Any help will be very useful.
Follow my setup and my files:

Glassfish 4
Primefaces 3.5
commons-fileupload 1.3
commons-io 2.4

index.xhtml
<f:loadBundle basename="i18n" var="bundle" />
<h:head>
    <title>#{bundle['index_title']}</title>
</h:head>
<h:body>
    #{bundle['index_appname']}

    <h:form id="frmIndex">

    </h:form>
</h:body>

IndexMB.java
@ManagedBean ("indexMB")
@RequestScoped
public class IndexMB {

private String password;
private String user;

public IndexMB() {
}

public String loginTest(){
   ...
}

// getters and setters
}

log (Glassfish)
javax.el.PropertyNotFoundException: /index.xhtml @18,66 value="#{indexMB.user}": Target Unreachable, identifier 'indexMB' resolved to null
    at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:100)
    at org.primefaces.renderkit.InputRenderer.findImplicitConverter(InputRenderer.java:170)
    at org.primefaces.renderkit.InputRenderer.findConverter(InputRenderer.java:190)
    at org.primefaces.renderkit.InputRenderer.getConvertedValue(InputRenderer.java:196)
    at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1046)
    at javax.faces.component.UIInput.validate(UIInput.java:976)
    at javax.faces.component.UIInput.executeValidate(UIInput.java:1249)
    at javax.faces.component.UIInput.processValidators(UIInput.java:712)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    at javax.faces.component.UIForm.processValidators(UIForm.java:253)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
    at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:724)
    Caused by: javax.el.PropertyNotFoundException: Target Unreachable, identifier 'indexMB' resolved to null
    at com.sun.el.parser.AstValue.getTarget(AstValue.java:174)
    at com.sun.el.parser.AstValue.getType(AstValue.java:86)
    at com.sun.el.ValueExpressionImpl.getType(ValueExpressionImpl.java:201)
    at org.jboss.weld.el.WeldValueExpression.getType(WeldValueExpression.java:93)
    at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:98)
    ... 43 more

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">

    <application>
        <locale-config>
            <default-locale>pt_BR</default-locale>
            <supported-locale>en</supported-locale>
            <supported-locale>fr</supported-locale>
        </locale-config>
    </application>
</faces-config>

beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

Comment: I don't see anywhere CDI really comes into play here. That notwithstanding, where are you importing `@ManagedBean` and `@RequestScoped` bean
Answer: Your bean is really not a CDI bean I guess your problem is caused by mixing up the imports. So try
 @javax.inject.Named //defaults to "indexMB"
 @javax.enteprise.context.RequestScoped
 public class IndexMB {
      //rest of your class here
 }

Comment: I changed "@ManagedBean" by "@Named" and it worked. Thanks!


Ruby Time comparison mayhem and chaos. An unsolvable mystery

Question: Look, here's the thing... There is absolutely no reason why this is not working. However, I've decided to publicly come here and express my discontent and frustration towards this piece of code. For as much as I love Ruby I believe there are things coming past me unseen. Please, take a look at it.
def pull(start_time=10.minutes.ago.utc, end_time=Time.now.utc)
  count = 0
  binding.pry
  while start_time.utc <= end_time.utc do
    count =+ 1
    start_time = (start_time + 1.minute).utc
  end
  p "Count is at #{count}, and start_time is at #{start_time}"
end

I've tried to compare Time objects multiple times and in many different ways but I could never make an incremental loop using this comparison. I've been inside the loop and appended the binding.pry to inspect the values of start_time. It's properly being incremented. But the loop is failing to be making any logical sense.
To experiment, I have also printed a message at the end to check the values of the counter count to see how many times the loop is going through. It stops after the first round. Immediately after start_time gets assigned a new value inside the loop. This is the only message I have from calling this method.
"Count is at 1, and start_time is at 2020-01-26 17:49:37 UTC"

I look forward to hearing suggestions about something unseen and escaping me. Because I came from Rails I admit I'm not entirely sure about all Ruby's default libraries and how to use them.
By the way, to run this code you will have to require these:
require 'active_support/core_ext/numeric'
require 'pry'

Comment: I understand your frustration. The thing is, there's *always* a reason when some code doesn't work as expected. It might be very complex or surprising, it doesn't mean there's no reason, though. Keep on looking!
Comment: BTW, what do you want to calculate, exactly? What's your goal?
Comment: Thanks, Eric. This is a pull method in a sophisticated script to fetch roughly 500K records daily. I am not a developer and I had to code this all by myself because this applies to Trading and Finance. All of these records are used to create signals and eventually open trading positions. The reason for the while loop is that requests are limited to 1K records at a time.
Comment: I don't think you should reinvent the wheel and write your own scheduler, then. https://github.com/javan/whenever, https://github.com/collectiveidea/delayed_job or https://itnext.io/sidekiq-overview-and-how-to-deploy-it-to-heroku-b8811fea9347 might be able to help you.
Answer: You're doing count =+ 1, not count += 1 like you intended.
Here's the corrected version:
def pull(start_time=10.minutes.ago.utc, end_time=Time.now.utc)
  count = 0
  while start_time.utc <= end_time.utc do
    count += 1
    start_time = (start_time + 1.minute).utc
  end
  p "Count is at #{count}, and start_time is at #{start_time}"
end

Output with corrected version:
=> "Count is at 11, and start_time is at 2020-01-26 18:41:22 UTC"

Comment: Correct. `count =+ 1` means `count = +1` to Ruby. Mistyping the `+=` shorthand strikes once again.
Answer: It might not be a full answer but I think it could prevent you from having yet another headache:
def pull(start_time=10.minutes.ago, end_time=Time.now)

This line looks simple enough but there's a problem lurking: When no argument is sent, start_time will be initialized to 10.minutes.ago and end_time will be initialized to Time.now.
The problem is that end_time will be initialized a few microseconds after start_time, so the difference between both will be 10 minutes + a few microseconds, which is strictly longer than 10 minutes:
 10.minutes.ago - Time.now
 => -600.000279946

In the other direction, it would be a bit shorter than 10 minutes:
Time.now - 10.minutes.ago
# => 599.999981608

You might want to divide by 60 and round to avoid this problem:
(Time.now - 10.minutes.ago) / 60
#=> 9.99999967125
((Time.now - 10.minutes.ago) / 60).round
#=> 10

Comment: Eh. What's a few spare microseconds here or there? :-)
Comment: @Stefan: It could work. What OP really needs is some kind of background processing, e.g. with ActiveJob & Sidekiq
Comment: Instead of rounding, you could set the default argument values to `nil` and conditionally assign the correct values within the method.
Comment: @Stefan: I'm not sure I understand your point. What are the correct values? Do you mean you want to define `now` first and then define `start_time` as `now - 600`?
Comment: @EricDuminil something like that, yes. "Correct" is having both values exactly 10 minutes apart.
Comment: Or maybe `def pull(start_time=nil, end_time=Time.now)` and then `start_time ||= 10.minutes.before(end_time)`.


If data is square rooted to assume normality, should the data used to test with Levene's Test for Equality of Variance also be square rooted?

Question: I am going to run a MANOVA, two of the assumptions are normally distributed data and equal variances.
I had a data set that non-normally distributed. I square rooted it, and it is approximately normally distributed now. The data set is 155 data points/rows long.
Considering I square rooted data for normality testing, should I keep the data in square root format to test for Equality of Variance (Levene's Test), or revert back to the raw data?
Answer: If you do the equality of variance test for the purposes of assumptions of manova, you need to test the data on the scale you will use in the manova.
Presumably (after what you told us) that is the square root scale.


What's the relationship between Banach space and inner product space

Question: I know that Banach space is a special Hilbert space. Inner product space is a special normed space. Hilbert space is a complete inner product space. Banach space is a complete normed space. I'm wondering what is the relationship between Banach space and inner product space.
Answer: A Banach space is a complete metric space, so that it has a distance function $d(x,y)$ and every Cauchy sequence converges to an element of the space.
A Hilbert space is a complete vector space, with an inner product $<x,y>$ or $x \cdot y$, that defines angles:
$$
cos(\theta) = \dfrac{\langle x,y\rangle}{||x|| ||y||}
$$
which defines the norm as
$$
||x|| = \sqrt{\langle x,x\rangle}.
$$
and distance as
$$
||x-y|| = \sqrt{\langle x-y,x-y \rangle}.
$$
So in a Banach space, you can talk about distance and convergence but not direction, while a Hilbert space has all of those. You need a Hilbert space for generalizing things like orthogonality, characterizing solutions to minimum distance problems (by way of the parallelogram equality), projection for statistics like OLS, and often useful results in approximation.
For example, consider the difference between $\mathbb{R}^N$ with the norm
$$
||x|| = \sup_{i} |x_i|
$$
and the Euclidean norm
$$
||x|| = \sqrt{\sum_{i=1}^N x_i^2} = \sqrt{x\cdot x}.
$$
You can think of the first as a Banach space but not a Hilbert space, and the second as a Hilbert space.  Imagine what you lose by analyzing $\mathbb{R}^N$ without angles.
Comment: They seem to understand the difference between Hilbert and Banach spaces. Their specific question was regarding the relationship between general inner product spaces and Banach spaces.
Answer: Every inner product induces a norm, so an inner product space is a normed vector space. Banach spaces are complete, normed vector spaces. So, the relation between inner product spaces and Banach spaces is that they're both normed vector spaces.
However, (1) an inner product space might lack the completeness that a Banach space possesses and (2) a Banach space norm need not be induced by an inner product. The norm needs to satisfy the parallelogram law for this to be the case (see https://en.wikipedia.org/wiki/Parallelogram_law#Normed_vector_spaces_satisfying_the_parallelogram_law).
Comment: Can we say that there is an intersection between Banach space and inner product space, and Hilbert space is in that intersection?
Comment: Sure! $\ \ \ \ \ $


Why is my pie chart showing multiple labels and incorrect count?

Question: Background
I have a site where users can submit change requests. I created a custom content type "Change Request" which has numerous fields in it, some of which I want to generate charts for.
One of these fields is a list called "urgency" which includes the options "Low", "Medium" and "High". Only one option can be selected per change request.
Goal
I created 4 change requests with sample data which I am using to generate a chart. My goal is to create a pie chart that shows the number of change requests that falls under each urgency level.
Issue
I am experiencing two related issues which I believe are stemming from an issue with my aggregation settings. First, the labels are being duplicated, and second, those duplicated values are being counted and charted separately instead of being combined into one item on the chart.
For example, I have 2 change requests that are "Low" urgency, and the other two change requests are "Medium" and "High" respectively. Instead of having this reflected in the pie chart, it is showing "Low" as two separate labels, and both of them has a count of 1. These should be instead combined into a single label with a count of 2. I understand that I need to aggregate the results, but I am struggling to achieve this.

Setup

I created a new view called "Overview".
The view settings are set to show Content of type "change requests".
I enabled create a page and set it to display a chart of fields.
I enabled Advanced > Other > Use aggregation on the display.
I added the Urgency field to be used as a label.
I added the Urgency field a second time to be used as data. For this, I attempted multiple aggregation functions listed below in attempts. This is the same urgency field, but I am using it once for labels, and again to count the number of requests for each value in the field.
I clicked Format > Chart > Settings and set my label and data fields to match the above fields.

Attempts
First Attempt: Using Field Count Formatter

I tried using the Field Count Formatter module at first, but I discovered that this was not counting the amount of content with that field, but is rather counting the number of items in the field. This resulted in a count of 1 for each urgency even if there was multiple change requests with one of the urgencies.

Second Attempt: Using aggregation settings

For the duplicate labels, I set the aggregation type to "Group results together" and set the Group Column to "Value". My thoughts were that it would group the duplicate values together but this didn't do anything.

For the counts being separate for the duplicate values, I set the aggregation type to "Count" but this didn't seem to do anything. I also attempted "Count Distinct". I also attempted to use grouping settings.

More Info

Drupal 10
Module: https://www.drupal.org/project/charts
I'm using Charts with views integration, not programmatically
I read Charts documentation but it is limited and doesn't touch on aggregation
I looked for aggregation documentation but I couldn't find anything that helped
Charting Library: Highcharts
Answer: As per this question:

The problem turned out to be a Sort Criteria that was added by default to the view. The default "Sort by: authored by" caused issues with the aggregation and duplicated labels, but the issue was resolved as soon as this option was removed.


Como validar uma regra regex para uma citação de usuario?

Question: Estou fazendo um funcionalidade no meu site para citar usuários usando @:
@bananinha disse aquilo

No caso o nome @bananinha vai se transforma em um link quando a pessoa submeter o comentário. Consigo fazer com um monte de if essa validação porém vi que com regex o código fica mais clean.
No caso estou fazendo com regex porém não estou conseguindo pegar todas os casos.
As regras que precisa atender é:

O primeiro caractere deve ser @
O restante dos caracteres devem ser A-Z, a-z, . , ou , _. E deve conter pelo menos un caractere.
O caractere @ deve aparecer apenas uma única vez.

O que tenho até agora é essa regra:

function validNickname(str) {
    var pattern = new RegExp('[@][A-Za-z0-9._]','i');
    return !!pattern.test(str);
  }

  function getMention(str) {
    var words = str.split(' ');

    for (var i = 0 ; i < words.length ; i++) {
      console.log(words[i], validNickname(words[i]));
    }
  }

  t = '@ @@@@ @bananinha oloco@meu cachorrinho@ @nick_fury @pik4chu @$$money_ @estou_entre_arrobas@ @estou_entre_arrobas@eu_tambem@'

  getMention(t);

Porém tem alguns casos que não estou conseguindo validar, como primeira e única ocorrência do @.
Answer: Basta trocar para:

function validNickname(str) {
    let pattern = /^@[A-Za-z0-9._]+$/;
    return pattern.test(str);
}

function getMention(str) {
    str.split(' ')
       .forEach(word => console.log(word, validNickname(word)));
}

let t = '@ @@@@ @bananinha oloco@meu cachorrinho@ @nick_fury @pik4chu @$$money_ @estou_entre_arrobas@ @estou_entre_arrobas@eu_tambem@';

getMention(t);

Os marcadores ^ e $ são respectivamente o início e fim da string. Assim você garante que a regex vai verificar todo o conteúdo da string, além de deixar claro que a @ só pode estar no início.
O trecho [A-Za-z0-9._] é uma classe de caracteres, que corresponde a qualquer letra de A a Z (maiúsculas ou minúsculas), dígitos de 0 a 9, ponto ou _. O detalhe é que toda essa expressão corresponde a apenas um caractere. Ou seja, a sua regex só verificava se tinha um caractere depois da @, desconsiderando o restante da string.
Para considerar mais de um caractere, usei o quantificador + (uma ou mais ocorrências), para indicar que as letras, ponto e _ podem se repetir várias vezes. E o $ garante que só pode ter esses caracteres até o final da string.
Repare que a flag i não é necessária. Ela indica que a regex deve ser case insensitive, mas como você já usou A-Za-z, a regex já vai considerar tanto as letras maiúsculas quanto as minúsculas.
Também troquei [@] por apenas @, já que os colchetes não fazem diferença nesse caso (ambas as expressões são equivalentes).
Por fim, o método test já retorna um booleano, não precisa fazer !! no retorno do método.

Outra opção é usar:

let pattern = /^@[\w.]+$/;

let t = '@ @@@@ @bananinha oloco@meu cachorrinho@ @nick_fury @pik4chu @$$money_ @estou_entre_arrobas@ @estou_entre_arrobas@eu_tambem@';

t.split(' ').forEach(word => console.log(word, pattern.test(word)));

Pois o atalho \w já considera as letras, números o o caractere _.

Vale lembrar que essas regex são "ingênuas", pois aceitam strings como @_._..., por exemplo (pois todos os caracteres contidos em [A-Za-z0-9._] podem se repetir várias vezes - veja):

let pattern = /^@[\w.]+$/;

let t = '@__._... @___abc.123....';

t.split(' ').forEach(word => console.log(word, pattern.test(word)));

Se quiser ser mais específico, a regex fica um pouco mais complicada. Por exemplo, se o critério for que ponto e o _ não podem aparecer mais de uma vez seguida (@abc.123 pode, mas @abc..123 e @abc._123 não), uma opção seria:

let pattern = /^@[A-Za-z0-9]+([._][A-Za-z0-9]+)*$/;

let t = '@__._... @___abc.123.... @abc.123_xyz @abc._123';

t.split(' ').forEach(word => console.log(word, pattern.test(word)));

Repare que agora a classe de caracteres [A-Za-z0-9] só tem as letras e números. Em seguida, há um trecho contendo [._] (um ponto ou _) seguido de uma ou mais letras/dígitos. Esse trecho final está agrupado entre parênteses, e o quantificador * indica que ele pode se repetir zero ou mais vezes. Ou seja, a sequência "ponto ou _, seguido de letras/dígitos" pode se repetir várias vezes (para casos como @abc.123_xyz), ou nenhuma (para os casos como @abc123).
Enfim, regex é assim mesmo: quanto mais específica e quanto mais casos quiser tratar, mais complexa ela vai ficando. Cabe a você escolher até onde ir (se você sabe que nunca terão casos como @abc....123, por exemplo, pode usar a primeira versão mesmo).


How to run a php script, only if X page redirects you to it

Question: If (If X Page redirect me here)
{
run this code
}
else
{
run this code
}

What to write in IF condition? What is the PHP Code?
Comment: What you have tried till yet?
Comment: I am newbie, I do not know the code.
Comment: in your x page html a     and in y page php  if(isset($_GET['from_page']) && $_GET['from_page']=='x'){ echo "run this code "; }else { echo " run this coe "; }
Comment: From you `X` page send some parameters via `GET` or `POST` then in your if section check for the presence of that parameter, if its present then run the code you want, or else code
Comment: [check referer with php](http://stackoverflow.com/q/1864583/6521116)
Answer: Try $_SERVER variable
<?php
echo '
';
print_r($_SERVER);
?>

Output (on phpfiddle.org)
Array
(
    [DOCUMENT_ROOT] => /home/xfiddlec/public_html/main
    [EE_HOST] => main.xfiddle.com
    [EE_LIB] => /home/xfiddlec/public_html/main/inclibs/
    [EE_LIB_PREFIX] => /home/xfiddlec/public_html/main/inclibs/
    [EE_ROOT] => /home/xfiddlec/public_html/main/
    [GATEWAY_INTERFACE] => CGI/1.1
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.5
    [HTTP_CONNECTION] => close
    [HTTP_HOST] => main.xfiddle.com
    [HTTP_REFERER] => http://phpfiddle.org/
    [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
    [HTTP_USER_AGENT] => Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
    [HTTP_X_FORWARDED_FOR] => 220.127.116.11
    [HTTP_X_REAL_IP] => 18.104.22.168
    [PATH] => /bin:/usr/bin
    [PHPRC] => /home/xfiddlec/config
    [PROXY_ADDR] => 184.108.40.206
    [QUERY_STRING] =>
    [REDIRECT_STATUS] => 200
    [REMOTE_ADDR] => 220.127.116.11
    [REMOTE_PORT] => 56471
    [REQUEST_METHOD] => GET
    [REQUEST_URI] => /code_45646358.php
    [SCRIPT_FILENAME] => /home/xfiddlec/public_html/main/code_45646358.php
    [SCRIPT_NAME] => /code_45646358.php
    [SERVER_ADDR] => 18.104.22.168
    [SERVER_ADMIN] => email@example.com
    [SERVER_NAME] => main.xfiddle.com
    [SERVER_PORT] => 80
    [SERVER_PROTOCOL] => HTTP/1.0
    [SERVER_SIGNATURE] =>
Apache Server at main.xfiddle.com Port 80

    [SERVER_SOFTWARE] => Apache
    [SITE_WEBMASTER] => PhpFiddle Webmaster
    [SITE_WEBMASTER_URI] => mailto:firstname.lastname@example.com
    [TZ] => America/New_York
    [UNIQUE_ID] => WRaD3x8WBGYADWv4OMgAAAAN
    [PHP_SELF] => /code_45646358.php
    [REQUEST_TIME_FLOAT] => 1494647775.2
    [REQUEST_TIME] => 1494647775
    [argv] => Array
        (
        )

    [argc] => 0
)

You can use following value in if condition
if ( $_SERVER[HTTP_REFERER] == "some thing" ) {

    // do my job
} else {
    // do another job

}

Or You can pass some GET/POST parameters and check their existence in php page.
Answer: In your X page
If you navigating using anchor html
y page
(or)
If your redirecting using php header()
header('Location:y.php?from_page=x');

In Y page
php
if(isset($_GET['from_page']) && $_GET['from_page']=='x')
{
  echo "run this code ";
}
else
{
   echo " run this coe ";
}

Answer: you can use $_SERVER['HTTP_REFERER'] to get the request referer. Refer to this post for get referer.
if ($_SERVER['HTTP_REFERER'] = "X page path")
{
  //run this code
}
else
{
  //run this code
}


Hidden Markov Model to predict the next state

Question: I am learning to use HMM and I am trying to solve the following problem. There is a robot moving around the nodes in graph. The robot can move to adjacent nodes with  certain probabilities. Each time the robot steps into a new "node", a (noisy) information about the node is generated. That is, I do not know the exact node.
I have the following data:

Each node node is a hidden state (finite number)
A transition matrix that defines the probabilies for the transitions between nodes. $A$
Emission probabilities for each hidden node

Using HMM standard functions I should be able to predict the "hidden state" at time t if I have "t observations" (observations from $1,\dots,t$) $P(X_t|O_{1,\dots,t})$.
Is there a way to predict the next move (hidden state at t+1)? If I have "$t$-observations" (all observations at time $t$), is it possible to predict the most probable "hidden state" at time "$t+1$"?
Which HMM principle should I use?
Comment: To get P(t+1) simply multiply your distribution over the hidden states at time t by the transition probabilities.
Comment: Rabiner's review paper on HHMs is an amazing source for starting to work with HMMs. All the important algorithms are described (forward algo, backward algo, and EM algo) Take a look (http://www.cs.cornell.edu/Courses/cs4758/2012sp/materials/hmm_paper_rabiner.pdf)
Comment: My current interest is same kind of HMM model. I will not give detailed explanation, because there is a better alternative. I have learned whatever I know thanks to this paper:
http://www1.se.cuhk.edu.hk/~hcheng/paper/sdm2013.pdf Especially focus on section 3.2 (3.2.1 and 3.2.2).
Answer: You use the forward algorithm to predict $P(X_{t+1})$.
$P(X_{t+1}|X_t, Y_{1:t} ) = \sum_{X} P(X_{t+1}|X_t) \cdot P(X_t|Y_{1:t}) $
So, you use the same principle for predicting $P(X_{t})$, but without being able to incorporate $Y_{t+1}$, since it is not observed yet.
Comment: How would we calculate P(Xt|Y1:t) ? it is opposite of emission probabilities. I have P(Y(t)/X(t)) which is emission probabilities.
Answer: To get the probability over hidden states at t_2, just multiply your posterior over t_1 by your transition matrix.
https://stackoverflow.com/questions/15554923/how-to-perform-a-prediction-with-matlabs-hidden-markov-model-statistics-toolbo


plotting number range in a correlation matrix with colorbar with rectangular tiles [matshow (matplotlib)]

Question: I am trying to plot a correlation matrix with values shows in plot. Instead of a single value of correlation coefficient, I want a range on the tiles (confidence interval). To achieve this I am first plotting the matrix with a colorbar using matshow and individual writing values of low and high intervals on the plot using centering option. Here is the snippet of that code.
cax = ax.matshow(data, interpolation='nearest', cmap=GnRd, vmin=-1, vmax=1 ,alpha=1 )
fig.colorbar(cax, ticks=[-1,0,1], shrink=0.8)
for (i, j), z in np.ndenumerate(data2):
  if i>=j and z > -0.5 and z < 1:
     ax.text(j, i, '{:0.2f}'.format(z), ha='left', va='center', size=28, color='black', **hfont)
  if z < -0.5 :
     ax.text(j, i, '{:0.2f}'.format(z), ha='left', va='center', size=28, color='black', fontweight='bold', **hfont)
  if z == 1 :
     ax.text(j, i, '{:0.2f}'.format(z), ha='center', va='center', size=28, color='black', fontweight='bold', **hfont)
for (i, j), z in np.ndenumerate(data3):
  if i>=j and z > -0.5 and z <1:
     ax.text(j, i, '{:0.2f}'.format(z), ha='right', va='center', size=28, color='black', **hfont)
  if z < -0.5 :
     ax.text(j, i, '{:0.2f}'.format(z), ha='right', va='center', size=28, color='black', fontweight='bold', **hfont)

plt.show()

and here is my  plot :

The problem with this plot is coloring in the tiles  is not correct and I am not sure how to color the tiles for a range. Also, there is a wasted space on the tiles which can be reduced by making titles rectangular but I believe matshow doesn't that option. I found a few work around based on object drawing, which will probably make my life  more complicated. Any help will be appreciated.
Answer: I came up with an answer for my query. I changed my aspect='auto' and tiles became retangular for the other issue colorbar issue, I decided to simply use the average of these number for the plotting  :
cax = ax.matshow(data, interpolation='nearest', cmap=GnRd, vmin=-1, vmax=1 ,alpha=1, aspect='auto' )
fig.colorbar(cax, ticks=[-1,0,1], shrink=0.8)
for (i, j), z in np.ndenumerate(data2):
   if i>=j and z > -0.5 and z < 1:
      ax.text(j, i, '{:0.2f}'.format(z), ha='left', va='center', size=28, color='black', **hfont)
   if z < -0.5 :
      ax.text(j, i, '{:0.2f}'.format(z), ha='left', va='center', size=28, color='black', fontweight='bold', **hfont)
    if z == 1 :
      ax.text(j, i, '{:0.2f}'.format(z), ha='center', va='center', size=28, color='black', fontweight='bold', **hfont)
for (i, j), z in np.ndenumerate(data3):
     if i>=j and z > -0.5 and z <1:
       ax.text(j, i, '{:0.2f}'.format(z), ha='right', va='center', size=28, color='black', **hfont)
     if z < -0.5 :
       ax.text(j, i, '{:0.2f}'.format(z), ha='right', va='center', size=28, color='black', fontweight='bold', **hfont)

plt.show()


Javafx - How to Add Pie Chart to BorderPane from Different Class

Question: I have two classes. A Main class and a Chart class. My Chart class extends PieChart and instantiates a Pie Chart in its constructor. My main class creates a BorderPane, I then instantiate an object of the Chart class(creating the Pie Chart) and add it to the center pane.The only problem is I don't know the exact syntax to make this work properly, specifically in the constructor of my Chart class.
I know that for example, if I was creating an HBox instead of a Pie Chart in the constructor, I could simply use this. and a number of methods. But Pie Charts have additional elements with Observable Lists so i'm not sure how to make this work? Here are my two classes below. Please help. Thank you.
MAIN CLASS
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
    BorderPane border = new BorderPane();

    Chart chart = new Chart();

    border.setCenter(chart);

    Scene scene = new Scene (border, 640,680);
    primaryStage.setScene(scene);
    primaryStage.show();

}
public static void main(String[] args) {
    launch(args);
}}

CHART CLASS
public class Chart extends PieChart{

public Chart(){
    ObservableList<PieChart.Data>pieChart = FXCollections.observableArrayList(
            new PieChart.Data("Fruits", 75),
            new PieChart.Data("Vegetables", 25)
            );

    PieChart chart = new PieChart(pieChart);

    //What code can create the Pie Chart here? Is the solution to place the chart on it's own pane instead?
}}

Answer: You are probably looking for
public Chart(){
    ObservableList<PieChart.Data>pieChart = FXCollections.observableArrayList(
            new PieChart.Data("Fruits", 75),
            new PieChart.Data("Vegetables", 25)
            );
    setData(pieChart);
    // no need for this -> PieChart chart = new PieChart(pieChart);
}

or
public Chart(){
   super(FXCollections.observableArrayList(
         new PieChart.Data("Fruits", 75),
         new PieChart.Data("Vegetables", 25)
   ));
}

Edit after comment: setData(ObservableList data) is a method from PieChart class. And it will set data objects. It is just easy and convenient way to work with data in chart or any other collection powered view. (Yep, it is not chart-only style. It is pretty much the same for all JavaFX views. Chart will listen for data changes and redraw itself internaly.You just need to set data you'd like to display. In your case you have this method because your Chart extends PieChart
When you do PieChart charts = new PieChart(data); in PieChart it will call setData internaly
public PieChart(ObservableList<PieChart.Data> data){
   setData(data);
   ...
}

So that's why you have to call super(data) or setData(data) yourself in your extended class. But if you want to chage charts, you don't have to recreate whole chart every time. Can just change data with charts.setData(someData) or get data List object with charts.getData() and then change it.
For example:
PieChart charts = new PieChart();
ObservableList<PieChart.Data> pieChart = ...
charts.setData(pieChart);
// pieChart == charts.getData() // this is the same object. so
pineChart.add(new PieChart.Data("New Fruit", 75)) // will change chart

Btw, take a look at this tutorials https://docs.oracle.com/javafx/2/charts/jfxpub-charts.htm
Comment: Yes, that's it! Thank you. If you have a sec, could you explain the setData method. Is this something specific for graphs or used more generally when instantiating javafx controls? Thanks again


How to trace a variable and slice all the code that it touches with Frama-C

Question: Is it possible to trace a variable and slice all the code it touches using Frama-C? For example consider the following program:
#include <stdio.h>

#define SIZE 512

int storage[SIZE];

void insert(int index, int val) {
    storage[index] = val;
}

int main(int argc, char *argv[]) {
    int x = 10;
    int y = 20;
    int z = 30;

    z = 0; /* some change to unrelated var */

    insert(x, y);

    return 0;
}

My expected slice for variable x is:
#include <stdio.h>

#define SIZE 512

int storage[SIZE];

void insert(int index, int val) {
    storage[index] = val;
}

int main(int argc, char *argv[]) {
    int x = 10;
    int y = 20;

    insert(x, y);

    return 0;
}

How can I achieve this? So far, I have tried following frama-c slice_issue.c -no-frama-c-stdlib -kernel-msg-key -slice-value x -then-on 'Slicing export' -print. It generates following slice:
/* Generated by Frama-C */
int main(void)
{
  int __retres;
  int x = 10;
  __retres = 0;
  return __retres;
}

I can get the expected output if I supply -slice-calls insert in slice command. But is there any way to get the same effect without specifying the function names explicitly in the slice commands?
Thanks in advance. Any hints or pointing to the documentation will be appreciated.
Answer: I'm not sure that -slice-calls is doing what you want. According to frama-c -slicing-help:

-slice-calls <f1, ..., fn>  select every calls to functions f1,...,fn, and all their effect.

In other words, you're adding to the slicing criterion any call to insert, regardless of whether one of the arguments is x or not (e.g. if you replace your call with insert(z,y), it will also be kept in the slice.
It seems to me that you're more after -slice-rd x. Quoting again frama-c -slicing-help:

-slice-rd <v1, ..., vn>  select the read accesses to left-values v1,...,vn (addresses are evaluated at the beginning of the function given as entry point)

With that, insert(x,y); is added to the slicing criterion because there's a read access to x, not because it is a call to insert (and insert(z,y) gets discarded as expected).
That said, if you really want to trace all calls to all functions, as with many options that takes a set of functions as parameter, you can do it with -slice-calls @all (see section 3.3.3 of Frama-C's user manual)


Como controlar formulários MDI através de um método geral?

Question: Estou desenvolvendo um sistema com formulários MDI. Tenho um menu que é o MdiParent e todos os demais ficam alocados como seus filhos.
Originalmente, o MDI permitia que eu abrisse o mesmo formulário diversas vezes; então eu passei a controlar a existência dos formulários através de uma declaração estática, dessa forma:
public static Form form1;

Na hora de abrir o formulário:
if (form1 != null)
{
    form1.Activate();
}
else
{
    form1 = new TED_Dados();
    form1.MdiParent = this;
    form1.Show();
}

E finalmente, quando eu fecho o formulário:
Menu.form1 = null;

Esse código é funcional, porém é necessário replicá-lo para todos os formulários, e eu preciso que todos estejam declarados no menu.
Gostaria de saber se há alguma solução que me permita controlar todos os formulários através de uma classe ou método únicos.
Comment: `Menu` é o quê? O form pai (MDI)?
Comment: Conselho que eu te dou para entender mais sobre isso: Crie um MDI à partir do template do Visual Studio, observe o código que é gerado. Já tem muita coisa pronta para trabalhar com os *Child* do MDI.
Answer: Tem várias formas de resolver isso.
Uma abordagem que eu gosto é criar um método genérico para abrir os forms.
Neste caso, o método está no form MDI.
public void OpenForm<TForm>() where TForm : Form, new()
{
    var form = Application.OpenForms.OfType<TForm>().FirstOrDefault();
    if (form != null)
        form.BringToFront();
    else
        new TForm {MdiParent = this}.Show();
}

Veja um GIF do funcionamento:
Comment: Excelente solução, obrigado @LINQ! Seguindo ainda nessa linha, é possível também passar **parâmetros para um construtor** através desse método? Possuo um formulário que serve como cadastro e edição, e para o segundo caso preciso passar um ID. Estou passando um `int?` como parâmetro para a função `OpenForm` mas não consegui diferenciar a exibição do novo formulário para os dois casos.
Comment: @CaioPoschardt Aí vai depender um pouco da sua estruturação de código, se os parâmetros são sempre do mesmo tipo e tal. Sempre tem como fazer =D Se você tentar desenvolver a solução para este novo problema e não conseguir, abra uma nova pergunta para podermos tentar te ajudar


Install AWS SSL Certificate to EC2 instance without load balancer

Question: I'm new with AWS and facing some confusion with ACM SSL certificate installation to an EC2 instance.
Is it possible to install the certificate without using ELB or Cloudfront. I don't need load balancer because the app is running on a single instance.
Do I have any other option to install the AWS SSL cert? If load balaner is the only option, is it possible for a single instance only?
Thanks in advance for your answers
Comment: You appear to be asking about certificates from Amazon Certificate Manager, without actually mentioning it.  Is that what you are referring to?
Answer: Certificates obtained through Amazon Certificate Manager (ACM) can only be installed on Elastic Load Balancers, CloudFront, API Gateway, and other AWS services. They cannot be exported or installed directly onto EC2 instances.
If you want to install an SSL certificate directly on your EC2 instance, you cannot use ACM. Instead, you will need to obtain an SSL certificate through a third-party (such as Lets Encrypt, GoDaddy, ec.) and install it following the instructions for your web server.
It is 100% valid to put an ELB in front of a single EC2 instance, especially for the purpose of letting the ELB manage the SSL certificate.
Other benefits of using ELB in front of your EC2 instance:

You'll gain the protection of AWS Shield (which provides some levels of DDoS protection),
You can replace the EC2 instance or scale out more easily if needed in the future,
The ELB will handle the encryption/decryption of the HTTPS connections (freeing your EC2 instance's CPU to do other work)
Comment: "It is 100% valid to put an ELB in front of a single EC2 instance ..." Yeah but how do you do that, with a long live EC2 instance? All the examples I see ELB are attached to ASG target groups.
Comment: @spinkus EC2 target groups don't have to be associated with an ASG. You can just create one and add your EC2 instance, then point the ELB at that.
Answer: You will have to install the certificate for any server software that you are running on your instance. e.g apache, nginx, tomcat, nodejs. Each of these have their own mechanism for using the certificates. Read their documentation.
Also if you have setup DNS resolution for your instance public ip (make sure you are using elastic IP) then you can use certbot from let's encrypt to automate this process. check https://certbot.eff.org/. It supports multiple environments out of the box. and its free ssl certificates.
Comment: Just note that you'll need a custom domain - https://community.letsencrypt.org/t/policy-forbids-issuing-for-name-on-amazon-ec2-domain/12692/6
Answer: You can use a service like nip.io which acts like on the fly DNS and forwards all requests from <IP>.nip.io to <IP>.
You can then use a service like Caddy to setup TLS certificates.
This is what your configuration will look like if your application is running on port 3000
<EC2 Public IP>.nip.io {
    reverse_proxy localhost:3000
}

Once you run Caddy, you will be able to access the site using the link https://<IP>.nip.io
I wrote an article on this, HTTPS on AWS EC2 without a Load Balancer
Comment: Caddy is a great suggestion as it takes care of the Let's Encrypt provisioning and renewal automatically. Note that you don't need to use `nip.io` here. If you have your own domain (which is the most common case) then you can simply deploy Caddy beside your existing port-80 service and have it reverse-proxy to port-443 with the desired hostname. Set `auto_https disable_redirects` in the global config block to make sure Caddy does not try to bind to port-80.


Prove $X$ and $Y$ are not independent

Question: Let $X$ and $Y$ be two random variables. Their joint probability density function is
$$f: (x, y) \mapsto C(y^2 - x^2)e^{-y} \mathbf{1}_A(x, y)$$
where $C \in \mathbb{R}$, $A = \{(x,y) \in \mathbb{R}, |x| < y \land y > 0\}$
and $\mathbf{1}_A: (x,y) \mapsto 1$ if $(x,y) \in A$ else $0$
How can you prove that $X$ and $Y$ are not independent?
EDIT
We need to prove that $f \neq f_X f_Y$ where
$$f_X = \int_y C(y^2 - x^2)e^{-y}\mathbf{1}_A(x, y)dy$$
$$f_Y = \int_x C(y^2 - x^2)e^{-y}\mathbf{1}_A(x, y)dx$$
How can I prove that?
Comment: Observe that we cannot write $f=f_Xf_Y$ where $f_X$, $f_Y$ are the marginal densities of $X$, $Y$.
Comment: $f_X = \int_y C(y^2 - x^2)e^{-y}\mathbf{1}_A(x, y)dy$, I don't know how to deal with the $\mathbf{1}_A(x,y)$ because it needs to stay but I don't know how to make it depend only on $x$
Answer: Integrating the joint density, we have
\begin{align}
\int\limits_{\mathbb R^2} f&=\int_0^\infty\int_{-y}^y C(y^2-x^2)e^{-y}\ \mathsf dx\ \mathsf dy\\
&= C\int_0^\infty \frac43 y^3 e^{-y}\ \mathsf dy\\
&= 8C,
\end{align}
so $C=\frac18$. To compute the marginal densities, we integrate the joint density. For $x>0$,
$$
f_X(x) = \int_x^\infty \frac18 (y^2-x^2)e^{-y}\ \mathsf dy = \frac14 e^{-x}(1+x),
$$
and for $x<0$,
$$
f_X(x) = \int_{-x}^\infty \frac18 (y^2-x^2)e^{-y}\ \mathsf dy = \frac14 e^{x}(1-x),
$$
so
$$f_X(x) = \frac14 e^x(1-x)\mathsf 1_{(-\infty,0]}(x) + \frac14 e^{-x}(1+x)\mathsf 1_{(0,\infty)}. $$
For $y>0$ we have
$$f_Y(y) = \int_{-y}^y \frac18(y^2-x^2)e^{-y}\ \mathsf dx = \frac16 y^3 e^{-y}. $$
It is clear that $f\ne f_Xf_Y$, so $X$ and $Y$ are not independent.

Prove $X$ and $Y$ are not independent


The drush command 'rets-import' could not be found

Question: I believe I have all the pieces of the Drupal RETS Real Estate Framework installed in my drupal 7 site.
https://www.drupal.org/project/drealty
But when I run:
drush -u=admin -d rets-import

I get:
The drush command 'rets-import' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions.

What step might I have missed in my install of this framework?
Comment: Have you run that commnand form a directory inside your Drupal installation? Have you run the drush cache-clear drush command? Is he module enabled?
Comment: Yes, to all 3 questions.
Answer: The file that integrates DRealty with Drush drealty.drush.inc is kind of in an odd place within a drush folder of the module.
http://cgit.drupalcode.org/drealty/tree/drush/drealty.drush.inc
Drush will scan the root level of a module folder or your .drush directory for drush include files but I dont think it will randomly scan deeply into module directories. I recommend moving this file into your .drush folder and clearing the cache, then trying from your site folder again. Eg,

cp ./drealty/drush/drealty.drush.inc ~/.drush
drush cc drush
cd YOUR_DRUPAL_PROJECT/sites/all/modules
drush -u=admin -d rets-import
Comment: it's not a bug persay. Drush support is optional. Drush's scanning behavior is documented within drush .... if anything it could use a mention in their `README.txt` or `INSTALL.txt`. If you want to open an issue for them on the matter it probably wouldn't be a bad idea.
Comment: This worked thank you very much!   Is this a bug in DRealty module that should be reported?


Is there a Windows equivalent of Unix 'CPU steal time'?

Question: In order to assess performance monitoring accuracy on virtualization platforms, the CPU steal time has become an increasingly relevant metric - see EC2 monitoring: the case of stolen CPU for an instructive summary in the context of Amazon EC2 and IBM's paper on CPU time accounting for a more in-depth technical explanation (including illustrations) of the concept:

Steal time is the percentage of time a virtual CPU waits for a real
  CPU while the hypervisor is servicing another virtual processor.

Accordingly, it is exposed in most related Unix/Linux monitoring tools nowadays - see e.g. columns %steal or st in sar or top:

st  --  Steal Time
  The amount of CPU 'stolen' from this virtual machine by the hypervisor
  for other tasks (such as running another virtual machine).

I've been unable to figure out how to capture the same metric on Windows though, is this possible already? (Ideally for the Windows 2008 Server R2 AMIs on EC2 and via a respective Windows Performance Counters of course.)
Answer: Edit: Updating on Oct. 1 2013 - Some of my original answer has since become obsolete.
I'm not sure if you're still active on this site or that you'll see this, but I wanted you to know that I read this question today and it fascinated me, and so I spent all day (when I should have been working) researching Hyper-V and Windows internals and even digging in to the very concepts of virtualization itself in hopes that I might be ready to answer your question.
Let me preface by saying that I am coming from the point of view of Hyper-V as a virtualization platform because that is where I have the most experience.  Even though there may be certain tenets of virtualization, as we know it, that cannot be deviated from, Microsoft and VMware and Xen all have different strategies for how they design their hypervisors.
That's the first thing that makes your question challenging.  You pose your question as if it were hypervisor-agnostic, when in truth it is not.  Amazon EC2, for example, uses the Xen hypervisor, and the "CPU Steal Time" metric that you see in the output of a top command issued from within a Linux VM running on that hypervisor is a result of the integration services installed on that guest OS (or virtualization-aware tools on the guest) in conjunction with data provided by that specific hypervisor.
First off let me just answer your question straight up: There is no way to see from inside a virtual machine running Windows how much time the processors belonging to the physical machine on which the hypervisor runs spends doing other things, unless the particular virtual tools/services or virtualization-aware tools for your particular hypervisor are installed in the guest VM and the particular hypervisor on which the guest is running exposes that data to the guest.  Even a Windows guest running on a Hyper-V hypervisor will not have immediate access to information regarding the time spent that the physical processors on the hypervisor were doing other things.  (To quote voretaq7, something that "breaks the fourth wall.")  Even though Windows client and server operating systems running as virtualized guests in Hyper-V with the correct integration services/tools installed make use of "enlightenments" (which are literally kernel code alterations made especially for VMs) that significantly increase their performance in using the resources of a physical host, the bottom line is that the hypervisor does not have to give any more information to the guest OS than it wants to.  That means the hypervisor does not have to tell a guest VM what else it is doing besides servicing that VM... unless it wants to.  And that information about what else the physical processors are doing is necessary for deriving a metric from the perspective of the VM such as "CPU Steal Time: the percentage of time the vCPU waits for a physical CPU."
How could the guest OS know that, if it didn't even realize that it was actually virtualized?
In other words, without the right integration tools installed on the guest, the guest OS won't even know that its CPU is actually a vCPU.  It won't even know that there is another force outside of itself "stealing" CPU cycles from it, therefore that metric will not exist on the guest VM.
VMware has begun to expose this data to Windows guests as well as of ESXi 5.0. VMware integration tools also need to be updated on the guest. Here is a reference; they refer to it as "CPU Stolen Time".
A hypervisor such as Hyper-V does not give guests direct access to physical resources such as physical processors or processor cores.  Instead the hypervisor gives them vDevs - virtual devices - such as vCPUs.
A prime example of why: Say a virtual machine guest OS makes the call to flush the TLB (translation look-aside buffer) which is a physical component of a physical CPU.  If the guest OS was allowed to clear the entire TLB on a physical processor, that would have negative performance effects for all the other VMs that were also sharing that same physical TLB.  In the case of Windows, that call in the guest OS is translated into a "hypercall" or "enlightened" call which is interpreted by the hypervisor so that only the section of the TLB that is relevant to that virtual machine is flushed.

(Interestingly, that hints to me that guest VMs that do not have the proper integration tools and/or services could have the ability to impact the performance of all the other VMs on the same host, but that is completely outside the scope of this topic.)

All that to say that you can still detect in a Hyper-V host the time that a virtual processor spent waiting for a real processor to become available so that it could scheduled to run.  But you can only see that data on a Windows Hyper-V hypervisor.  If it is possible to see this in other hypervisors, I urge others to tell us how to see this in that hypervisor and also if it is exposed to the guests.  (Edit 10/1/2013 Thank you evilensky for doing just that!)
My test machine was Hyper-V Server 2012, which is the free edition of Server 2012 that only runs Core and the Hyper-V role.  It's effectively the same as any Windows Server 2012 running Hyper-V.
Fire up Perfmon on your parent partition, aka physical host.  Load this counter:
Hyper-V Hypervisor Virtual Processor\CPU Wait Time Per Dispatch\*

You will notice that there will be an instance of that counter for each virtual machine on that hypervisor, as well as _Total. The Microsoft definition of that Perfmon counter is:

The average time (in nanoseconds) spent waiting for a virtual processor to be dispatched onto a logical processor.

Obviously, you want that number to be as low as possible.  For computers, waiting is almost never a good thing.
Other performance counters on the hypervisor that you will want to investigate are Hyper-V Hypervisor Root Virtual Processor\% Guest Run Time, % Hypervisor Run Time, and % Total Run Time.  These counters provide you with the percentages that could be used to determine facts such as how much time the "real" processors spend doing things other than servicing a VM or all VMs.
So in conclusion, the metric that you are looking for in a guest virtual machine depends on the hypervisor that it is running on, whether that hypervisor chooses to provide the data about how it spends its time other than servicing that VM, and if the guest OS has the right virtualization integration tools/services/drivers to be aware enough to realize that the hypervisor is making that data available.
I know of no way on a Windows guest, integration tools installed or not, to see how much time, in terms of seconds or percentage, that VM's host has spent servicing it or not servicing it respective to the total physical processor time. (Edit 10/1/2013: ESXi 5.0 or better exposes this data to the guest VM through the integration tools. Still nothing on Hyper-V though.)
Comment: It could, in theory, but don't hold your breath. Like I said, it requires that the vendor-specific hypervisor and the vendor-specific guest OS make a coordinated effort to make that data about the physical host available and accessible from within the guest VM.    http://wiki.xen.org/wiki/Xen_Kernel_Feature_Matrix
Comment: Tangential: VMware hypervisors will refer to steal team as [ready time](http://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/cpu_counters.html) -- the amount of time a virtual CPU is waiting to be serviced by a physical resource.
Comment: +1 - epic answer is epic
Comment: +1 for the thorough exploration indeed, highly appreciated. So regarding EC2 this apparently boils down to Unix/Linux guests running in `Xen paravirtual` mode, which is a _paravirtualized domain_ (i.e. not full virtualization, the guest OS is modified to run on the host), where _steal time_ is available, vs. Windows/FreeBSD/... guests running in `Xen HVM`, which is a _hardware emulated domain_ (i.e. the guest OS is unmodified to run on the host), where it apparently isn't - so a definite negative answer, guess that's what counts. Do I read you correctly that it could get added eventually?
Comment: this is a well known topic on the mainframe. The metric has been available for decades. It's called "wait on cpu".
Comment: Still fascinated by this topic, I looked up a Windows 2003 machine running on ESXi 5.1, and it looks like CPU information is available to the guest about it's virtualized CPU state, specifically it's stolen time (referred to as just that on the guest), CPU shares, CPU limit, and CPU reservation. [pic](https://gs1.wac.edgecastcdn.net/8019B6/data.tumblr.com/5fb69f67fe9976259b0209c63cb6d7fc/tumblr_mtzr01k5iF1qzcm9mo1_500.png)
Comment: @evilensky Indeed! It's newly added in ESXi 5.0 or later. Also the VMware tools must be up to date. Here's one reference: http://publib.boulder.ibm.com/infocenter/tivihelp/v61r1/index.jsp?topic=%2Fcom.ibm.itm.doc_6.3%2Foswin%2Fattr_vmprocssr.htm
Comment: @RyanRies, Thats an awesome explanation. I am working on fetching "cpu steal" metric from a hyperv-vm, using WMI counters using a vb script.. Right now, i cant see "Hyper-V Hypervisor Virtual Processor" class on the vm. But its present on the physical host. I am able to connect to the to the host machine(by providing username and password) and get this data. But its not practical for a vm to the credentials of host. Is there any other way i can get these WMI counters without needing to connect to the host?
Answer: FWIW, I just looked through the Perfmon counters of a Windows 2008r2 server running under Hyper-V and did not see anything related steal time (or to virtualization at all for that matter).
Comment: Thanks for checking - apparently [Virtualization Counters](http://technet.microsoft.com/en-us/library/ff367892.aspx) for Hyper-V should actually be available, maybe they must be installed/activated somehow first? I'm still unable to identify/deduce a similar/related metric amongst these though.


How to retrieve node body from nid with an SQL query in Drupal 7?

Question: From this question I learned that I have to look in field_data_body to retrieve the body of a node from a database.
field_data_body does not have an nid field though.
What query can I use to retrieve the body from an nid?
To clarify: I simply wanted to quickly fetch a text from a database dump without installing the dump on an actual site. So not looking for PHP here.
Answer:
field_data_body does not have an nid field though.

Because a field can be attached to any entity, which may have a different primary key than nid.
If you really must use direct SQL, you can query the field like this
SELECT body_value FROM field_data_body WHERE entity_type = 'node' AND entity_id = 1
However, this bypasses several of Drupal's layers, so it's normally strongly discouraged to use direct queries.
Instead, it's better to
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->propertyCondition('nid', 1)
;
$result = $query->execute();

$nodes = node_load_multiple(array_keys($result['node']));

foreach ($nodes as $node) {
  $bodies = field_get_items('node', $node, 'body');
  foreach ($bodies as $body) {
    var_dump($body['safe_value']);
  }
}

The EFQ version have several advantages

It's safe. You can't (easily) accidentally open injection attacks.
It outputs a safely escaped value, avoiding XSS attacks.
It works if a node has multiple values for the body field.
It works on sites with multiple languages.
Answer: I believe it's because field_data_body can be associated with entities that are not nodes, you need to look at the entity_id field as equivalent to the nid field.
If it's a node's body content you're trying to query, then I would run db_query('SELECT body_value FROM `field_data_body` where entity_id = :nid, array(":nid" => $nid));
Answer: In general, all entities are fieldable. Thus, the table field_data_body holds data for all body fields, regardless of being attached to a node or a comment. Hence, the column you are looking for is entity_id (with entity_type = 'node').
On a side node, you shouldn't tamper with the database in such a way, just use
$node = node_load($nid);
$body = node->body['und'][0]['value'];

to get the body (exact code of course depends on your site setup in terms of language, etc.).
Comment: please don't recommend `->body['und'][0]['value']` but use `field_get_items` instead.


Markers Google Maps V3 JavaScript

Question: var map

function detectBrowser() {
  var useragent = navigator.userAgent;
  var mapdiv = document.getElementById("map_canvas");

  if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {
    mapdiv.style.width = '100%';
    mapdiv.style.height = '100%';
  } else {
    mapdiv.style.width = '600px';
    mapdiv.style.height = '800px';
  }
}

function carregarMapa() {

    lat=document.getElementById("txtLat").value;
    lng=document.getElementById("txtLng").value;

var myLatlng = new google.maps.LatLng(lat,lng);

var mapOptions = {
    zoom: 16,
    center: myLatlng,
disableDefaultUI : false

  }

var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  map.setOptions({styles: [
    {
     featureType: "poi",
     stylers: [
        { visibility: "off" }
     ]
    }
 ]});

}

function criaPonto(){

plat=document.getElementById("txtLat").value;
plng=document.getElementById("txtLng").value;

var myLatlng = new google.maps.LatLng(plat,plng);

var marker2 = new google.maps.Marker({
  position: myLatlng,
  map: map,
  title: 'Título Restaurante Y'});

}
google.maps.event.addDomListener(window, 'load', initialize);

Olá, criei esse código no javascript tentando criar um mapa do google onde eu posso carregar markers, até o momento, só consegui criar markers se eu ficar resetando o mapa, e a ideia era criar esses markers em tempo de execução.
Por exemplo:
Criaria um marker se este estivesse a X de distância do ponto que meu sensor localizou, caso contrário, esse marker não é exibido.
O Problema foi resolvido!
Agradeço a ajuda do usuário : https://pt.stackoverflow.com/users/10196/migmar
Que foi bem presente e conseguiu me explicar os meus erros.
Obrigado!
Answer: A função initialize chamada na última linha do seu código não existe. Deve substituir o nome da função carregarMapa() por initialize(). A função criaPonto() nunca é chamada?
Tem de criar um método na função initialize que detecte a proximidade de novos pontos e aí chamar a função criaPonto().
Tem de criar uma variável tipo array com nome markers, e depois adiciona cada marcador nessa variável, através da função criaPonto() com markers.push(marker2).
Comment: Olá, obrigado pela resposta...
Então, a função carregarMapa() e criaPonto() são chamadas por botões no meu form html, segue o código:

Comment: Ok, compreendi. Vamos por partes, a função carregarMapa() pode ser executada dessa forma. Mas a última linha de código "google.maps.event.addDomListener(window, 'load', initialize);" existe para isso mesmo. Repara, primeiro parâmetro é "window" + segundo parâmetro "load". Isto é igual a "body onload". O terceiro parâmetro é o nome da função que deverá ser chamada quando a página acaba de carregar. Por norma essa função é chamada de initialize, voce optou por carregarMapa. Retire o onload do elemento  e substitua initialize por carregarMapa.
Agora, como o valor de txtLat é actualizado?
Comment: Ok, alterei a linha e deletei o onload do body. Obrigado pela dica!
Entendi o porque ela se chama initialize graças a sua explicação! O valor de txtLat e txtLng são atualizados por um campo :  por esse motivo dou um document.getElementById no código. Eu tinha tentado deixado o map como variável global, mas não conseguia carregar ele nas funções. vou tentar novamente depois
Comment: Tenho alguns artigos para iniciante em Google Maps API publicados em http://www.marnoto.com. Talvez possam ajudar a compreender a estrutura da criação dos mapas e marcadores.
Comment: Eu já acessei esse site, mas não consegui encontrar isso que perguntei aqui no stackflow.
Comment: Eu ainda não compreendi bem aquilo que pretendes fazer. Podes indicar o link para o teu site para que eu possa dar uma olhada no código?
Comment: Não está online, é um projeto que está local, mas passo o link do projeto para que possa testar localmente.
https://drive.google.com/file/d/0B5kTRRclWirSamNKc183V0FGNHM/edit?usp=sharing

Oque quero é incluir marcadores sem precisar recarregar o mapa, no momento consigo incluir apenas um marcador e para isso preciso recarregar o mapa (mesmo usando-o como variável global)

Na verdade vou passar isso para um APP mobile, e ainda estou na fase de aprendizado e testes, mas futuramente precisarei de acesso ao GPS do usuário também...
Comment: Esse ficheiro está restrito, tem de dar permissão de acesso.

Markers Google Maps V3 JavaScript


There is no default content in joomla 3.1

Question: I am new to joomla, so i recently downloaded joomla 3.1 after installing it in my localhost i am not able to proceed further in creating a website since there is no default content in joomla 3.1 when compared to joomla 2.5.
Is there any way to enable the content from administrator login ?
Answer: No, default content is installed  as part of the setup process.
If all you've done is install Joomla, then I suggest you delete the installation and re-install Joomla, this time selecting the option to install one of the "Sample Data" groups:

List itemBlog English (GB) Sample Data
Brochure English (GB) Sample Data
Default English (GB) Sample Data
Learn Joomla English (GB) Sample Data
Test English (GB) Sample Data

You'll find this option on the third and final tab before the installation proceeds, as shown below:


Como carregar uma tabela Excel e transforma-la em uma tabela HTML utilizando JavaScript?

Question: Pretendo criar um botão para carregar um arquivo xls ou csv e transformar essa tabela do Excel em uma tabela HTML, como posso fazer isso utilizando JavaScript? Por favor...
Comment: Você vai precisar de uma linguagem de programação. Sugiro adicionar a linguagem de sua preferência nas tags, para que a gente possa responder com exemplos nessa linguagem.
Comment: Ah sim, farei isso, obrigado!
Comment: @JuanLima você tentou a solução que eu lhe propus?
Answer: Existe um plugin jQuery que possibilita a conversão de de arquivos .csv para JSON. Desta forma você consegue extrair os dados do arquivo e trabalhar com eles em tela como bem desejar.
Segue link do site oficial do plugin: papaparse.com
Fiz este código abaixo para testar o plugin (Você pode facilmente copiar e testar em seu computador):

    <title>Teste PapaParse</title>

    Arquivo (.csv) <input type="file" name="csv_file">

    <button id="btnConverter">Converter</button>

O código acima disponibiliza um botão para selecionar o arquivo e outro que converte o arquivo em JSON e exibe em tela como uma tabela.
Nesse link há um arquivo .csv para testar a funcionalidade.


How to test whether the difference in difference between means is significantly different? (with example)

Question: Basically I have

Four groups (2-by-2) with sample means $\overline{x_{1,A}}$, $\overline{x_{2,A}}$, $\overline{x_{1,B}}$ and $\overline{x_{2,B}}$, standard deviations $s_{1,A}$, $s_{2,A}$, $s_{1,B}$ and $s_{2,B}$ with sample sizes $n_A$ and $n_B$ (i.e. $n_{1,A}=n_{2,A}$ and $n_{1,B}=n_{2,B}$).

I calculate the differences between the two means as $d_{1-2, A} =  \overline{x_{1,A}}-\overline{x_{2,A}}$ and $d_{1-2, B} =  \overline{x_{1,B}}-\overline{x_{2,B}}$.
My objective is to test whether $d_{1-2, A}$ is statistically different from $d_{1-2, B}$, corresponding to a two sided test.
My suggestion would be: $\frac{d_{1-2, A}-d_{1-2, B}}{ [s_{1-2, A}^2/n_A] + [s_{1-2, B}^2/n_B] }$.
The problem is that I don't know how to calculate the standard deviation of this difference, i.e. $s_{1-2, A}$ and $s_{1-2, B}$.
So my questions are basically:

Do you agree with my procedure?
How do I calculate $s_{1-2, A}$ and $s_{1-2, B}$?

p.s. I tried $s_{1-2, A} = \sqrt{s_{1,A}^2 + s_{2,A}^2}$ but it didn't work.

Here is an example with numbers
$\overline{x_{1,A}} = 2.310$; $s_{1,A}=0.865$; $n_A = 16753$
$\overline{x_{1,B}} = 2.403$; $s_{1,B}=0.897$; $n_B = 5378$
$\overline{x_{2,A}} = 2.993$; $s_{2,A}=1.002$; $n_A = 16753$
$\overline{x_{2,B}} = 3.108$; $s_{2,B}=1.042$; $n_B = 5378$
The objective is to replicate a p-value for significane between $d_{1-2, A}$ and $d_{1-2, B}$ of $0.032$ (two sided would be my guess).
Answer: You can get this result just by determining the distribution of the final random variable representing the difference-in-difference.  Each of your means has a standard error of $\frac{s_{i,g}}{\sqrt{n_g}}$, for $i \in \{1, 2\}$ and $g \in \{A, B\}$.  That implies that the true means (call them $X_{i,g}$) are distributed as $X_{i,g} \sim \mathcal{N}(\bar{x_{i,g}},\ \frac{s_{i,g}}{\sqrt{n_g}})$.
You want to determine the distribution of the final random variable, to see how much of it crosses 0.  That is, $X_{1,A} - X_{2,A} - (X_{1,B} - X_{2,B})$.  This is just a linear combination of Gaussian random variables, so the answer is:
$$
\mathcal{N}\!\left(\bar{x_{1,A}} - \bar{x_{2,A}} - (\bar{x_{1,B}} - \bar{x_{2,B}}),\ \ \sqrt{\frac{s_{1,A}^2}{n_A} + \frac{s_{2,A}^2}{n_A} + \frac{s_{1,B}^2}{n_B} + \frac{s_{2,B}^2}{n_B}}\right)
$$
Then you can just integrate the density of the PDF that's less than 0.  If that integral is less than your significance level, then the difference is significant.
Comment: Welcome to the site, @JamesRising. With the quality of your answer & your mastery of our formatting, we look forward to having you around.
Answer: Kind of a cheap trick, but because the t-test is a special case of a linear regression model adjusting for a binary predictor, the analogous regression routine for what you're calculating is a test of interaction, also called effect modification.
If you have a design matrix with an intercept, 1 column of 0/1 indicators denoting membership to one of the two groups, and another column of 0/1 indicators for membership to the comparison versus referent category in each group, then the product of these two columns gives a regressor which estimates the "difference in differences" as a parameter in the regression model.
The standard error of this term can be obtained mathematically by calculating the covariance matrix for parameter estimates: $\sigma^2 \mathbf{X}^T\mathbf{X}$. This corresponds to the T-test for equal variances. Using the sandwich based robust standard error estimator: $(\mathbf{X}^T\mathbf{X})^{-1}(\mathbf{X}^Tr^2_i\mathbf{X})(\mathbf{X}^T\mathbf{X})^{-1}$ is analagous to the t-test in unequal populations.
Comment: Thank you for the reply. So basically I will need the covariance matrix. Do you perhaps know other "cheap tricks" without the use of the covariance matrix, and hence assuming that the two variables are independent - or an estimate that approaches the estimate with the covariance. I am asking this because I do not have information available on the covariance between the two variables.
Comment: It's dead easy to do with R, are you determined to calculate an exact mathematical expression for this value?
Comment: If you have the variables then yes its dead easy. But I was indeed searching for the exact mathematical expression.


single-row subquery returns more than one row : ORA-01427

Question: UPDATE DESIGNATION_REVISED A SET A.DCODE_ORG=(SELECT D.DCODE_ORG FROM DESIGNMAST_DUP D WHERE D.DNAME=A.DNAME)

The above update throws

single-row subquery returns more than one row : ORA-01427
Comment: It is what is says - your subquery e.g. `SELECT D.DCODE_ORG FROM DESIGNMAST_DUP D WHERE D.DNAME=A.DNAME` returns more than one `DCODE_ORG` for specific `DNAME` - check your data ...  change your subquery to return single row ...
Answer: I think in your DESIGNMAST_DUP  table names are duplicate so inner query returns more than one row.
Try this:-
UPDATE DESIGNATION_REVISED A SET A.DCODE_ORG=(SELECT distinct D.DCODE_ORG FROM DESIGNMAST_DUP D WHERE D.DNAME=A.DNAME)


puppet - using ensure with package 'version' and 'held'

Question: Overview:
Just started using Puppet and used the following array with 'ensure' so a specific version of Apache is installed (rather than the latest) and its 'held'(which means it won't be upgraded on a standard apt-get dist-upgrade to the latest version.
Problem:
When using the code below only the first value in the ensure array is taken into consideration by Puppet.  So when the code is below is executed it installs the correct version of Apache but the package is not set to hold (checked by running dpkg --get-selection).
If the values in the array are swapped then the package is held but the latest version is installed.
Code:
package { 'apache2':

        ensure => [ "2.0.64", held ],
 }

Appreciate any pointers on this one!
Thanks.
Comment: "Held is considered a superset of installed." Source: http://docs.puppetlabs.com/references/2.6.4/type.html
Answer: As best I can tell by reading the source code the "holdable" feature is fundamentally flawed.  The ensure (see ensurable.do, line 50) cannot accept an array of options.  Thus, a package can not both be installed at a particular version and marked held using dpkg.  I assume the default behavior of the parser is such that if it receives an array where one is not supported, the first value is used.  That would explain your outcome.
In my opinion the version and/or holdable features should be re-implemented as a new variable, such as:
package { 'apache2'
  ensure => installed,
  version => '2.0.64',
  hold => true,
}

I suggest you submit a bug report.  In the meantime, you could do:
package { 'apache2':
  ensure => '2.0.64',
}

exec { 'hold-apache2-version':
  command => 'dpkg ...',
  require => Package['apache2'],
}

Comment: Thanks for getting back to me.  I'll take a look at the source code as you suggest.  Something I'm defo going to do in the future!
Comment: P.S I guess the only way to achieve the desired pinning of packages would be to run an exec command with dpkg --set-selections
Answer: I came up with a workaround. Brace yourself, this is gross.
if $::puppetversion == '2.7.11' {
  $ensure_puppet = 'held'
} else {
  $ensure_puppet = '2.7.11-1puppetlabs1'
}
package { ['puppet', 'puppet-common']:
  ensure => $ensure_puppet
}

It uses the built-in fact $::puppetversion to do version interrogation. So the state of the package will be 'held' unless the installed version is different from what we want. This should enable me to upgrade the puppet infrastructure at will without worrying about unattended-upgrades doing it for me.
This doesn't answer the exact question regarding version locking Apache, but one could trivially write a custom fact to query Apache for its version.
I had initially tried the manual dpkg hold approach. I used the package type to ensure versions and then ran an execute script to make sure it was held separately. It's similar to the approach that I take with yum version locking.
define apt::hold() {
  exec { "hold-${name}":
    command => "/bin/echo '${name} hold' | /usr/bin/dpkg --set-selections",
    unless  => "/usr/bin/dpkg --get-selections ${name} | /bin/grep hold",
    require => Package[$name]
  }
}

package { ['puppet', 'puppet-common']:
  ensure => '2.7.11-1puppetlabs1'
}
apt::hold { ['puppet', 'puppet-common']: }

Now, this works, but it produces a lot of annoying notifications in the logs and reports. The package type can't reconcile that a package can be both held and a certain version. So it will notify me that the package state has changed from 'held' to '2.7.11-1puppetlabs1'.
[sanitized.server.name.net] out: info: Retrieving plugin
[sanitized.server.name.net] out: info: Loading facts in /var/lib/puppet/lib/facter/operatingsystemmajor.rb
[sanitized.server.name.net] out: info: Loading facts in /var/lib/puppet/lib/facter/datacenter.rb
[sanitized.server.name.net] out: info: Caching catalog for sanitized.server.name.net
[sanitized.server.name.net] out: info: Applying configuration version '1333727048'
[sanitized.server.name.net] out: notice: /Stage[main]/Puppet/Package[facter]/ensure: ensure changed 'held' to '1.6.6-1puppetlabs1'
[sanitized.server.name.net] out: notice: /Stage[main]/Puppet::Client/Package[puppet-common]/ensure: ensure changed 'held' to '2.7.11-1puppetlabs1'
[sanitized.server.name.net] out: notice: /Stage[main]/Puppet::Client/Package[puppet]/ensure: ensure changed 'held' to '2.7.11-1puppetlabs1'
[sanitized.server.name.net] out: notice: Finished catalog run in 6.25 seconds

I don't like my reports crying wolf all the time. It also causes issues if I want to do something like:
package { ['puppet', 'puppet-common']:
  ensure => '2.7.11-1puppetlabs1',
  notify => Service['puppet']
}

To restart the service after an upgrade. I end with the service being bounced every single time puppet runs.
I agree with everyone else though that 'held' should probably be a separate attribute of the package type.
Answer: I use this puppet module to manage apt on my systems. It provides a "preferences_snippet" define which can be used to pin packages to specific versions or releases (see README).


Creating a function that works for all numeric primitives

Question: I am writing an assembly with some functionality that is intended to work with numeric primitives, i.e. float, int, decimal, etc.
One of the functions takes two sequences and calculates the running average of the two. An implementation for floats may look like this
let average x y = (x+y)/2.
let a = [1..10] |> List.map float
let b = List.rev [1..10] |> List.map float
let result = (a, b) ||> List.map2 average

How can I make this generic for numeric primitives?
Answer: F# has so called "static member constraints" that can be used for writing generic numerical code. This is limited to F# (because .NET has no concept like this).
In general, you need to mark the function as inline. This will make the standard operators inside the function behave as generic. In addition, you need to avoid using constants (like 2.0). You can typically replace them with some operation from the LanguagePrimitives module. For example, your average function can be written as generic using:
let inline average x y =
  LanguagePrimitives.DivideByInt (x + y) 2

For more information check out this blog post about generic numeric computations in F#.
Comment: Very nice blog post.


JOptionPane Cannot Find Symbol

Question: I am trying to create a simple calculator using JOptionPane. I have encountered compiling errors.
import javax.swing.JOptionPane;

public class Calculator {
  public static void main ( String args[] ) {

     double n1 = Double.parseDouble(JOptionPane.showInputDialog(" Enter first number: "));
     double n2 = Double.parseDouble(JOptionPane.showInputDialog(" Enter second number: "));
     String x = JOptionPane.showInputDialog("Enter operator: ");
     double result;

     if (x == "+"){
         result = (n1 + n2);
           JOptionPane.showMessageDialog(n1, "+", n2,"=", result);
           }

        else if (x == "-"){
         result = (n1 - n2);
           JOptionPane.showMessageDialog(n1,"-", n2,"=", result);
           }

        else if (x == "/"){
            result = (n1 / n2);
            JOptionPane.showMessageDialog(n1,"/", n2,"=", result); }
        else if (n2 == 0){
                JOptionPane.showMessageDialog(null, "Cannot divide by 0"); }

        else if (x == "*"){
            result = (n1 * n2);
            JOptionPane.showMessageDialog(n1,"*", n2,"=", result); }

        else if (x == "%"){
               result = (n1 % n2);
               JOptionPane.showMessageDialog(n1,"%", n2,"=",(n1%n2)); }
  }
}

My code brings up these compiling errors:
5 errors found:
File: /Users/gcaruso/Documents/CISS 110/Module 3/Module 4/Calculator.java  [line: 14]
Error: /Users/gcaruso/Documents/CISS 110/Module 3/Module 4/Calculator.java:14: cannot find symbol
symbol  : method showMessageDialog(double,java.lang.String,double,java.lang.String,double)
location: class javax.swing.JOptionPane
File: /Users/gcaruso/Documents/CISS 110/Module 3/Module 4/Calculator.java  [line: 19]
Error: /Users/gcaruso/Documents/CISS 110/Module 3/Module 4/Calculator.java:19: cannot find symbol
symbol  : method showMessageDialog(double,java.lang.String,double,java.lang.String,double)
location: class javax.swing.JOptionPane
File: /Users/gcaruso/Documents/CISS 110/Module 3/Module 4/Calculator.java  [line: 25]
Error: /Users/gcaruso/Documents/CISS 110/Module 3/Module 4/Calculator.java:25: cannot find symbol
symbol  : method showMessageDialog(double,java.lang.String,double,java.lang.String,double)
location: class javax.swing.JOptionPane
File: /Users/gcaruso/Documents/CISS 110/Module 3/Module 4/Calculator.java  [line: 32]
Error: /Users/gcaruso/Documents/CISS 110/Module 3/Module 4/Calculator.java:32: cannot find symbol
symbol  : method showMessageDialog(double,java.lang.String,double,java.lang.String,double)
location: class javax.swing.JOptionPane
File: /Users/gcaruso/Documents/CISS 110/Module 3/Module 4/Calculator.java  [line: 37]
Error: /Users/gcaruso/Documents/CISS 110/Module 3/Module 4/Calculator.java:37: cannot find symbol
symbol  : method showMessageDialog(double,java.lang.String,double,java.lang.String,double)
location: class javax.swing.JOptionPane
Answer: I finished it off so the whole thing works:
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Calculator extends JPanel {
    public static void main(String args[]) {

        JFrame f = new JFrame();

        double n1 = Double.parseDouble(JOptionPane
                .showInputDialog(" Enter first number: "));
        double n2 = Double.parseDouble(JOptionPane
                .showInputDialog(" Enter second number: "));
        String x = JOptionPane.showInputDialog("Enter operator: ");
        double result;

        if (x.equals("+")) {
            result = (n1 + n2);
            JOptionPane.showMessageDialog(f, n1 + "+" + n2 + "=" + result);
            System.out.println(x);
        }

        else if (x.equals("-")) {
            result = (n1 - n2);
            JOptionPane.showMessageDialog(f, n1 + "-" + n2 + "=" + result);
            System.out.println(x);
        }

        else if (x.equals("/")) {
            if (n2 == 0) {
                JOptionPane.showMessageDialog(null, "Cannot divide by 0");
            }else{
            result = (n1 / n2);
            JOptionPane.showMessageDialog(f, n1 + "/" + n2 + "=" + result);
            System.out.println(x);
            }
        }

        else if (x.equals("*")) {
            result = (n1 * n2);
            JOptionPane.showMessageDialog(f, n1 + "*" + n2 + "=" + result);
        }

        else if (x.equals("%")) {
            result = (n1 % n2);
            JOptionPane.showMessageDialog(f, n1 + "%" + n2 + "=" + (n1 % n2));
        }
    }
}

"==" is not the same as ".equals" -
.equals compares the value of the two objects
== compares if they are the same object in java ~
Comment: As a note, you don't need to provide a `JFrame f`. You can use `null` and the dialogs will work just fine. The first argument is for a parent owner IIRC. If something doesn't have a parent, no need to give it one.
Comment: Understandable, @MatthewRowlands FYI, it's hidden away in the [JavaDoc](http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html#showMessageDialog%28java.awt.Component,%20java.lang.Object%29).
Answer: So I think you have done the method showMessageDialog wrong:
JOptionPane.showMessageDialog(n1, "+", n2,"=", result);

Try this:
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Calculator extends JPanel {
    public static void main(String args[]) {

        JFrame f = new JFrame();

        double n1 = Double.parseDouble(JOptionPane
                .showInputDialog(" Enter first number: "));
        double n2 = Double.parseDouble(JOptionPane
                .showInputDialog(" Enter second number: "));
        String x = JOptionPane.showInputDialog("Enter operator: ");
        double result;

        if (x == "+") {
            result = (n1 + n2);
            JOptionPane.showMessageDialog(f, n1 + "+" + n2 + "=" + result);
        }

        else if (x == "-") {
            result = (n1 - n2);
            JOptionPane.showMessageDialog(f, n1 + "-" + n2 + "=" + result);
        }

        else if (x == "/") {
            result = (n1 / n2);
            JOptionPane.showMessageDialog(f, n1 + "/" + n2 + "=" + result);
        } else if (n2 == 0) {
            JOptionPane.showMessageDialog(null, "Cannot divide by 0");
        }

        else if (x == "*") {
            result = (n1 * n2);
            JOptionPane.showMessageDialog(f, n1 + "*" + n2 + "=" + result);
        }

        else if (x == "%") {
            result = (n1 % n2);
            JOptionPane.showMessageDialog(f, n1 + "%" + n2 + "=" + (n1 % n2));
        }
    }
}

Comment: Thank you! Now it is compiling but it is still showing no output.
Comment: As a side note, you can use switch/case on strings as of java 7.

JOptionPane Cannot Find Symbol


multiple SqlConnections for one feature: bad idea?

Question: I got an asp.net gridview connected to my sql database. When Inserting a new record or updating a record im doing some serverside checks and then either update/insert a record or do nothing. right now i got 2 methods CheckArtistExists and CheckSongExists which are both using a SqlConnection Object e.g.
public bool CheckSongExists(string _title, int _artistId)
    {
        int cnt = -1;
        using (SqlConnection con = new SqlConnection(CS))
        {
            //check if song already is exists in DB
            SqlCommand cmd = new SqlCommand("Select Count(ID) from tblSong WHERE Title = @newTitle AND ArtistId = @newArtistId;", con);
            cmd.Parameters.AddWithValue(@"newTitle", _title);
            cmd.Parameters.AddWithValue(@"newArtistId", _artistId);
            con.Open();
            cnt = (int)cmd.ExecuteScalar();
            // if cnt ==1 song exists in DB, of cnt == 0 song doesnt exist
            if(cnt == 1)
            { return true; }
            else
            { return false; }
        }
    }

So for the Update function in the gridview i need to establish 3 SqlConnections (at max) one to check for the artist(if artist doesnt exist i have to insert a record to tblArtist first)
then a check if the song exists(only if artist exists) and finally if song doesnt exist I have to insert a new record.
I know database connections are valuable resources thats why i put them in a using block. So im not quite sure if its good style to use 3 SqlConnection objects to update/insert. Can you please tell me if my code is ok or if i should rather use another approach for this problem.
thank you
Answer: ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:

In practice, most applications use only one or a few different
  configurations for connections. This means that during application
  execution, many identical connections will be repeatedly opened and
  closed. To minimize the cost of opening connections, ADO.NET uses an
  optimization technique called connection pooling.
Connection pooling reduces the number of times that new connections
  must be opened. The pooler maintains ownership of the physical
  connection. It manages connections by keeping alive a set of active
  connections for each given connection configuration. Whenever a user
  calls Open on a connection, the pooler looks for an available
  connection in the pool. If a pooled connection is available, it
  returns it to the caller instead of opening a new connection. When the
  application calls Close on the connection, the pooler returns it to
  the pooled set of active connections instead of closing it. Once the
  connection is returned to the pool, it is ready to be reused on the
  next Open call.

So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created, opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.
So you're gaining no performance improvement if you "reuse" connections but the opposite.

Create, open(in case of Connections), use, close and dispose them where you need them(f.e. in a method)
use the using-statement to dispose and close(in case of Connections) implicitely

So yes, it's absolutely fine to use one connection per method since you are not using a physical connection at all if connection-pooling is enabled (default).
Another question is if you could improve your approach. You could create a stored-procedure which checks existence and updates or inserts accordingly.
Solutions for INSERT OR UPDATE on SQL Server


Prove that $R/(2i)$ and $\mathbb{Z}/4\mathbb{Z}$ are isomorphic rings

Question: Let $R=\{a+2ib|a,b\text{ integers}\}$.Prove that $R/(2i)$ is isomorphic to $\mathbb{Z}/4\mathbb{Z}$
Comment: I saw that if a is of the form 4k+t(t=1,2,3) then 4k+t=(-2i)(2ik)+t.So a+2ib mod (2i) is actually equal to t mod (2i).But I am not getting the isomorphism
Comment: Can you list some of the elements of the quotient $R/(2i)$?
Comment: I want to ask a question here: If i can show there are two homomorphism one from A to B, another B to A, then does Schröder-Bernstein theorem imply , there exists a isomorphism between them ?
Comment: But as far I know you need to have some injective homomorphism to apply bernstein
Answer: Often, when trying to show that there exists an isomorphism between a quotient ring $R/I$ and another ring $S$, it is easiest to find a surjective homomorphism $R\to S$ which has kernel $I$, and then to use the isomorphism theorem.
In this case, consider the map
$$\begin{align}R &\to \mathbb Z/4\mathbb Z\\a+2ib&\mapsto a\pmod 4\end{align}$$
Can you show that this:

is a homormorphism
is surjective
has kernel $(2i)\subset R$


What is the record for winning a Formula 1 race by leading least number of laps?

Question: What is the record for winning a Formula 1 race by a driver who has lead the least number of laps in that race?
For example: if one driver has been in position 1 for the entire race but on the last lap had an engine failure such that the driver in position 2 won the race without actually leading the race for any laps.
Has this ever happened? If not that what is the minimum number?
Comment: The lead laps is only defined when the driver crosses the line right? So, if he takes the win on last lap wouldn't be 0 laps lead?
Answer: There have been cases where a driver won without leading a single lap (mostly due to post-race disqualifications), and there have been cases where a driver took the lead on the last lap, of which my favourite was the 2011 Canadian Grand Prix win by Jenson Button.
List of drivers who won without leading (source):

List of drivers who won after leading only one lap (source):


probability of choosing an object at least once in $3$ drawings

Question: So there are $4$ objects in total, and I want to know the probability of choosing object A at least once in $3$ drawings. What I did was add  $3C1 + 3C2 + 3C3$ and got $7$ and, as a final answer, I got $7/64$, since there is a $4^3$ samples space. Why doesn't this method work?
Answer: You're not taking into account the different possibilities for the choices that aren't A. It's true that if you pick A exactly once, there are $\binom31=3$ ways to pick which of the $3$ choices is the A, but in each case there are $3\cdot3=9$ possible ways to make the other two choices: each can be any of the other $3$ outcomes. That's a total of $3\cdot9=27$ different sequences of $3$ choices having exactly one A. Similarly, if exactly $2$ of the choices are A, there are $\binom32=3$ ways to choose which $2$ choices they are, but the remaining choice can be any of the other $3$ possible outcomes. Thus, there are $3\cdot3=9$ different sequences of $3$ choices having exactly two As. Finally, there is a single sequence having A every time, so there are altogether $27+9+1=37$ sequences having at least one A, and the probability of such a sequence is therefore $\frac{37}{64}$.
Comment: makes sense again. thanks again haha
Comment: @Armon: You're welcome!


Add extra obligatory fields when editing a node as anonymous user

Question: I need a way to either add extra fields or make two fields obligatory when an anonymous user is editing a node. I'll explain:
There is a node type in my site that can be freely edited, modifications are saved as new revisions. To know who edited a node i want to add a mail field and other extra fields that require other info from the anonymous user but these fields don't need to be obgligatory when the nodes are edited by registered users.
I was thinking about using the module suggested in this discussion: How can anonymous users be allowed to post while still maintaining content integrity?
but i require that the mail entered from the user is saved inside the node and also i require an extra field other than the mail.
Is there any way to achieve that?
Answer: You could use a the hook_form_alter to get the desired function:
<code>function mymodule_form_alter(&$form, &$form_state) {
  if($form['type']['#value'] == 'DESIRED_CONTENT_TYPE') {
    if( user_is_anonymous() ){
      //Fields are required for anonymous users
      $form['field_ABC'][LANGUAGE_NONE]['0']['value']['#required'] = TRUE;
      $form['field_DEF'][LANGUAGE_NONE]['0']['value']['#required'] = TRUE;
    }
    else{
      //Hide fields for logged in users
      $form['field_ABC']['#access'] = FALSE;
      $form['field_DEF']['#access'] = FALSE;
    }
  }
}
</code>
Comment: Isn't there a module to do it? Otherwise how do i specify that this has to happen only for a certain content type?
Comment: You can use $form['type']['#value'] to get the content type
Comment: missing a "{" on line 2, but it works, thanks!
Comment: great! I added the missing "{" in the example.