What does it mean for the variance to be squared?

Question: Suppose we are measuring the heights of different people. Our measures will be in $cm$, but the variance will be in $cm^2$. If we were measuring the time to complete a race course, our measures would be in $seconds$ , but the variance would be $seconds^2$
What do those units mean? Why are they there?
I'm not asking about the formula, that much I can understand, but I'm asking for the underlying meaning of it.
Answer: We calculate the variance by finding the squared differences between each data point and the mean. Squaring these differences ensures they are all positive.
The squaring of variance is used to ensure that there are not canceling issues while using signed values that have direction. For example, someone a few centimeters taller and another a few centimeters shorter than the average might have their deviations cancel to zero. Squaring ensures all deviations contribute as positive values, preventing this cancellation and providing a more accurate picture of the spread.
Squaring the units also gives more weight to larger deviations. Since squares are always non-negative, larger deviations from the mean contribute more significantly to the overall variance.


Clicar sobre a barra de títulos e não ordenar a coluna no dataTables

Question: Bom dia. Estou usando o dataTables e em uma das colunas eu coloquei um input:checkbox para o usuário poder marcar ou desmarcar todas colunas, lembrando que nas colunas eu tenho como fazer a ordenação quando clica na barra de título e nessa coluna também tem isso. Até ai tudo funcionando. O que não estou sabendo como fazer é que, quando o usuário clica no checkbox não faça a ordenação, somente fazer essa ordenação, pois quando ele clica para marcar ou desmarcar já faz a ordenação, e isso que não pode acontecer. Como faço para tirar a ordenação apenas desta coluna?
Answer: Você pode desabilitar o ordenamento da primeira coluna com:
<code>$('#example').dataTable({
  "columnDefs": [
    {
      "orderable": false,
      "targets": 0
    }
  ]
});
</code>
De uma olhada na documentação para mais opções
Comment: Se o problema foi resolvido aceite essa reposta
Comment: Valeu pela ajuda Guilherme. Resolvi da seguinte forma:

"columnDefs": [ {
                        "targets": [ 0, 10 ],
                        "orderable": false
                    } ]


Como ler web service XML no VB6?

Question: Eu peguei vários exemplos na Web que deram certos, mas preciso pegar os valores desse arquivo que segue o link abaixo.

https://ws.printwayy.com/api/Printer?api_token=1F61D333-CCA5-423A-A764-F8577119A9FE&company_token=&serialNumbers=AK18054352&initialDate=&endDate=

Como eu faria isso com VB6?
Comment: Exemplo: https://technet.microsoft.com/pt-br/library/2008.10.heyscriptingguy.aspx
Comment: Obrigado pelos links Virgilio, mas não deram certo.
Comment: Exemplo: https://stackoverflow.com/questions/8254600/reading-xml-file-with-vbscript
Comment: @Guilherme, muito mas muito obrigado. Deu certo, eu vou estudar seu código. Mas fiz um teste aqui e respondeu. Obrigado mesmo
Comment: @Renato pode marcar a resposta como correta então? Se não souber como fazer veja este link https://pt.meta.stackoverflow.com/q/1078/3635, mas só marque se tiver certo que a resposta lhe resolveu mesmo o problema especificado. Até mais.
Answer: Você pode usar XMLHTTPRequest, que funciona bem semelhante ao do javascript e para fazer o parse do XML pode usa:
Set doc = CreateObject("MSXML2.DOMDocument")
doc.loadXML(xhr.responseText)

E o Xpath pode ser útil pra selecionar os nodes necessários:
Set nodes = doc.SelectNodes("//IPAddress")

Um exemplo "síncrono":
Dim xhr, method, url, contents, formatcontent, doc

Set xhr = CreateObject("MSXML2.XMLHTTP")

method = "GET" 'Escolhe o método HTTP de envio
url = "https://ws.printwayy.com/api/Printer?api_token=1F61D333-CCA5-423A-A764-F8577119A9FE&company_token=&serialNumbers=AK18054352&initialDate=&endDate=" 'url da API
contents = "" 'conteudo
formatcontent = "application/json" 'Se a API usar outro formato basta alterar aqui

xhr.Open method, url, False

'Necessário pra sua API retornar XML ao invés de JSON
xhr.setRequestHeader "Accept", "application/xml"

If method = "POST" Or method = "PUT" Then
    xhr.setRequestHeader "Content-Type", formatcontent
    xhr.setRequestHeader "Content-Length", Len(contents)
    xhr.send contents
Else
    xhr.send
End If

If xhr.status < 200 Or xhr.status >= 300 Then
    'Algo falhou, as vezes pode haver uma descrição em `xhr.responseText` ou pode retornar vazio, o `xhr.status` indica o tipo de erro
    MsgBox "Erro HTTP:" & xhr.status & " - Detalhes: " & xhr.responseText
Else
    'Faz o parse da String para XML
    Set doc = CreateObject("MSXML2.DOMDocument")
    doc.loadXML(xhr.responseText)

    'Seleciona com XPATH
    Set nodes = doc.SelectNodes("//IPAddress")

    MsgBox "Elementos encontrados para IPAddress: " & nodes.length

    For Each node In nodes
        MsgBox "Endereço IP: " & node.text
    Next
End If

Note que usei MSXML2.XMLHTTP e MSXML2.DOMDocument se causar erro tente mudar o MSXML2. para Microsoft., depende do sistema.

XmlHttpRequest assíncrono
Pra usar XMLHTTP assíncrono você pode usar:
Set xhr = CreateObject("MSXML2.XMLHTTP")
xhr.open hMethod, hUrl, True

E deve usar a propriedade:
xhr.onreadystatechange = GetRef([Nome de uma Function ou Sub])

Um exemplo completo:
Dim hMethod, hUrl, hFormat, hContents, hAccepts, xhr

'url da API
hUrl = "https://ws.printwayy.com/api/Printer?api_token=1F61D333-CCA5-423A-A764-F8577119A9FE&company_token=&serialNumbers=AK18054352&initialDate=&endDate="

hMethod   = "GET"              'Metodo HTTP
hAccepts  = ""                 'Necessário pra sua API retornar XML ao invés de JSON
hContents = ""                 'Conteúdo em requisições POST/PUT
hAccepts  = "application/xml"  'http accepts

MsgBox hUrl

Set xhr = CreateObject("MSXML2.XMLHTTP")

Sub doParseXml(xmlStr)
    'Faz o parse da String para XML
    Set doc = CreateObject("MSXML2.DOMDocument")
    doc.loadXML(xmlStr)

    'Seleciona com XPATH
    Set nodes = doc.SelectNodes("//IPAddress")

    MsgBox "Elementos encontrados para IPAddress: " & nodes.length

    For Each node In nodes
      MsgBox "Endereço IP: " & node.text
    Next
End Sub

'Recebe assincronamente o resultado
Sub doReadyStateChange()
    If xhr.readyState = 4 Then
        If xhr.status < 200 Or xhr.status >= 300 Then
            MsgBox "Erro HTTP:" & xhr.status & " - Detalhes: " & xhr.responseText
        Else
            doParseXml xhr.responseText
        End If
    End If
End Sub

xhr.onreadystatechange = GetRef("doReadyStateChange")

xhr.open hMethod, hUrl, True

If hAccepts <> "" Then
    xhr.setRequestHeader "Accept", hAccepts
End If

If hMethod = "POST" Or hMethod = "PUT" Then
    'Accpet HTTP request
    If hFormat = "" Then
        xhr.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    Else
        xhr.setRequestHeader "Content-Type", hFormat
    End If

    xhr.setRequestHeader "Content-Length", Len(hContents)
    xhr.send hContents
Else
    xhr.send
End If

Como ler web service XML no VB6?


Variance of a variable constructed from parameter estimates and predicted values of a linear regression

Question: My data set is an annual panel data set on individual income, the year of unemployment and a number of demographic variables. I run an OLS regression of the form
$y_{it} = \sum _{j=1} ^n D_{j,it} \beta_j + \sum_k x_k\delta_k + u_{it},$
where $y$ denotes income and $D_1,...,D_n$ are $n$ mutually exclusive dummy variables which represent the timing of unemployment. They are mutually exclusive because unemployment occurs exactly once. If, for example, $D_1$=1 and all other dummies equal 0, then the individual was unemployed 1 year earlier. The other covariates are denoted by $x_k,k=1,...,K$, which are all dummy variables as well. In addition, $i$ denotes individuals, $t$ denotes time. After the estimation I construct the variable
$c = \frac{\hat{\beta_3}-\hat{\beta_2}}{\bar{y}}$
where $\hat{\beta_j}$ is the parameter estimate associated with $D_j$, and $\bar{y}$ is the mean predicted value of $y$ for those who have $D_2 = 1$. Note that $\hat{\beta_3}-\hat{\beta_2}$ denotes the estimated difference in income between having become unemployed 2 relative to 3 years earlier. In addition, $\bar{y}$ is predicted income for individuals who became unemployed 2 years earlier. Hence, $c$ is the estimated percentage change in income from 2 to 3 years after unemployment.
My question is: How do I construct the variance of $c$? I guess the variance of the numerator must be $var(\hat{\beta_2})+var(\hat{\beta_3})-2covar(\hat{\beta_2},\hat{\beta_3})$ - but how do I construct the variance of the whole thing?
Comment: Variances of ratios can be tricky!  In particular, if $\bar{y}$ can be zero there is obvious problems.  If the probability that $\bar{y}$ is close to zero is so small that can be neglected, you could try bootstrapping (or simulation).  In that case you could also try the "delta method", that is, a linear taylor approximation and then calculate the variance in that linear approximation. But if $\bar{y}$ can be close to zero, that can be very wrong.  For a better answer, we need more details.  Give us much more information about your data and model!
Comment: @kjetilbhalvorsen Thank you! I added a few details to the post. Since I have no experience with bootstrapping I would like to use the delta method. It looks like I would need the covariance between $\bar{y}$ and $\hat{\beta_2}$ and $\hat{\beta_3}$, respectively. Do you have any suggestion how to compute this?
Comment: You can read about the method here:  http://en.wikipedia.org/wiki/Delta_method
Answer: $\DeclareMathOperator{\var}{var}  \DeclareMathOperator{\cov}{cov}   $
I will give some details of a solution using the delta method.  First, read about the delta method in http://en.wikipedia.org/wiki/Delta_method
Define the function $f(x,y)=x/y$.  We calculate the first order taylor expansion around the point $(x_0. y_0)$ as:
$$
   f_1(x,y) = x_0/y_0 +  \frac1{y_0} (x-x_0)  -  \frac{x_0}{y_0^2} (y-y_0)
$$
It can be usefull to have an idea of the percent error you are doing in using this approximation!  I will illustrate that by choosing $x_0=y_0=1.0$ and letting $x\in [0.7, 1.3],  y \in [0.7, 1.3]$.  Following is R code for making a contour plot:
<code>> f  <-  function(x,y)  x/y
> f1  <-  function(x,y,x0=1, y0=1) f(x0,y0)+(1/y0)*(x-x0) - (x0/y0^2)*(y-y0)
> X  <-  Y  <-  seq(0.7, 1.3, by=0.01)
> Z  <-  outer(X,Y,FUN=function(x,y) 100 * ((f(x,y)-f1(x,y))/f(x,y)))
> contour(X,Y,Z)
</code>
This results in the following contour plot:

You could do it yourself (with ranges relevant for your situation) to see if the percent error is acceptable!
To use this, let $x=\hat{\beta_3}-\hat{\beta_2}, x_0 = \beta_3-\beta_2, y=\bar{y} , y_0=y  (\text{that is, the true but unknown value})$ and calculate the variance in this linear approximation:
$$   \begin{align}
 \var(\frac{\hat{\beta_3}-\hat{\beta_2}}{\bar{y}} &\approx
            (\frac{1}{\bar{y}})^2 \var(\hat{\beta_3}-\hat{\beta_2}) +
             (\frac{\hat{\beta_3}-\hat{\beta_2}}{\bar{y}^2})^2 \var(\bar{y})
   - \\ &2\cdot \frac1{\bar{y}}\cdot \frac{\hat{\beta_3}-\hat{\beta_2}}{\bar{y}^2}\cdot
         \cov(\hat{\beta_3}-\hat{\beta_2}, \bar{y})
  \end{align}
$$
Now, $\bar{y}$ shoudl be a linear combination of data times coefficients, so you should be able to compute its variance from the covariance matrix of the coefficients estimates, which should be part of output.  Likewise for $ \cov(\hat{\beta_3}-\hat{\beta_2}, \bar{y}) $.
You could do a simulation study to see if this approximation is good enough!


Concatenating different "letters" or domains together, so they don't touch

Question: i will try to be short.
i need some "formula" or. a described way, how can i concat domains "together" so they dont touch?
in a example i will use letters instead of domains, i have:
A - gmail.com - 4
B - yahoo.com - 2
C - hotmail.com - 1
and thousand more

now i need some algorithm, so domains wont be together, like:
A | B | A | C | A | B | A

how can i accomplish that?

if letters must be togeter, let them be together as less as possible. another example is :
A - 10
B - 2

bad example of concat:
AAAAABAAAAAB

good example:
AAABAAABAAAA

Comment: The problem is unclear. What makes AAABAAABAAA better than AAAAABAAAAAB? For what purpose are you concatenating them? Are you trying to find the shortest unambiguous string? Or is it about distributing the letters more evenly?
Comment: hey, tnx for fast reply. rule: concat same characters as little as possible. AAAAABAAAAAB has AAAAAx2 = A10. AAABAAABAAAA has AAAx2 and AAAAx1 = 10A. in first example, they are more A's together than in second example. imagine this: 99xA and 2xB. in this example it is better to have 33A+B+33A+B+33A than 45A+B+44A+B...
Answer: If no letter is more common than all the others put together, you should have no problems. You could first fill the even positions, then the odd. Example $A=3$, $B=2$, $C=2$ then $\text{A_A_A__} \rightarrow \text{ABA_A_B} \rightarrow \text{ABACACB}$. No repetitions will occur.
If A is more common than all the others put together, repetitions are unavoidable. Say $M$ is the number of As and $N$ is the number of all other characters. There are at most $N+1$ gaps between the $N$ characters. You need to distribute $M$ into $N+1$ parts as evenly as possible. All gaps will have $\lfloor \frac{M}{N+1} \rfloor$ As except for the first $M mod (N+1)$ which will have $1$ additional A.


add pre-registered links to user menu via hook_menu

Question: One step before being forced to using internationalization (i18n) module!
I'am trying to add translatable Register and Login links to secondary menu via hook_menu in way which user module dose for Account and Logout links via user_menu():
// user module:

function user_menu(){
  ...
  $items['user/logout'] = array(
    'title' => 'Log out',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'user_logout',
    'weight' => 10,
    'menu_name' => 'user-menu',
    'file' => 'user.pages.inc',
  );
  ...
}

but as this two links (user/register and user/login) re pre-defined via user_menu(), I whould like to know how can I add my links to primary menu?
so simplified question is:
how can I add pre-registered links to menu via hook_menu() ?
Answer: You can use hook_menu_alter() to override properties for existing paths:
function MYMODULE_menu_alter(&$items) {
  $items['user/logout']['menu_name'] = 'primary-links';
}

Answer: With Clive's help, here this final code:
<?php

function MYMODULE_menu_alter(&$items) {
  $items['user/register']['menu_name'] = 'user-menu';
  $items['user/register']['type'] = MENU_NORMAL_ITEM;
  $items['user/login']['menu_name'] = 'user-menu';
  $items['user/login']['type'] = MENU_NORMAL_ITEM;
}


Extend this basis to a basis of $V$

Question: Let $\{v_1, v_2,\dots , v_r\}$ be a set of vectors that spans a subspace $W$ of a vector space $V$. Prove that one can choose a
subset of these vectors that forms a basis for $W$, and that this basis can be extended to a basis for $V$. Demonstrate
this procedure on the vectors
$$(1,-1, 0, 0), (1, 0,-1, 0), (1, 0, 0,-1), (0, 1,-1, 0), (0, 1, 0,-1), (0, 0, 1,-1).$$
I removed the non-linearly independent vectors to get the basis (here written as a matrix):
$$\begin{pmatrix} 1 & -1 & 0 & 0 \\
0 & 1 & -1 & 0\\
0 & 0 & 1 & -1\end{pmatrix}.$$
However, I'm unsure how to extend this basis to a basis for $V$. In examples of this question online, I saw people use standard basis vectors to extend a basis. Do I do that here too? I'm confused because I believe that to find the dimensions we subtract the number of linearly-independent rows from the number of columns, here that would be $4 - 3$, which would be one dimension. This is obviously incorrect? I just don't know where I've gone wrong.
Comment: The middle line of your matrix is not one of the original vectors. I suppose that's a typo (the second $1$ should probably be $0$), but I just wanted to make sure.
Answer: Once you have a basis for $W\subset\mathbb R^n$, you can extend it to a complete basis by finding the orthogonal complement of $W$. This is just the kernel of the matrix that has your basis vectors as its rows (which you've already written down). If you row-reduce this matrix, you get $\pmatrix{1&0&0&-1\\0&1&0&-1\\0&0&1&-1}$, from which you can read that the kernel is spanned by $(1,1,1,1)^T$.
Comment: @Maddie The idea here is that you decompose $V$ into $W\oplus W^\perp$. The row space of the matrix that has your basis as its rows is just $W$, and $W^\perp$, the orthogonal complement of $W$, is its null space. If you find a basis for the latter, you can extend your basis of $W$ with it to cover all of $V$.
Comment: So I choose a subset of linearly independent vectors, which is the basis of the subspace, and then by row reduction, I then get the extended basis?

Extend this basis to a basis of $V$


PlayN JBox2D Y velocity increases but collision happens

Question: So i'm seeing a really strange problem.
using the PlayN peas demo from the showcase i put together a simple app - i have a dynamic entity dropping onto a static entity and i cannot figure out why it isn't bouncing.
After doing some printouts i find that the collision is happening - the y position stays the same but the y velocity just keeps increasing
here's my update code in the dynamic entity
<code>  @Override
  public void paint(float alpha) {
    float x = (body.getPosition().x * alpha) + (previousX * (1f - alpha));
    float y = (body.getPosition().y * alpha) + (previousY * (1f - alpha));
    float w = (body.getAngle() * alpha) + (previousRotationAngle * (1f - alpha));
    if (body.m_type == BodyType.DYNAMIC) {
      System.out.println("body x = " + body.getPosition().x + ", y = " + body.getPosition().y);
      System.out.println("velocity x = " + body.m_linearVelocity.x + ", y = "
      + body.m_linearVelocity.y);
    }
    imageLayer.setTranslation(x, y);
    imageLayer.setRotation(w);
  }

  @Override
  public void update(float delta) {
    previousX = body.getPosition().x;
    previousY = body.getPosition().y;
    previousRotationAngle = body.getAngle();
  }
</code>
here's the printout - as you can see the velocity keeps going up but the y position stays the same right at 8.46
<code>  [java] body x = 17.024979, y = 0.5199691
 [java] velocity x = 0.0, y = 1.2983631
 [java] body x = 17.024979, y = 0.79601336
 [java] velocity x = 0.0, y = 2.562787
 [java] body x = 17.024979, y = 0.8908453
 [java] velocity x = 0.0, y = 2.8736944
 [java] body x = 17.024979, y = 0.99586946
 [java] velocity x = 0.0, y = 3.18255
 [java] body x = 17.024979, y = 0.99586946
 [java] velocity x = 0.0, y = 3.18255
 [java] body x = 17.024979, y = 1.1110185
 [java] velocity x = 0.0, y = 3.489367
 [java] body x = 17.024979, y = 1.2362258
 [java] velocity x = 0.0, y = 3.794159
 [java] body x = 17.024979, y = 1.2362258
 [java] velocity x = 0.0, y = 3.794159
 [java] body x = 17.024979, y = 1.3714248
 [java] velocity x = 0.0, y = 4.096939
 [java] body x = 17.024979, y = 1.5165496
 [java] velocity x = 0.0, y = 4.3977213
 [java] body x = 17.024979, y = 1.6715348
 [java] velocity x = 0.0, y = 4.696518
 [java] body x = 17.024979, y = 1.6715348
 [java] velocity x = 0.0, y = 4.696518
 [java] body x = 17.024979, y = 1.8363149
 [java] velocity x = 0.0, y = 4.993343
 [java] body x = 17.024979, y = 2.0108259
 [java] velocity x = 0.0, y = 5.2882085
 [java] body x = 17.024979, y = 2.195003
 [java] velocity x = 0.0, y = 5.581128
 [java] body x = 17.024979, y = 2.388783
 [java] velocity x = 0.0, y = 5.8721147
 [java] body x = 17.024979, y = 2.388783
 [java] velocity x = 0.0, y = 5.8721147
 [java] body x = 17.024979, y = 2.5921018
 [java] velocity x = 0.0, y = 6.1611805
 [java] body x = 17.024979, y = 2.5921018
 [java] velocity x = 0.0, y = 6.1611805
 [java] body x = 17.024979, y = 2.804897
 [java] velocity x = 0.0, y = 6.4483385
 [java] body x = 17.024979, y = 3.0271058
 [java] velocity x = 0.0, y = 6.733601
 [java] body x = 17.024979, y = 3.0271058
 [java] velocity x = 0.0, y = 6.733601
 [java] body x = 17.024979, y = 3.2586663
 [java] velocity x = 0.0, y = 7.016981
 [java] body x = 17.024979, y = 3.4995165
 [java] velocity x = 0.0, y = 7.298491
 [java] body x = 17.024979, y = 3.4995165
 [java] velocity x = 0.0, y = 7.298491
 [java] body x = 17.024979, y = 3.7495952
 [java] velocity x = 0.0, y = 7.5781426
 [java] body x = 17.024979, y = 4.0088415
 [java] velocity x = 0.0, y = 7.8559484
 [java] body x = 17.024979, y = 4.277195
 [java] velocity x = 0.0, y = 8.131921
 [java] body x = 17.024979, y = 4.5545955
 [java] velocity x = 0.0, y = 8.406072
 [java] body x = 17.024979, y = 4.5545955
 [java] velocity x = 0.0, y = 8.406072
 [java] body x = 17.024979, y = 4.840983
 [java] velocity x = 0.0, y = 8.678413
 [java] body x = 17.024979, y = 4.840983
 [java] velocity x = 0.0, y = 8.678413
 [java] body x = 17.024979, y = 5.1362987
 [java] velocity x = 0.0, y = 8.948957
 [java] body x = 17.024979, y = 5.440483
 [java] velocity x = 0.0, y = 9.217716
 [java] body x = 17.024979, y = 5.440483
 [java] velocity x = 0.0, y = 9.217716
 [java] body x = 17.024979, y = 5.753478
 [java] velocity x = 0.0, y = 9.484701
 [java] body x = 17.024979, y = 6.0752254
 [java] velocity x = 0.0, y = 9.749924
 [java] body x = 17.024979, y = 6.0752254
 [java] velocity x = 0.0, y = 9.749924
 [java] body x = 17.024979, y = 6.4056673
 [java] velocity x = 0.0, y = 10.013396
 [java] body x = 17.024979, y = 6.7447467
 [java] velocity x = 0.0, y = 10.275129
 [java] body x = 17.024979, y = 7.0924063
 [java] velocity x = 0.0, y = 10.535135
 [java] body x = 17.024979, y = 7.0924063
 [java] velocity x = 0.0, y = 10.535135
 [java] body x = 17.024979, y = 7.4485893
 [java] velocity x = 0.0, y = 10.793425
 [java] body x = 17.024979, y = 7.8132396
 [java] velocity x = 0.0, y = 11.05001
 [java] body x = 17.024979, y = 7.8132396
 [java] velocity x = 0.0, y = 11.05001
 [java] body x = 17.024979, y = 8.186301
 [java] velocity x = 0.0, y = 11.304901
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 11.55811
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 11.55811
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 11.8096485
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 12.059526
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 12.059526
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 12.307755
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 12.554346
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 12.554346
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 12.799309
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 13.042655
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 13.042655
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 13.284395
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 13.52454
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 13.7631
 [java] body x = 17.024979, y = 8.465522
 [java] velocity x = 0.0, y = 13.7631
 [java] body x = 17.024979, y = 8.465522
</code>
and here's an image - the flower was my test dynamic entity - it clearly stopped on the brick but i can't figure out why the velocity is just continuing to go up

i don't know what other code would be helpful here - i have a setup that is virtually identical to the Peas Demo from the showcase - to the point where I've deleted things from the Showcase demo and can't recreate the problem in that.
I am 100% at a loss here and since it's a physics problem it's kind of hindering all my progress.  The peas demo completely works
Any help would be greatly appreciated - i have tried for 4 hours now trying all the things i can think of and nothing is working

edit added main world class (this is definitely pretty ugly - please don't judge me)
<code>public class LevelWorld implements ContactListener, Paintable, Updatable, Destroyable {

  private static final float PHYSICS_UNITS_PER_PIXEL = PhysicsScale.PHYSICS_UNITS_PER_PIXEL
  .getScaleFactor();

  private final playn.core.GroupLayer worldLayer;

  private final Context context;
  private final World world;
  private final float frameRate;

  private final List<playn.core.GroupLayer> groupLayers;
  private final List<Entity> entities;
  private final Stack<Contact> contacts;
  private final Map<Body, PhysicsEntity> bodies;

  public LevelWorld(Level level, Context context) {
    worldLayer = graphics().createGroupLayer();
    worldLayer.setScale(1.F / PHYSICS_UNITS_PER_PIXEL);
    this.context = context;
    final Integer fps = (Integer) context.get(FPS);
    this.frameRate = 1.F / fps.floatValue();
    final Vec2 gravity = new Vec2(0.F, 10.0F);
    world = new World(gravity, true);
    world.setWarmStarting(true);
    world.setAutoClearForces(true);
    groupLayers = new ArrayList<playn.core.GroupLayer>();
    entities = new ArrayList<Entity>();
    contacts = new Stack<Contact>();
    bodies = new HashMap<Body, PhysicsEntity>();
    for (final GroupLayer groupLayer : level) {
      final playn.core.GroupLayer gl = graphics().createGroupLayer();
      gl.setDepth(groupLayer.getDepth());
      gl.setScale(groupLayer.getScaleFactor());
      groupLayers.add(gl);
      for (final Entity entity : groupLayer.getEntities()) {
        if (entity instanceof PhysicsEntity) {
          final FixtureDef fixtureDef = new FixtureDef();
          final BodyDef bodyDef = new BodyDef();
          if (PhysicsType.DYNAMIC.equals(entity.getEntityMetadata().getPhysicsType())) {
            bodyDef.type = BodyType.DYNAMIC;
          } else if (PhysicsType.STATIC.equals(entity.getEntityMetadata().getPhysicsType())) {
            bodyDef.type = BodyType.STATIC;
          }
          final Body body = world.createBody(bodyDef);
          fixtureDef.shape = entity.getEntityMetadata().getShape();
          fixtureDef.density = 0.4f;
          fixtureDef.friction = 0.1f;
          fixtureDef.restitution = 0.5f;
          body.setLinearDamping(0.2f);
          body.createFixture(fixtureDef);
          body.setTransform(new Vec2(entity.getPosition().x, entity.getPosition().y),
          entity.getRotationAngle());
          ((PhysicsEntity) entity).setBody(body);
          bodies.put(body, (PhysicsEntity) entity);
        }
        gl.add(entity.getImageLayer());
      }
      entities.addAll(groupLayer.getEntities());
      worldLayer.add(gl);
    }
    graphics().rootLayer().add(worldLayer);
    world.setContactListener(this); // kinda sketchy
  }

  @Override
  public void beginContact(Contact contact) {
    System.out.println("BEGIN CONTACT HAPPENED");
    contacts.push(contact);
  }

  @Override
  public void endContact(Contact contact) {

  }

  @Override
  public void preSolve(Contact contact, Manifold oldManifold) {

  }

  @Override
  public void postSolve(Contact contact, ContactImpulse impulse) {

  }

  @Override
  public void destroy() {
    worldLayer.destroy();
  }

  @Override
  public void update(float delta) {
    // worldLayer.setOrigin(worldLayer.originX() + (delta / 250.F),
    // worldLayer.originY());
    for (final Entity entity : entities) {
      entity.update(delta);
    }
    world.step(0.033F, 10, 10);
    // processContacts();
  }

  @Override
  public void paint(float alpha) {
    for (final Entity entity : entities) {
      entity.paint(alpha);
    }
  }

  private void processContacts() {
    while (!contacts.isEmpty()) {
      final Contact contact = contacts.pop();
      final PhysicsEntity a = bodies.get(contact.m_fixtureA.m_body);
      final PhysicsEntity b = bodies.get(contact.m_fixtureB.m_body);

      if (a != null && b != null) {
        if (a instanceof PhysicsEntity.IsContactListener) {
          ((PhysicsEntity.IsContactListener) a).contact(b);
        }
        if (b instanceof PhysicsEntity.IsContactListener) {
          ((PhysicsEntity.IsContactListener) b).contact(a);
        }
      }
    }
  }
}
</code>
Comment: The collision handler is yours? If so, can we see it?
Comment: To tell you the truth like I said I modeled everything off of the Peas demo - they have a processContacts method in the PeaWorld class - I found commenting this out that the entities still bounce so right now I honestly don't think I have a collision handler - That being said I'll edit the post and add my World class
Comment: Perhaps you're supposed to implement a collision handler for custom objects.
Answer: In case anybody runs into this - After a whole day and a half of trying to figure this out and creating a separate simple project dropping 1 dynamic entity onto a static entity and seeing it do the same thing.
If you see this happen where the Entity stops moving but the velocity keeps increasing - the Collision Shape you put in is BACKWARDS - i had 4 vertices being put into the shape in order of 0,1,2,3 - had I put them in as 3,2,1,0 it would have worked fine. I suppose if you hit this same type of problem try reversing the order your creating your shape and see if the collision works.
Comment: Or reverse your collision test.  Thats the big thing with insideness, you have to make sure the edges are oriented correctly, or you have to use a test that doesn't depend on it, which may be slower.
Comment: It's helpful to use Box2D's debug draw feature to see exactly what the physics engine is seeing. Chances are the polygon would not look right in debug draw which would tip you off straight away.


Arithmetic Progression of a book

Question: Given that a book starts on page 1, and is numbered on each page
a) Show that the first eleven pages contain 13 digits
b) If total number of digits is 1260, how many pages are in the book?
So, If it starts on page 1, that means $U_1=1$ and $U_n=n$
But what Im trying to figure out is what the formula for
$U_{digits}$ would be.
I tried making a chart, to see the correlation between the set of pages and the set of digits, and noticed that, up to 9 it is $n+1$. After $10$ until $99$ it is $n+2$. After $100$ until $999$ it is $n+3$
How would I go about doing this?
Answer: There are $9$ single-digit positive integers, $99 - 9 = 90$ two-digit positive integers, and $999 - 99 = 900$ three-digit positive integers.  The nine pages numbered with a single digit have $9 \cdot 1 = 9$ digits on them.  The $90$ pages numbered with two digits have $90 \cdot 2 = 180$ digits on them.  Thus, at the end of the first $99$ pages, we have encountered a total of $9 + 180 = 189$ digits.  Each page numbered with a three-digit integer has three digits on it.   Since $9 + 90 \cdot 2 = 189 < 1260 < 9 + 90 \cdot 2 + 900 \cdot 3 = 2889$, the number of pages in the book must be a three-digit positive integer.  Since $1260 - 189 = 1071$, there must be $1071$ digits on pages numbered with three digits.

 Since $1071 = 3 \cdot 357$, the book must contain $357$ pages with three-digit numbers, the smallest of which is $100$. Thus, there are $356$ pages in the book numbered larger than $100$, so the book has $456$ pages.
Comment: Ok, Thank you !
Comment: +1, random trivia: Question 1 of the 1947 Stanford high school maths entrance comp (am not that old but got it from [this](https://www.amazon.co.uk/Stanford-Mathematics-Problem-Book-Solutions/dp/0486469247)!) had 1890 digits needed to number a 'bulky volume'. The choice of course results in a devilish 666 pages required, wonder if that raised a few eyebrows back then!
Answer: (My first time posting an answer. I'm open for any critiques)
Note: We know the number of digits end in the range of a three-digit number because
pages $\;$ $1$ - $9 = 9$ $\;$ pages and digits ($1\,$- digit)
pages $\;$ $10$ - $99 = 90$ pages $*\;2 = 180$ digits (with $2\,$- digits)
pages $\;$ $100$ - $999 = 900$ pages $*\;3 = 2,700$ Digits (with $3\,$- digits)
The total number of digits from the question only goes up to 1260. Therefore, we know the answer ends in the $3$ - digits range.
$9 + 90\cdot 2 + (n-99)3 = 1260$
$  \;9 + 90 \cdot 2\; = 189$ (both one digits and double-digits)
$ \; (n-99)3 = 1260 - 189$
$=\;3n - 297 = 1071$
$3n = 1368$
$ n = 456$ pages
Comment: Welcome to MSE.  Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to format both, your questions and your answers :)
Comment: Noted, and thanks!
Comment: You have not explained why we know that the number of pages in the book is a three-digit number.  Doing so would justify your correct solution to the problem.
Comment: 1 - 9 = 9 digits in total
10 - 99 x 2  = 189 digits in total
100 - 999 = 900 with three digits, and multiply 900 with 3 = 2,700
Since the question refers to 1260 number of pages, we can already assume that the number of digits end in the three - digit number.
Comment: Sorry my answer above looks rather messy, I thought I indented them. But if this answers what you mean, I'll reedit my post. EDIT: Since the question refers to 1260 number of digits,
Comment: I think everything after "Note" in your answer, explains why you only have 3 digit pages, but also the formula you use to find 456. IMHO, your answer would be way more clear if it was at the begining. Anyway, welcome to MSE!
Comment: Also, I initially upvoted your answer, but I had to take it back because of the messy use of $=$ sign. You can't write things like "$3n−297=1071=3n=1368$", it burns the eyes of mathematicians. I'll suggest an edit to your answer, feel free to accept or reject it
Comment: Understood, and thanks for the critiques
Comment: You're welcome. To summarize all my critics about your initial answer, I would say that you should focus a bit more on explaining how to get the result, and less on what is the result. You'll find that quite a lot of accepted/best voted answers on this site are just hint on how to solve rather than full numerical solutions.

Arithmetic Progression of a book


Add a button in user orders view requesting info about current order Drupal Commerce 7

Question: I have an automated e-shop in Drupal 7 and drupal commerce.
I am trying to add an action button in user orders view, which on "pressing" by every current user is sending email(alert with replacement tokens about current selected order) to administrator of eshop.
Any ideas to implement action button?
I tried VBO and Views Send modules but i didn't succeded.
Answer: You can use the Rules module.

Create a component with the Action Send mail. Use tokens to customize the subject and message body as you like.
Edit the view and use VBO to trigger the rules component.
Comment: Thats it.Thanks! I would need also  in user orders view in each row a button for every row to achieve above function(VBO provides only one button and checkboxes to each order).


whole array printing instead of a single value within it

Question: I need to be able to read in a word from a file one at a time and then be able to sort the text into a struct to track how many times words have been repeated however whenever I try to point to a specific word in the file I'm getting the whole file value instead of the specific word I'm trying to retrieve. apologies if the solution is simple, I still struggle with the different types of pointers and file commands
#include <stdlib.h>
#include <stdio.h>

char *inputFilename;
char *outputFilename;

char inputText[5000];
char outputText[5000];

int inputFlag;
int outputFlag;

int readfile(char **data){

    FILE *input;
    input = fopen(inputFilename, "rb");
    int len = sizeof(*input);

    printf("input length is %d\n", sizeof(char));

    //First value is number of integers
    int size;
    fread(&size, sizeof(char), 0, input);

    //allocate memory for that number of values
    *data = (char*)malloc(sizeof(char) * size);

    //Read in rest of data
    fread(*data, sizeof(char), size, input);

    //return size
    printf("size is %d\n", size);
    return size;
}

int valueSearch(char *vData, int argCount, char **argv){

    for(int argLoop = 0; argLoop < argCount; argLoop++){

        //If vData is detected then the next argument is the input file name
        if(strcmp(argv[argLoop], vData) == 0){

            return argLoop + 1;

        }
    }
    return 0;
}

int main(int argc, char **argv){

    char *data;

    inputFlag = valueSearch("-i", argc, argv);

    printf("input flag is %d\n", inputFlag);

    inputFilename = argv[inputFlag];

    if(inputFlag == 0){

        printf("Please enter the text you would like to sort: ");

        fgets(inputText, 5000, stdin);

    }
    else{

        int size = readfile(&data);

    }

    int i = 0;

    //Value that should be placed into struct
    printf("readfile value 0:\n%s\n", data[i]);

    free(data);

    return 0;

}

Comment: Are you able to compile it ?
Answer: Your last printf uses %s instead of %c. %s treats the argument as a pointer to a string (char array), and prints each byte until it encounters a byte of 0. You want %c, which prints out a single char.
Comment: that's what I'm trying to do. I need to be able to select a whole word from the file then be able to compare it to ones saved in the counting struct im going to add like I have done with the inputFilename using the valueSearch function and argv[inputFlag] on line 58. essentially im trying to read from my file the same as i would the argv
Answer: Use %c instead of %s because %s is a identifier of string and that will print whole string.
 printf("readfile value 0:\n%c\n", data[i]);

Hopefully it will work for you.
Answer: You need to become familiar with compiling with compiler warnings enabled, and then do not accept code until it compiles without warning or error.
You invoke Undefined Behavior on line 19 and again on line 76 by using improper conversion specifiers for int (instead of long int - line 19) and again as already noted on line 76 where you use %s instead of %c.
Further, you do not include string.h which is required for the use of strcmp on line 41. There is no declaration for strcmp so your compiler makes a guess at an implicit declaration.
You will also find unused variables len and size in your code. (lines 17 and 69, respectively).
All of these problems are readily apparent from your compiler output if you compile with -Wall -Wextra (and if wanted -pedantic) on gcc, with -Weverything on clang, or /Wall with VS (cl.exe) (you may want /W3 on VS as /Wall means all (and you will have to individually disable a handful of warning there with /wdXXXX where XXXX is the code for the warning you wish to disable).
While not an error, the standard coding style for C avoids the use of camelCase or MixedCase variable names in favor of all lower-case while reserving upper-case names for use with macros and constants. It is a matter of style -- so it is completely up to you, but failing to follow it can lead to the wrong first impression in some circles.
Moral of the story -- (1) enable compiler warnings, and (2) do not accept code until it compiles cleanly -- without warning. Letting your compiler help you write better code will eliminate a large percentage of the errors you spend time chasing :)


Why do I get the error "error: unknown type name 'virtual'" when trying to compile this code?

Question: Code:
<code>struct IRenderingEngine {
    virtual void Initialize(int width, int height) = 0;
    virtual void Render() const = 0;
    virtual void UpdateAnimation(float timeStep) = 0;
    virtual void OnRotate(DeviceOrientation newOrientation) = 0;
    virtual ~IRenderingEngine() {}
};
</code>
Learning opengles from a book for 3d iphone programming and it uses this example code but the book is targeted for xcode 3.x
Somehow I feel like its something with xcode 4....
EDIT:
Heres the actual error:
/Users/Dan/Documents/opengles/Hello Arrow/Hello Arrow/IRenderingEngine.hpp:27:2: error: unknown type name 'virtual' [1]
And that legitamtely is all that it takes to fail to compile, absolutely no other files. (Yes I've tried compiling with literally a main.m and this hpp file)
It is recognizing the hpp file as a cpp header file though, if I try to add it to the compiled files it says that "no rule to process file '$(PROJECT_DIR)/Hello Arrow/IRenderingEngine.hpp' of type sourcecode.cpp.h for architecture i386" so I really have no idea what is going on
Note that I compiled with main.m meaning I compiled another Cocoa/Foundation based application
I tried compiling for a c++ application and everything worked out just fine....
Similarly compiling with a main.mm test file worked fine too
heres the actual project, lemme know how insane I really am:
[Removed considering I lost the file]
Comment: Post an SSCCE. I can't help you with this code, it's obviously not the actual source of the problem.
Comment: http://pastie.org/private/07cebz0irqp6ehybicctw is literally the entire file and it will not compile. just throws the error: unknown type name 'virtual' [1]
Comment: What do you mean a `main.m`? C++ does not use `.m` files. Use a `.cpp`
Comment: I compiled a cocoa application which uses .m files
Comment: It's not Objective-C++ unless you use .mm
Comment: didn't think about that but if I compile with a main.mm file for the test app it works - still doesn't explain why I can't import a hpp to a regular .h file
Comment: so thanks Daniel, turns out you can't include from a normal c header only from other files that understand c++
Comment: I had same issues.I had renamed the "AppDelegate.m" to "AppDelegate.mm",but it doesn't work for me.There is no main.m file in my project.
Comment: I had similar problems, but then i replaced all the .m with .mm Although the screen is all grey and theres no arrow. If you have resolved the problem, could you kindly upload the files?
Answer: Please rename the main.m to main.mm. This worked for me.
Comment: I had to rename both main.m and AppDelegate.m with the .mm extension.
Comment: To get this example working in xcode 4 I also had to get delete the MainStoryboard_iPhone.storyboard and MainStoryboard_iPad.storyboard files as well as remove their references from HelloArrow-Info.plist, but the errors for those were much clearer.
Answer: If you're using Xcode 4, try changing the name of file "AppDelegate.m" to "AppDelegate.mm". It works for me.
Answer: Changing the name of file "AppDelegate.m" to "AppDelegate.mm". It's correct!
Answer: I moved the #import "IRenderingEngine.hpp" line from the GLView.h file to the GLView.mm - this prevented it from being imported into the main.m and HelloArrowAppDelegate.m files when they were compiled - and restricted the import into the .mm file, that could handle the C++.
I also had to make a couple of other fixes for bugs I'd introduced when typing in the code - so apologies if that wasn't the only thing that needed to be done, but it might help those with similar problems!
Comment: This worked for me! Very simple solution, just move all of your instance variables into the @implementation.
Answer: if you call C++ files ( even if you only import them ) you need to change the .m file that call's it to .mm
Answer: This is just a stupid guess since I've never tried compiling something with the word virtual in a C compiler... but is there any chance that you were trying to compile this C++ code as C code?  That's the only reason I can think of that a compiler wouldn't understand the keyword virtual.
Comment: supposedly xcode is compiling the files based on their file types (which this one happens to be hpp so I'm guessing it's smart enough to know that that means it's cpp)
Answer: The header <stdlib.h> is not the right one to use in a C++ program.  When I replaced it with the c++ version of C's stdio library <cstdlib> then your code compiled for me.
Comment: when I try adding that to the header it errors that it can't find that file


Function prints value but returns "None"

Question: def findLineParam(sprotParam, pos):

    if line[:2] == sprotParam:
        start = pos
        while line[start] == " ":
            start += 1
        stop = start + 1
        while stop < len(line) and not line[stop] in (" ", ";"):
            stop += 1
        print(line[start:stop]) # prints the correct value!
        return line[start:stop] # returns None?

To briefly explain the function of the code is that it should take an input string (keyword), e.g. "ID" and find this on a line in a text file then it should find the first value after white space reading to next " " or ";" and return this. I can see that when I print the line, it returns exactly what I want but when I return it, it returns "None".
Whenever I change the "sprotParam" to an input list instead (*sprotParam) it does return the values but also an equal amount of "None" corresponding to the lines in the file, which I believe indicates, that it iterates and performs operations on all lines, which it shouldn't.
Code calling the function
try:
    file = input("Enter filename: ")
except IOError as e:
    print("That is not a recognised filename. Error given: " + str(e))
    sys.exit(1) # Close the program

with open(file, 'r') as infile:
    for line in infile:
        ident = findLineParam("ID", 2)

Comment: Please add the code that calls the function.
Comment: I have a much easier solution to your problem, but I am not *exactly* sure what you are trying to accomplish with your code.  Can you provide example file data, and your expected outcome?
Comment: Hi, @Phintac did you find a solution to the problem. I'm facing this currently and the answers on this post do not help.
Answer: line isn't within the function's scope, so you need to pass it to the function as an argument:
def findLineParam(sprotParam, pos, line):
    if line[:2] == sprotParam:
        start = pos
        while line[start] == " ":
            start += 1
        stop = start + 1
        while stop < len(line) and not line[stop] in (" ", ";"):
            stop += 1
        print(line[start:stop]) # prints the correct value!
        return line[start:stop] # returns None?

with open(file, 'r') as infile:
    for line in infile:
        ident = findLineParam("ID", 2, line)

Update
Here is a simplified version of your code:
def findLineParam(sprotParam, file):
    for line in file.split(sprotParam):#split by parameter
        if line != '<':
            for item in line.split(): #split by whitespace
                if item != '=':
                    print(item)
                    return item

    raise Exception(f'No {sprotParam} parameters were found in the given file')

file = 'test.txt'
with open(file, 'r') as f:
    ident = findLineParam("ID", f.read())

Now, if you run this for test.txt:
<ID= 'foo'    >

asdfnewnaf

It will return 'foo'.
Comment: Hi Caleb, thank you for your comment, I tried incorporating your suggestion but it still returns "None" :(
Comment: @Phintac Added an update.  Let me know if isn't what you want.
Answer: As @NoxFly suggested all paths doesn't return.
def findLineParam(sprotParam, pos, line):
    ret = ''
    if line[:2] == sprotParam:
        start = pos
        while line[start] == " ":
            start += 1
        stop = start + 1
        while stop < len(line) and not line[stop] in (" ", ";"):
            stop += 1
        print(line[start:stop]) # prints the correct value!
        ret = line[start:stop] # returns None?
   return ret

with open(file, 'r') as infile:
    for line in infile:
        ident = findLineParam("ID", 2, line)

A much better approach will be to use regex instead of those while loops.
for example the regex will find the value.
r"ID:([^(\s|;)]*)"

Answer: if your function must return something, you should return a default value (you only are returning on a if statement, so if you don't matche this if, you return None)
I know it's not solving you problem but it's better to get this ^^
Comment: But in that case, it was also not supposed to print anything
Comment: yeah it's why I'm saying it's not solving the problem. I should just "add a comment" instead of giving an "answer", right


How do I access a custom field from an action?

Question: I want to access a custom field names field_heat in a Rules action in D8 and it does not accept it. This is my condition:

And this is my action which cannot be accepted:

If I use a build field like node.title.value it works OK so the problem must be with custom fields. I am using Rules 8.x-3.0-alpha1.
Comment: In D7 you could use a condition of "entity has field" or something like that to bring fields into scope that were otherwise missing. Do you have the same option?
Comment: The option is there but I haven't managed to come up with a working configuration.
Answer: Preface
Be aware of what's written in comment nr 7 of issue nr 2574691:

rules 8.x-3.0-alpha1 ... is a preview release and is not intended for production sites. Use at your own risk.

With that in mind, read on for more details to do a similar experiment with rules 8.x-3.0-alfa1.
Verify setup of content type and field

I'll use content type "Article", which already has a field with machine name "field_image" (out of the D8-box).
Navigate to /admin/structure/types/manage/article/fields to verify this.

Create a rule

Enable the Rules module.
Navigate to /admin/config/workflow/rules and create a new rule, with these details:

Use Rules Event "Before saving content"
Add a Rules Condition like "Entity has field" (for the field_image field). To do so, click on "Value" (within the "Entity" box), and select node. And also click on "Value" (within the "Field" box), and select field_image. Then click the Save button (to save the Rules Condition).
Add a Rules Action "Set a data value",and continue like so: click on "Value" (within the "Data" box), and select node:field_image:value (note that for this Data Selector I'm using : (twice), instead of . (twice) as in your screenprint). And also enter some "Value" (within the "Value" box), eg myNiceImage. Then click the Save button (to save the Rules Action).
You are then returned to the "edit rules reaction" screen (for the rule you are editing. And it shows a message like "You have unsaved changes.". Click the Save button (to save the rule). Then a message will be shown like "Reaction rule ABC has been updated." (ABC = the label you gave to your rule).

Verify if the rule got saved

Navigate to /admin/config/workflow/rules to ensure the rule was really saved (that it does show up there).
Navigate to admin/config/development/configuration/single/export and as "Configuration type" select "Reaction Rule". Then select the label of your rule as the "Configuration name".
You should then see the exported rule, which should look similar to mine, i.e.:
uuid: ab289332-0b45-484f-a1ae-38842620b7e4
langcode: en
status: true
dependencies: {  }
id: check_a_field_before_saving_a_node
label: 'Check a field before saving a node'
events:
  -
    event_name: 'rules_entity_presave:node'
description: ''
tags:
  - ''
config_version: '3'
expression:
  id: rules_rule
  uuid: 354332c5-8307-4097-b33c-0e77307a5e0e
  conditions:
    id: rules_and
    uuid: e82407a4-05c6-45d3-8195-1c1b5f34a07d
    conditions:
      -
        id: rules_condition
        uuid: 3c9094ed-95ec-4202-8398-5a6ca000604a
        context_values:
          entity: node
          field: field_image
        context_mapping: {  }
        context_processors: {  }
        provides_mapping: {  }
        condition_id: rules_entity_has_field
        negate: false
  actions:
    id: rules_action_set
    uuid: 3313095c-f75a-46f2-8d11-f845d12a90f2
    actions:
      -
        id: rules_action
        uuid: 23a3a68e-893e-48c4-a7ee-102201af5a25
        context_values:
          data: 'node:field_image:value'
          value: myNiceImage
        context_mapping: {  }
        context_processors: {  }
        provides_mapping: {  }
        action_id: rules_data_set

The above export should illustrate that I could perfectly save this ... because otherwise I could not have exported it, right?

Pushing the limits
So far so good, but next I wanted to update the value to be assigned in my Rules Action, let's say myNiceImage should be updated to myNewestNiceImage. So I returned to my Rules Action, and started to edit it. But, that resulted in an error message like so:

The context Data may only be configured using a selector.

By clicking on the Switch to data selection button (so that the button label changed to Swith to direct input mode), and trying again, I got another error message like so:

Data selector node:field_image for context Data is invalid. Unable to get variable node:field_image, it is not defined.

There has to be a way to do it ...
So it seems like updating a Rules Action is not what you should try to do (at least not in the current D8 release of the Rules module).
However, here are the steps I performed to actually get the value updated (from myNiceImage to myNewestNiceImage) anyhow:

delete the Rules Action (with the old value myNiceImage).
create a new Rules Action (with the new value myNewestNiceImage).

Voilà!
PS: did you notice I'm using "Entity has field", and not "Entity is of type"?
Comment: Thanks for the detailed answer. I replicated your steps, basically doing the same thing that I always did, but I ended up with a WSOD and error: Recoverable fatal error: Argument 1 passed to Drupal\rules\Plugin\Condition\EntityHasField::doEvaluate() must implement interface Drupal\Core\Entity\FieldableEntityInterface, string given in Drupal\rules\Plugin\Condition\EntityHasField->doEvaluate() (line 47 of /home/drlz1/www/sites/default/modules/rules/src/Plugin/Condition/EntityHasField.php).

I have double-checked by testing on http://simplytest.me as well. Which Drupal version are you using?
Comment: I have a hard time replicating. Can you share some screenshots or more detailed settings?
Comment: I cannot create the \entity has field' condition. Trying to use 'node:field_image:value' I get an error message 'Data selector node:field_image:value for context Field is invalid. Unable to get variable node:field_image:value, it is not defined.'

Note that I have entered 'node' as entity data selector.
Comment: @FotisDimanidis : your turn again ... see my updated answer ...
Comment: @FotisDimanidis : I used the "latest and greatest D8 version, ie alfa1" (there is no more mature version). You didn't specify what you did prior to getting that WSOD. But as per your "*I replicated your steps*" I assume that WSOD occured when trying to execute the rule afterwards. In that case, I'd suggest you create a followup question (maybe with a reference to this question). And also mark this answer as accepted?
Comment: Yes when saving the article you get this error. It's pretty easy to replicate. Actually I was asking which Drupal core version are you using.

Marking you answer as the right one as I believe it should work if Rules wanted to cooperate. Thank you.
Comment: @FotisDimanidis : merci for the accept! FYI : The Drupal (core) version I used was pretty sure the same as yours ... since I also did an experiment on simplytest.me ... (so whatever the core version was the day I did my experiment). And because of your last comment (= you get this error when saving), I think you should create an issue for that on D.O (if no such issue exist yet).
Comment: Issue here: https://www.drupal.org/node/2776109
Answer: Looks like to get access to a Content Type fields the condition needed is 'Entity is of bundle' as stated in this issue comment, and fill it with:

Entity: node
Type: node
Bundle: Your content type machine name
Answer: I have received the same error. What I have done is:

Go to configuration sync (Configuration > development > configuration synchronisation)
Export single item: Reaction rule > YOUR RULE. Copy the generated text.
Delete the previous rules you have built
Import single item: Reaction rule > Paste the generated text. This time, change the value of the field by hand, that the rule was not accepting previously.
If you constructed the structe correctly, the rule works.


Warm Standby with Windows Server 2003

Question: We have a primary file server for our Windows Server 2003 (Standard Edition) domain.  We're running active directory in a plain vanilla type environment.  When we recently migrated from an old server to a new one, I set up a DNS entry as Files.OurDomain.local as an Alias (CNAME) to the real server name.  I disabled Strict Name Checking (see MSDN link text).  All client machines now refer to \\Files or \\Files.OurDomain.local to get to their files.  No one ever uses RealServer.OurDomain.local. Printers also use an alias to get to their server.
I plan to use this setup in the event of a significant server problem to switch the dns alias to another server as a poor man's warm standby.  Also it should make server migrations in the future very easy.  I tried DFS but it didn't give me the comfort that I had exact control over where files were going.  The default TTL (Time to Live) for the DNS entries is 1 hour.  That's probably what it would take the tech staff to determine that the server had been lost and we would really need to switch to the backup.
Any concerns or problems (or even accolades) with this approach?
Comment: You should be able to accomplish better solution with DFS replication.
Comment: I tried DFS but when I faked caused a server to fail and then brought it back on line it wasn't easy for me to figure out where the files were being changed.  I want to control which server is really the master.
Answer: It seems like you're handicapping yourself by not just using DFS or Clustered File Sharing.
http://support.microsoft.com/kb/284838
Comment: I think the clustering requires enterprise and I should have said we have a few Standard Edition versions of Windows server 2003.

Warm Standby with Windows Server 2003


PHP: Add difference from two DateTime object to another date using DateTime::modify

Question: How do I add the difference between two DateTime objects to another DateTime object? I tried some code similar to the one below, but it didn't work.
$first_time=new DateTime('01/01/2000 00:00:00');
$second_time=new DateTime('01/01/2000 00:00:50');
$diff=$first_time->diff($second_time);
$time=new DateTime('01/01/2012 12:00:00');
$time->modify('+'.$diff->format('%s').' seconds');
echo $time;
//Should echo: "01/01/2012 12:00:50"

Can somebody help me out?
Comment: What is the actual output of the echo?
Comment: If you use PHP5.3 or newer you can use DateTime::add otherwise DateTime::modify. See my answer for DateTime::modify()
Answer: format() does not calculate the absolut number of seconds of the Interval, it just give you the values of the intern attributes. Since you want to add, why not simply use add()? diff() returns a DateInterval object, and this is what add() needs.
$first_time=new DateTime('01/01/2000 00:00:00');
$second_time=new DateTime('01/01/2000 00:00:50');
$diff=$first_time->diff($second_time);
$time=new DateTime('01/01/2012 12:00:00');
$time->add($diff);
echo $time;

Comment: `DateTime::add()` is not available in PHP5.2. Thats why OP whants it with `DateTime::modify()`. See the notes [here](http://www.php.net/manual/en/datetime.add.php#refsect1-datetime.add-notes).


Fechar a pagina webView depois de carregar

Question: Estou utilizando a webView no iOS para acessar uma página web dentro de um aplicativo nativo utilizando a linguagem objective-c como no exemplo a seguir:
NSURL *url = [NSURL URLWithString:@"http://www.exemplo.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_webView loadRequest:request];

Porém eu gostaria que a página depois de carregada completamente se fechasse automaticamente sem a necessidade do usuário interferir. Eu ja procurei na documentação do NSURL, porém não encontrei algo que me ajudasse nessa questão.
Answer: Primeiro, acrescente em seu arquivo de cabeçalho .h a classe delegate referente ao UIWebView:
@interface WebViewController : UIViewController <UIWebViewDelegate>

E assim, na implementação defina a propriedade do seu UIWebView:
[_webView setDelegate:self];

E por fim, o método delegate que irá realizar a ação que você desejar, assim que a página for carregada:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    // Ação ao carregar página...
}

Por "fechar a página", eu não entendi bem qual exatamente esta ação que você deseja, mas acredito que a partir deste método você pode definir.
Comment: Dexia eu ver se entendi, no momento em que o método *webViewDidFinishLoad* é chamado, quer dizer que o carregamento da página terminou? Exemplificando, se tenho uma imagem na página em que estou acessando, esse método será chamado quando toda imagem for carregada na página?
Comment: @JonathanGonczoroski, esse método será chamado quando a página inteira for carregada, se por um acaso, essa página só for uma imagem, quando acabar de carregar a imagem ele será chamado.
Answer: Além de usar o método delegate da webView : webViewDidFinishLoad
- (void)webViewDidFinishLoad:(UIWebView *)webView {
     // Ação chamada ao terminar de carregar a página...

    // Recomendo adicionalmente uma ação para ser executada automaticamente após alguns segundos depois de carregada a pagina, seja para ocultar a webview ou apresentar uma mensagem ao usuário dizendo que foi com sucesso.
    [self performSelector:@selector(hideWebView) withObject:nil afterDelay:2.0];
}

Use também o método do delegate para tratar as situações de erro de carga da página!
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    //Trate os possíveis erros da carga da url aqui.
}


Building APK and getting 4 folders instead of the APK file

Question: Building an APK file from a project inside the Android Studio, normally I get the output folder with .apk file inside it, but in this particular case, instead of the APK file, I'm getting 4 folders:
generated
intermediate
outputs
temp
Altogether, they hold the weight of what I'd expect the APK file to be. Is there any way to get the APK out of this project?
Comment: you will find apk from this path: /app/build/outputs/apk.

If the apk is not there then run your project once again.
Comment: Thank you, unfortunately I can't mark the comment as the solution.
Comment: Welcome buddy :)
Answer: Please share your build.gradle file . i think there is mistake with this file thats why its not creating build.gradle file.
According to Build Unsigned APK with Gradle you can simply build your application with gradle. In order to do that:
click on the drop down menu on the toolbar at the top (usually with android icon and name of your application)
select Edit configurations
click plus sign at top left corner or press alt+insert
select Gradle
choose your module as Gradle project
in Tasks: enter assemble
press OK
press play
Answer: "you will find apk from this path: /app/build/outputs/apk. If the apk is not there then run your project once again." – Ronak Thakkar


Copiar celulas ao identificar alteração Worksheet_Change (Excel VB)

Question: Sou novo em VB e estou tentando fazer com que seja executada uma operação que copia algumas informações da planilha "Controle Backup Clientes" para a planilha "LOG".
O processo será assim:
o Excel ao detectar alteração em qualquer célula da coluna N da planilha "Controle Backup Clientes", deveria copiar o respectivo valor da coluna A (chamada codigo cliente) e colar na próxima linha em branco da planilha "LOG", onde ficara registrado todas as alterações feitas.
Abaixo segue o código que fiz, porém toda vez apresenta erro de "Objeto Obrigatório" e não consigo achar o problema
Dim celChave As Range
Dim codCliente As Long

Private Sub Worksheet_Change(ByVal Target As Range)

    'celChaves onde fica guardado as celulas que serão alteradas
    Set celChave = Sheets("Controle Backup Clientes").Range("N2:N1048576")

    If Not Application.Intersect(celChave, Range(Target.Address)) _
           Is Nothing Then

        codCliente = Sheets("Controle Backup Clientes").Select(0, 1)
        Sheets("LOG").Select(1048576, 1).End(x1Up).Offset(1, 0).Paste
        Application.CutCopyMode = False
        Sheets(Sheets("LOG").Select(1048576, 1).End(x1Up).Offset(0, 1)).FormulaR1C1 = "=TODAY()"
        Sheets(Sheets("LOG").Select(1048576, 1).End(x1Up).Offset(0, 2)).Paste = codCliente

        MsgBox "CORREÇÃO SALVA NO LOG! CELULA (" & Target.Address & ")"

    End If
End Sub

Comment: Veja [esta resposta](https://pt.stackoverflow.com/a/255233/75104), evite [o uso do select](https://stackoverflow.com/a/10717999/7690982) e em qual linha o erro é apresentado?
Comment: Outro detalhe: `Range(Target.Address)` parece-me uma redundância, pois `Target` já é uma `Range`. Além disso, como Daniel já pontuou, é essencial dizer em que linha o erro aconteceu. Rodei aqui no Excel e só deu erro nos `Selects`, por causa da sintaxe inválida, mas não foi objeto obrigatório (foi chamada ruim de método).
Comment: Obrigado @danieltakeshi pela dicas, me ajudou muito!
Answer: Salve,
Depois de muita pesquisa e estudo, consegui resolver meu problema. Vou explicar mais detalhado o problema e a solução.
Tenho duas planilhas, uma Clientes(trago essa listagem de um banco em SQL), onde tem os dados gerais do cliente(codcli, nome, cnpj, etc), e a outra é a planilha Log.
O que ocorre é que na planilha Clientes eu tenho a coluna N onde insiro uma data, referente a que dia o problema do cliente foi corrigido. O que eu precisava era que quando fosse inserido esta informação na coluna N, iria pegar o código do cliente(coluna A) da respectiva linha, data de hoje(Now), o valor inserido na celula da coluna N e o usuário, ir para a planilha "LOG" e gravar as informações na respectiva sequencia a partir da coluna A e na próxima linha disponível. Abaixo segue o código que realiza exatamente isso.
Public wsLog As Worksheet
Public nUsu As String

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("N1:N1048576")) Is Nothing Then
        Application.EnableEvents = False
        Dim Rng As Range
        Set wsLog = Sheets("LOG")
        Dim codCli As Variant
        Set Rng = wsLog.Range("A" & Rows.Count).End(xlUp).Offset(1)
        If nUsu = "" Then
            nUsu = InputBox("Digite seu nome!")
            MsgBox "Olá " & nUsu & "!"
        End If
        codCli = Target.Offset(, -13).Value
        With Rng
            .Value = codCli
            .Offset(, 1).Value = Now
            .Offset(, 2) = Target.Value
            .Offset(, 3) = nUsu
        End With
    End If
    Application.EnableEvents = True
End Su

b
Fiz tambem umas validações, por exemplo se ao alterar a celula na coluna N e nUsu(armazena o nome do usuario) estiver vazia, abre uma inputbox para inserir o nome.
Ainda vou implementar outras coisas, como pedir usuario e senha ao abrir a planilha para ter uma seguranca maior mas isso precisa um pouco mais de estudo rs.
Espero que ajude alguém aí. Abraço


How can I fix a migration input format mess?

Question: I did a migration from Drupal 6 to Drupal 8 and now I have two Full HTML, two Plain text, and all other individual for both versions of Drupal default text formats. Of course when I try to modify the duplicates I have warning that it is not possible to have the same human readable names so I have Full HTML and Full HTML2 now. I want to get rid the one of them. It looks like that all the migrated by me content is with a text format with a machine name 2 while the other Full HTML text format with no any content in the website is with the machine name full_html. Also the default Plain Text, the one that it is not possible to be removed is with a machine name 3.
As far as understand by the research I did, even if I disable the full_html text format, I cannot use its machine name for the other one. I don't mind what the name is, but can I safely change somehow the text format machine name 2 to something more meaningful?
Is it necessary to do so, or it will be fine if I leave it this way and just remove the full_html one as far as I do not need it?
Answer: One option is in the migration template, to add the input format value.
I found the default_value plugin worked well there e.g, to set default full_html:
field_subheading:
  plugin: sub_process
  source: field_subheading
  process:
    value: value
    format:
      plugin: default_value
      default_value: full_html

Another option, could be to run an SQL query to update the field data and revision data tables
update node__field_subheading set field_subheading_format = 'full_html' where field_subheading_format = 'other_format';
update node_revision__field_subheading set field_subheading_format = 'full_html' where field_subheading_format = 'other_format';

then clear cache.
However fixing as part of the migration template mapping is recommended.
Comment: Thanks for you reply, sorry if I am asking something obvious but I cannot run the migration again because the website has a lot of new content, does this mean that I can forget for the migration template and use the sql queries above to update the machine names?
Comment: it works with the sql query, thank you!


Simplify $\frac {\sqrt5}{\sqrt3+1} - \sqrt\frac{30}{8} + \frac {\sqrt {45}}{2}$

Question: I am trying to find the value of: $$\frac {\sqrt5}{\sqrt3+1} - \sqrt\frac{30}{8} +  \frac {\sqrt {45}}{2}$$
I have the key with the answer $\sqrt 5$ but am wondering how I can easily get to that answer?
I realize this is a very basic question on radicals and I know that square roots can be separated into parts, for instance $\sqrt {45} = \sqrt 9 \cdot \sqrt 5$ and I can see how that would be useful here in canceling out radicals but I have not yet been able to reach a solution using this method.
Comment: You can square that number and try to prove the square equals $25$, then you just need to prove that the given number is positive to conclude.
Comment: To begin,  write all the terms as multiples of $\sqrt 5$ (for example, from what you noted, the third term can be written as  ${\sqrt 9\over 2}\sqrt5={3\over2}\sqrt 5$). For the first term, multiply top and bottom by $\sqrt3-1$ to start.
Answer: $$\begin{align}
\frac{\sqrt{5}}{\sqrt{3}+1} - \sqrt{\frac{30}{8}} + \frac{\sqrt{45}}{2} &= \frac{\sqrt{5}(\sqrt{3}-1)}{(\sqrt{3}+1)((\sqrt{3}-1))} - \sqrt{\frac{15}{4}} + \frac{\sqrt{9·5}}{2}\\
&= \frac{\sqrt{5}(\sqrt{3}-1)}{2} - \frac{\sqrt{15}}{2} + \frac{3\sqrt{5}}{2}\\
&= \frac{\sqrt{15}-\sqrt{5} -\sqrt{15} + 3\sqrt{5}}{2}\\
&= \sqrt{5}
\end{align}$$


Query do Laravel retorna resultado "errado"

Question: Tenho uma tabela chamada "tabela_precos", com a seguinte estrutura:
categoria_veiculo_id | valor | preco_min | preco_max | tipo_veiculo
22                     77,70   0           2500        carros
22                     30,35   15000       20000       carros

Quando executo a seguinte query no phpmyadmin, o retorno é correto e só traz um resultado (o registo com valor 30,35):
select * from `tabela_precos` where `tipo_veiculo` = "carros" and `categoria_veiculo_id` = 22 and 15000 between preco_min and preco_max ;

mas quando executo isso no Laravel, ele me retorna os dois registros (mesmo usando limit 1 ou first(), código:
$query = TabelaPreco::whereRaw('? between preco_min and preco_max', [$request->preco_fipe])
        ->where('categoria_veiculo_id', $request->categoria_veiculo_id)
        ->where('tipo_veiculo', $request->tipo_veiculo);

esses dados vêm de um formulário, e mesmo eu colocando os dados diretamente no código, os mesmos dois registros são retornados.
Já dei um toSql() e a query é exatamente a mesma que executei diretamente no phpmyadmin
Sei que isso é provavelmente algo muito bobo, mas não consegui entender porque isso acontece.
Answer: Depois de rodar a internet toda procurando isso, acabou que o erro era era que eu estava enviando os valores do preco_fipe como string e por isso gerou esse resultado "estranho", quando fiz a conversão pra int os resultados vieram certos
Comment: não entendi porque negativaram minha resposta, ninguém soube responder, é um detalhe sutil mas difícil de perceber...


Filtrar consulta removendo duplicados

Question: Boa tarde, eu estou com o seguinte select:
select  codemp, codfunc, codevento
, vlrevento
from sankhya.TFPFOL
where codemp = 1
and codfunc = 26
and month(referencia) = 1
and year(referencia) = 2009
group by codemp, codfunc, codevento
, vlrevento
having count(1)=1

que me mostra o resultado abaixo

Vejam que existem 2 campos com o codevento 534. Eu quero remover ambos mas manter o vlrevento para os demais.
Se eu removo o vlrevento do GROUP BY ele nao me permite completar o SELECT:
select  codemp, codfunc, codevento, vlrevento
from sankhya.TFPFOL
where codemp = 1
and codfunc = 26
and month(referencia) = 1
and year(referencia) = 2009
group by codemp, codfunc, codevento

having count(1)=1

Mensagem 8120, Nível 16, Estado 1, Linha 22
A coluna 'sankhya.TFPFOL.VLREVENTO' é inválida na lista de seleção porque não está contida em uma função de agregação nem na cláusula GROUP BY.

e se eu removo o vlrevento do select obviamente ele nao me mostra no resultado

Como eu posso informar o campo vlrevento nesse select sem que apareça os codeventos que possuem valor duplicado?
Grato desde já
Comment: No caso seria apenas para informar o vlrevento correspondente ao codevento. Como eu quero remover os codevento que possuem valor duplicado eu nao preciso mostrar um min ou max. Os que estào repetidos eu não vou usar
Comment: Você tem que informar o que vai fazer com `vlrevento`. Você quer mostrar o maior? O menor? Uma soma?
Answer: Agrupe os registros e caso possua mais de um registro iremos remove-lo do nosso retorno utilizando a cláusula HAVING:
SELECT codemp, codfunc, codevento, SUM(vlrevento)
  FROM sankhya.TFPFOL
 WHERE codemp = 1
   AND codfunc = 26
   AND month(referencia) = 1
   AND year(referencia) = 2009
 GROUP BY codemp, codfunc, codevento
HAVING count(codemp) = 1

Comment: é que eu não preciso daqueles codeventos duplicados. Então se eu só somar os vlrevento eles ainda vão aparecer na consulta
Comment: Se o `codevento` possuir mais de 1 registro você quer remover todos desse `codevento` do retorno?
Comment: Isso mesmo. Se existir algum codevento duplicado eu não vou precisar de nenhum deles
Comment: Tente novamente com essa edição.
Comment: Era exatamente isso que eu precisava. Muito obrigado!
Comment: Falou, abraços!!

Filtrar consulta removendo duplicados


What are the prerequisites to start learning Bayesian analysis?

Question: Or in other words, How mature-I mean my statistical knowledge- should I be to start learning and doing Bayesian analysis?
Comment: Just need to know probability: frequentist background not necessary.
Answer: Maturity is not really what is needed. Clarity of purpose is useful, though, and that clarity is often absent in statistics books and courses.
According to Richard Royall, there are three main types of question that are typically answered with the help of statistics, and I think that those questions are the prerequisite for learning all statistical approaches to a more than superficial level.

What do the data say?
What should I believe now that I have these data?
What should I do or decide now that I have these data?

P-values interpreted as continuous indices of evidence and likelihood functions are well suited to answering the first question. Bayesian analyses are clearly well suited to answering question 2 and Frequentist approaches are well suited to answering question 3.
It is true that Bayesian analyses are often more involved than a simple recipe-based Frequentist hypothesis test approach, but that is inevitable given that considerations of information external to the data, sometimes in the form of opinion, come into the Bayesian analysis. However, a full understanding of the philosophy of the Frequentist approach requires more maturity on the part of students than is usually communicated by the test recipes.


Are Baroque Bassoons more difficult to play?

Question: In an article introducing The Breaking Winds Bassoon Quartet, it mentions that

The muffled, dark-sounding bassoon of the baroque era was so hard to
  play in tune that composers didn't write solos for it. But a century
  later, with better reeds and more keys, they began to take notice of
  its comic potential. Reynolds says Haydn's Symphony No. 93 and
  Beethoven's Sixth were some of the earliest to feature the bassoon as
  buffoon.

So, I assume the writer is implying that there is no solo pieces (concertos) composed in Baroque era.
However, this is completely contradictory to my knowledge. Since I know that Vivaldi alone wrote at least 39 (2 of them are incompleted) bassoon concertos. Not to mention other less known composers such as Graupner, Molter, and etc. Each of them also wrote several concerto pieces for Bassoons.
So is it correct for the writer to say that composers didn't write solos for [bassoons]?
Then I am wondering if baroque bassoon is really that difficult to play in tune. Anyone who has played both modern bassoon and baroque bassoon can comment on this?
Comment: My personal idea is that the writer is completely wrong when it comes to solo pieces for bassoon as he clearly did write them. Vivaldi might be a special example, if I remember correctly he was paid to make two concertos per month at the orphanage, adding up to some 350 concertos.
Answer: When the author writes about "solos", I think of solo orchestral passages, not solo concerti. Even with modern keys and reeds, the intonation on a bassoon is extremely flexible.  It's all about remaining flexible while playing when trying to play in tune with others.
The more important difference between the baroque and modern woodwinds is the available volume is much greater after the modern developments.   The principal reason bassoons get relatively few baroque-era solo orchestral passages is because it's development away from the older Dulcian was taking place as the Baroque era was raging.  It was admitted into many basso continuo sections at the time, and gained operatic usage. Once the Baroque era slipped into the Rococo, it's acceptance as an orchestral instrument beyond the basso continuo section is seen more regularly; once classical hits the scene, the bassoon is commonplace in orchestras, and solo passages in orchestral music are seen, for example, Mozart Symphony 41 "Jupiter" composed in 1788.  The Heckel factory opened 43 years later, kicking off further development.  It's always been difficult to play- that's physics fault- but now it had to sing from within the orchestra, so more volume was needed, and it had to play in tune at all volumes.
While studying bassoon, I asked my prof about baroque bassoon once.  He brought out the continuo parts.  There are some wicked difficult basso continuo parts in the baroque era.
Comment: How is the solo orchestral passages different from that solo concerti? I mostly listen to concerti, can you suggest some solo orchestral passages (any instrument) so that I can commpare with?
Comment: If a solo concerto could be considered a dialogue between the solo and tutti orchestra, symphonic concert work would be like a cocktail party.  Many instruments may play soli, and musical ideas may be passed about here and there. These type of orchestral excerpts are collected in volumes and studied by advanced students and professionals.  This a classic example of orchestral solo passages: http://www.people.vcu.edu/~bhammel/main/bassoon/excerpts.htm
Comment: https://orchestraexcerpts.com/bassoon/
Answer: The writer is wrong about the repertoire, but quite right about instrument development.
Most modern instruments went through a long phase of design improvements, usually to increase both sound and playability. (Even the violin, which has been essentially the same for centuries, had a long design phase, it was just earlier.) In particular, the complicated valve and key systems of modern wind instruments are a massive improvement in terms of what is even possible, or possible without virtuosity, to perform.
A comparison with archery might be helpful. Obviously you can hit the target exactly with a stone-age long bow - it's a matter of luck and practice. But modern bows for competition have a dozen extra gadgets added to them, and I assure you that all of them have a measurable impact on how exactly and how consistently you can hit anything. Hitting iffy notes on a musical instrument is not that much different.
Comment: Thanks for giving the analogy. However, I'm curious if it is really that difficult to play Bassoon in tune without all the keyworks. Take recorders and modern flute as an example. Modern flute has all the keyworks making the pressing of holes easier. But even without keyworks on recorders, you can still play it without serious out-of-tune problem. (sometimes it does sounds a bit out-of-tune if your fingers cannot cover the holes completely). It's more difficult, but I won't say it's so hard to play in tune. Since I have never tried a bassoon before, I would like to confirm this point.
Comment: If you have perfect pitch and ten years of study, sure! playing bassoon in tune is easy.  In orchestra then you have to chose who to play in tune with.. the oboe in front of you, or the clarinet beside you.  Add another ten years of work in the opera pit, and that will be easy for you also. :)


Pre-filled subject Form

Question: I wanted to attach a form to my node, in wich the subject would be already filled with the nodes title.
I was trying something with webforms and views but didnt get any results. Any Ideas?
Comment: Can you please elaborate your problem? Is subject is a simple webform text field?
Answer: If subject is a simple textfield on webform and token module is enabled then you can set this textfield's default value using token.
Comment: Thanks, Mutant. But what token do I use? I was able to enable the form into a block, in wich I can use in my node, but if I use %nid or %title, it gets the webform's info. I'm doing that with the Webforms Module.
Comment: Tokens are in the form of [node:title], [node:nid] use this syntax to use token as default value.
Comment: Sorry. Wasn't online this weekend. That worked! thanks!

Pre-filled subject Form


Galois extension for a specific matrix group

Question: I tried to solve the following problem, but I couldn't; I hope can you help me.

Let $G$ the matrix group
  $$G=\left.\left\{ \left(\begin{array}{cc} a & b \\ 0 & 1 \end{array}\right) \;\right|\;  a,b \in \mathbb{F}_p, a \neq 0 \right\},$$
  with $p$ prime. Build a Galois extension $K$ of $\mathbb{Q}$ such that $\mathrm{Gal}(K/\mathbb{Q}) \cong G$. In addition, , determine the intermediate extension for the subgroups
  $$H_1=\left.\left\{ \left(\begin{array}{cc} a & 0 \\ 0 & 1 \end{array}\right) \;\right|\; a \in \mathbb{F}_p, a \neq 0 \right\},$$
  and
  $$H_2=\left.\left\{ \left(\begin{array}{cc} 1 & b \\ 0 & 1 \end{array}\right) \;\right|\; b \in \mathbb{F}_p, a \neq 0 \right\}.$$

Thanks for you answer.
Comment: What tools do you have at hand? You should tell us what the context is...
Comment: $G$ corresponds to the splitting field of $x^p-\alpha$ (for $\alpha\in\mathbb{Q}$ not a $p$th power).  see lang chapter 6, section 9
Comment: Dear @yoyo: Your comment looks like an answer...
Answer: I'm ripping this from Lang's "Algebra" ch 6 sec 9:
Let $p$ be an odd prime and consider the splitting field $K$ of the irreducible polynomial $x^p-a$, with $a$ not a $p$th power.  Let $\alpha$ be a root and $\zeta$ a primitive $p$th root of unity.  We see that $[\mathbb{Q}(\zeta):\mathbb{Q}]=p-1$ and $[\mathbb{Q}(\alpha):\mathbb{Q}]=p$ are coprime.  Hence $K=\mathbb{Q}(\alpha,\zeta)$ has degree $p(p-1)$ over $\mathbb{Q}$.
For $\sigma\in G=G_{K/\mathbb{Q}}$, we have $\sigma(\alpha)=\alpha\zeta^{b(\sigma)}$ and $\sigma(\zeta)=\zeta^{d(\sigma)}$ for some $b\in\mathbb{F}_p, d\in\mathbb{F}_p^{\times}$.  Composition gives $\sigma\tau(\alpha)=\alpha\zeta^{d(\sigma)b(\tau)+b(\sigma)}$ and $\sigma\tau(\zeta)=\zeta^{d(\sigma)d(\tau)}$.  We can write this composition down as matrix multiplication under the correspondence you gave
$$
\sigma\mapsto
\left(
\begin{array}{cc}
d(\sigma)&b(\sigma)\\
0&1\\
\end{array}
\right)
$$
whether or not it is obvious that this produces a bijection between $G$ and our matrix group, we have an injective homomorphism ($b$ and $d$ are unique) between groups of the same order $p(p-1)$, hence an isomorphism.
I'll leave the fixed fields of $H_1,H_2$ to you.


Searching for records in pymongo using a datetime criteria

Question: In pymongo, the command mycoll.find_one() returned the following:
{u'name': u'John',u'sex':u'male',u'id':u'xbc541d',u'signup_date': datetime.datetime(2010, 12, 18, 22, 49, 20, 22000)}

If i search for a record using signup_date,no record shows up. That is mycoll.find({'signup_date':datetime.datetime(2010, 12, 18, 22, 49, 20, 22000)}) does not return any records.
What is the error in my syntax for finding records using the date ?
Please Help
Thanks
Comment: That syntax should work (returning a cursor). If you write a minimal Python script that fails (both adding the record and then retrieving it), we might be able to help you figure out what's wrong.
Answer: I just did a same search on my database and it worked. Try giving the following:
  mycoll.find({'signup_date':datetime(2010, 12, 18, 22, 49, 20, 22000)})

You can also try option of narrowing your search results with "$gt" and "$lt" queries.
http://cookbook.mongodb.org/patterns/date_range/


Array of objests with a method that has arguements (Java)

Question: I don't know what's wrong with this code:
class A{
    private int i,j;

    public void get(int i, int j)
    {
        this.i=i;
        this.j=j;
    }

    public void show()
    {
        System.out.println(i + " " + j);
    }
}

public class App {

    public static void main(String[] args) {
        A[] c = new A[11];
        for(int i=0; i<10; i++)
        {
            c[i].get(i, i);
        }
        for(int j=0; j<10; j++)
        {
            c[j].show();
        }
    }

}

can anyone please tell me the right way to call the get() method??
thanks in advance...
Comment: You should populate your array with instances of `A` first.
Comment: You're creating an array of type `A[]` but never populating it - every element will be null.
Comment: Can you please give an example code? I'm actually a new java learner...
Comment: You should give your stacktrace. Even though it"s obviously a NullPointerException
Comment: Possible duplicate of [NullPointerException when Creating an Array of objects](http://stackoverflow.com/questions/1922677/nullpointerexception-when-creating-an-array-of-objects)
Comment: `get` is also a poor name for a method that actually sets values. You should use a constructor.  https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
Answer: for(int i=0; i<10; i++)
{
    c[i] = new A();
    c[i].get(i, i);
}

You had an empty array. You need to fill that array with elements


Audio só iniciar quando eu chegar em determinada div

Question: Estou desenvolvendo uma página que em apenas determinados textos tem áudio. Quero fazer com que o áudio do texto só comece a tocar quando eu chegar no texto. Segue mais ou menos como eu queria. (Não tenho muito conhecimento em javascript, se puderem me dá um help com essa questão.)
<audio src="audio/2.mp3" autoplay></audio>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum animi nobis voluptates aspernatur, impedit molestiae reiciendis. Nisi necessitatibus magnam voluptatem eaque, ut ullam et, sunt aperiam voluptatibus alias, ipsa nesciunt.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum animi nobis voluptates aspernatur, impedit molestiae reiciendis. Nisi necessitatibus magnam voluptatem eaque, ut ullam et, sunt aperiam voluptatibus alias, ipsa nesciunt.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum animi nobis voluptates aspernatur, impedit molestiae reiciendis. Nisi necessitatibus magnam voluptatem eaque, ut ullam et, sunt aperiam voluptatibus alias, ipsa nesciunt.

<audio src="audio/2.mp3" autoplay></audio>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum animi nobis voluptates aspernatur, impedit molestiae reiciendis. Nisi necessitatibus magnam voluptatem eaque, ut ullam et, sunt aperiam voluptatibus alias, ipsa nesciunt.

Answer: Você precisa definir uma Classe ou um id para a div que quer que inicie o áudio.
  <audio id = "audioDiv" src="audio/2.mp3"></audio>

Remova o AutoPlay do seu elemento
No Javascript você irá pegar essa classe ou id:
   //Se você colocar id
   audio = document.GetElementById("audioDiv")

ou
  //Se você colocar class
   audio = document.GetElementsByClassName("audioDiv")

Então você colocará essa condição em baixo:
  if (document.documentElement.scrollTop >= audio.offsetTop) {

    audio.play()

   }

Resultado do código testável:
    audio = document.GetElementById("audioDiv")
    onscroll = function()
    {
       if (document.documentElement.scrollTop <= audio.offsetTop) {

       audio.play();
       console.log("ligado")

    }else if (document.documentElement.scrollTop >= audio.offsetTop){

       audio.pause();
       console.log("desligado")
    }
  }

Explicando o código e como aplicar a sua situação:
A variavel Audio receberá o elemento que contém a mídia. O if irá verificar se a pagina no navegador estará numa posição menor que a posição do elemento Audio.
Você pode mudar o operador >=  no if para obter outros resultados, como, por exemplo, mudar para <, que iniciará o audio quando o usuário passar por ele. Ai vai da sua necessidade.
A função onscroll irá fazer reproduzir o código toda vez que a pagina se mover. Ou seja, sempre que alguém rolar a pagina.
Observação sobre Class:
Se você for buscar o elemento pela Classe no javascript, ao final da linha de código você precisa definir um index para o elemento especifico, senão ele cria uma lista com todas as Classes existentes com o mesmo nome.
Ficará assim:
audio = document.getElementByClassName("audioDiv").item(0);

O 0 (zero) representa o primeiro elemento com a classe do nome audioDiv.


How do I calculate the confidence interval from the standard error?

Question: When using the Kaplan Meier estimator function in MedCalc, medcalc gives me the  the survival proportions at each observed timepoint as well as the standard error for that proportion, so I can for example say "At 2 years the overall survival is 87% with a standard error of 7%., p = 0.06"
Is there an easy way to calculate the confidence interval for that survival proportion from that info?
Answer: Typically the $87\%$ and $7\%$ would be an estimated mean and standard deviation of the sampling distribution for the reported statistic. In general these parameters can be used to compute a confidence interval, assuming a known parametric form for the distribution function.
In your case the normal approximation is not fully appropriate, as $0.87\pm{2}\times{0.07}$ gives an interval $[0.73,1.01]$ whose upper bound exceeds $100\%$. A reasonable alternative could be to assume a Beta distribution. In this case the 95% confidence interval corresponding to your numbers would be $[74.1\%,96.2\%]$.
I am not sure exactly how the calculation might incorporate the reported $p$ value? With the Beta interpretation above, the "effective sample size" would be $\hat{n}\approx{23}$, if that helps.

Note that the MedCalc manual says there is an option to
"Include 95% CI in graph", which is probably the easiest solution in your situation. This will presumably produce a result that is consistent with the software's underlying statistical model, as well.


MySQL error when creating field schema

Question: I have a problem when adding a new field to a content type. The schema installer for the specified field always causes the following error:

Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL DEFAULT NULL, PRIMARY KEY (entity_type, entity_id, deleted, delta,' at line 12.

Here is the hook_field_schema() implementation:
function google_directions_field_schema($field)
{
    return array(
        'columns' => array(
            'lat' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'lng' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'mapTypeId' => array(
                'type' => 'varchar',
                'length' => '15',
                'not null' => false,
            ),
            'zoom' => array(
                'type' => 'integer',
                'size' => 'small',
                'not null' => false,
            ),
        ),
        'indexes' => array(
            'lat_lng' => array('lat', 'lng'),
        ),
    );
}

I hope somebody can point out my mistake here. If some informations missing, please comment.
Thank you in advance.
Comment: please create transfer your 'edit' to your own answer, then except it.  If you don't then the site will think this is an unanswered question
Comment: Okay, sorry. Thought that would be too selfish.
Answer: I fixed this problem by myself. Please note the mistyped column type name integer which is now int:
function google_directions_field_schema($field)
{
    return array(
        'columns' => array(
            'lat' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'lng' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'mapTypeId' => array(
                'type' => 'varchar',
                'length' => '15',
                'not null' => false,
            ),
            'zoom' => array(
                'type' => 'int',
                'size' => 'small',
                'not null' => false,
            ),
        ),
        'indexes' => array(
            'lat_lng' => array('lat', 'lng'),
        ),
    );
}

MySQL error when creating field schema


How to call a Rules action settings form via drupal_get_form

Question: So, I'm trying to embed the form I find at '/admin/config/workflow/rules/reaction/manage/commerce_payment_paypal_wps/edit/3' - which contains the settings for the PayPal business, etc (from commerce_paypal_wps.module).
Looking in rules/ui/ui.controller.inc I can see it's called thus:
$items[$base_path . '/manage/%rules_config/edit/%rules_element'] = array(
      'title callback' => 'rules_get_title',
      'title arguments' => array('Editing !plugin "!label"', $base_count + 3),
      'page callback' => 'drupal_get_form',
      'page arguments' => array('rules_ui_edit_element', $base_count + 1, $base_count + 3, $base_path),
      'access arguments' => array('administer rules'),
      'load arguments' => array($base_count + 1),
      'file' => 'ui/ui.forms.inc',
      'file path' => drupal_get_path('module', 'rules'),
    );

I'm not entirely sure what extra things I should be passing into drupal_get_form('rules_ui_edit_element') to make it render the form as it does normally.
How on earth do I get that rules action settings form to render either through drupal_get_form, or some other mechanism, so I can put it at the URL of my choosing, and make it look a bit more presentable to our clients?
Comment: What exactly are you trying to do? This is a rules configuration form, just displaying it won't do much, the action is not executed when that form is submitted but when the corresponding event is executed.
Comment: @Berdir: He doesn't want to invoke an event, but to change the url of the settings form, for an action/event.
Answer: You must be using an old version of commerce to get an url like that. It was changed long ago to dmin/commerce/config/payment-methods/...
In hook_menu, the commerce_payment_ui module creates the path, where the rules forms should be located:
// Add the menu items for the various Rules forms.
$controller = new RulesUIController();
$items += $controller->config_menu('admin/commerce/config/payment-methods');

You could alter those if you want to change the url. You should however be aware that this url is also used elsewhere:
/**
 * Builds the payment settings page using the Rules UI overview table filtered
 *   to display payment method rules.
 */
function commerce_payment_ui_admin_page() {
  RulesPluginUI::$basePath = 'admin/commerce/config/payment-methods';

  ...
}

Since most of what Rules does, including creating these settings form is classed based, it wont exactly be easy to create the form. I haven't delved much into the Rules code, but I remember seeing public functions called

form
form_validate
form_submit

I believe these are used to create the form, but how it ends up in the FAPI is beyond me. If all you want is to change the path, you could just use hook_menu_alter and for commerce, overwrite the commerce_payment_ui_admin_page function with your own to create the overview table.
Comment: Turns out I was going through the Rules UI rather than the Commerce Payment UI, which gave me the old URL structure - we're on the Commerce Beta. I guess the right way to go, then, is to menu_alter the original rule form, and then form_alter it to look better (add our own validation, etc), and make sure form_submit for that rule gets called.