Java lwjgl rotating a model around its center

Question: I have been making a project in light weight java graphics library where i have loaded a model and rendered it with a color per triangle fine. My next step is to rotate the model around its center. From reading articles and source code i have a general understanding of what i need to do but i don't fully understand the glTranslatef() method. From my under standing you want to
glPushMatrix()
glTranslatef(0,0,0);
glRotatef(roation values);
glTranslatef(original coords);
render model
then glPopMatrix();
My main problem is i am manually doing the math in my glVertex() method calls instead of translating them i believe which is making the translation back from 0,0,0 to it's original spot difficult. Thanks for your time and help.
package render;

import static org.lwjgl.opengl.GL11.glBegin;
import static org.lwjgl.opengl.GL11.glRotatef;
import static org.lwjgl.opengl.GL11.glPushMatrix;
import static org.lwjgl.opengl.GL11.glTranslatef;
import static org.lwjgl.opengl.GL11.glPopMatrix;
import static org.lwjgl.opengl.GL11.glEnd;
import static org.lwjgl.opengl.GL11.GL_TRIANGLES;
import static org.lwjgl.opengl.GL11.glColor3f;
import static org.lwjgl.opengl.GL11.glClearColor;
import static org.lwjgl.opengl.GL11.glNormal3f;
import static org.lwjgl.opengl.GL11.glVertex3f;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.lwjgl.util.vector.Vector3f;

import models.Faces;
import models.Material;
import models.Model;
import models.OBJLoader;

public class OBJRender {
    Material material = new Material();
    private int count;
    Model m = null;
    Vector3f rgb = null;
    Vector3f v1 = new Vector3f();
    Vector3f v2 = new Vector3f();
    Vector3f v3 = new Vector3f();

public void load_model(String model_name){ //loads model data
    try{
        m = OBJLoader.loadModel(new File("res/obj/"+model_name+".obj"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void model_render(Vector3f coords, Vector3f degrees){
    count = 0; //count of triangle for coloring
    model_rotate(coords, degrees); //coords is the obj coords degrees is rotation coords
    glBegin(GL_TRIANGLES);
    for (Faces face : m.faces) {
        String mat = OBJLoader.getMaterialList().get(count);
        rgb = material.getMaterial(mat);
        glColor3f(rgb.x, rgb.y, rgb.z);
        Vector3f n1 = m.normals.get((int) face.normals.x - 1);
        v1 = m.vertices.get((int) face.Vertex.x - 1);
        Vector3f n2 = m.normals.get((int) face.normals.y - 1);
        v2 = m.vertices.get((int) face.Vertex.y - 1);
        Vector3f n3 = m.normals.get((int) face.normals.z - 1);
        v3 = m.vertices.get((int) face.Vertex.z - 1);
        glNormal3f(n1.x, n1.y, n1.z);
        glVertex3f(coords.x-v1.x, coords.y+v1.y+80, coords.z-v1.z);
        glNormal3f(n2.x, n2.y, n2.z);
        glVertex3f(coords.x-v2.x, coords.y+v2.y+80, coords.z-v2.z);
        glNormal3f(n3.x, n3.y, n3.z);
        glVertex3f(coords.x-v3.x, coords.y+v3.y+80, coords.z-v3.z);
        count++;
    }
    glClearColor(rgb.x,rgb.y,rgb.z,0);
    glEnd();
    glPopMatrix();
}

public void model_rotate(Vector3f coords, Vector3f degrees){
    glPushMatrix();
    glTranslatef(-0, -0, -0);
    glRotatef(degrees.y,0,1,0);
    }
}

Comment: The sequence is actually `glTranslate(center)`, `glRotate(angle)`, `glTranslate( - center)`. But when you're modifying the vertex coordinates, this has to be taken into account, and you have to compute the *new* center. (You should probably not do this. Just render the object as-it-is, and use only the `glTranslate` etc. calls to transform it).
Comment: So from what your saying you want me to exclusively use glTranslate to rotate my model?
Comment: `glTranslate` and `glRotate`, of course (this was what the "etc." stood for). The key point is: You usually don't modify vertex coordinates manually when you want to transform the whole object. Instead, you use the "original" vertex coordinates, and transform the object by manipulating the modelview matrix with `glTranslate` and `glRotate` (and `glScale`, if you want to).
Comment: can you give me a example of how to do this.
Comment: ive tried to translate to (0,0,0) rotate then (-0,-0,-0) back but it still renders off of where it should.
Comment: Translating about (0,0,0) does not make sense. You should probably read "Viewing and Modeling Transformations" in http://www.glprogramming.com/red/chapter03.html . Until now, there does not seem to be a real *question*.
Comment: I've read through that article and tried to put it to practice but it still makes no sense to me on rendering. i understand i have to rotate before rendering. But when i am rending and transforming back i cant get my model to be placed at its original coordinates which are represented by the Vector3f coords. My rotation is fine its when i am returning to its original location is my problem.
Answer: Although it is still not entirely clear what the actual question is (apart from "What do I have to change so that the code does what I want"), an attempt to answer:
When you load an object, for example, from an OBJ file, you usually will not modify the vertex coordinates. You will just use them as they are read from the file. When you want to transform the object as a whole, you use the OpenGL matrix operations - in this case, only glTranslate and glRotate.
In order to rotate the object about its center, you first have to know this center. In doubt, you can compute it from the vertices or the bounding box of the object.
Then, in order to rotate the object around its center, you have to

Move the object, using glTranslate, so that the center of the object is at the origin
Rotate the object, using glRotate
Move the object back to its original position, using glTranslate

Note that these operations are applied to the object in the opposite order than they appear in the source code. So the sequence of calls will be
glTranslatef( center.x,  center.y,  center.z);
glRotatef(rotationAngleDeg,0,0,1);
glTranslatef(-center.x, -center.y, -center.z);

Here is a MCVE that uses a simple rectangle consisting of 4 vertices as the object, and rotates it about its center. You can see that in the glVertex calls, it simply uses the vertices as they are (in your case, they would be read from the OBJ file). The whole transformation is done on the GL_MODELVIEW matrix, using the commands mentioned above.
import static org.lwjgl.opengl.GL11.*;
import java.awt.Canvas;
import javax.swing.JFrame;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.util.glu.GLU;
import org.lwjgl.util.vector.Vector3f;

public class RotateAboutCenter
{
    public static void main(String[] args)
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(500,500);
        f.setLocationRelativeTo(null);
        Canvas canvas = new Canvas();
        f.add(canvas);
        try
        {
            Display.setParent(canvas);
            f.setVisible(true);
            Display.create();
        }
        catch (LWJGLException e)
        {
            e.printStackTrace();
        }
        while (!Display.isCloseRequested())
        {
            draw();
            Display.update();
            try
            {
                Thread.sleep(10);
            }
            catch (InterruptedException e)
            {
                Thread.currentThread().interrupt();
            }
            rotationAngleDeg += 1.0f;
        }
        Display.destroy();
    }

    private static float rotationAngleDeg = 0;

    // The vertices of the model
    private static Vector3f v0 = new Vector3f(10,10,0);
    private static Vector3f v1 = new Vector3f(20,10,0);
    private static Vector3f v2 = new Vector3f(20,20,0);
    private static Vector3f v3 = new Vector3f(10,20,0);

    // The center of the model
    private static Vector3f center = new Vector3f(15,15,0);

    private static void draw()
    {
        // Basic setup of view etc.
        int w = Display.getWidth();
        int h = Display.getHeight();
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glViewport(0, 0, w, h);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        GLU.gluPerspective(45, (float) w / (float) h, 0.1f, 1000);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        GLU.gluLookAt(0,0,70,0,0,0,0,1,0);

        glPushMatrix();

        // ===================================================================
        // Now, do the model transform. Remember that this has to
        // be read "backwards":

        // THIRD STEP: Move the model back so that its center is
        // again at its original position
        glTranslatef(center.x, center.y, center.z);

        // SECOND STEP: Rotate the model about the origin (which now
        // is the center of the model)
        glRotatef(rotationAngleDeg,0,0,1);

        // FIRST STEP: Translate the model so that its center is at the origin
        glTranslatef(-center.x, -center.y, -center.z);

        // ===================================================================

        // Draw the object, with its original coordinates. All the
        // transforms are now contained in the MODELVIEW matrix.
        glBegin(GL_TRIANGLES);
        glColor3f(1,0,0);
        glVertex3f(v0.x, v0.y, v0.z);
        glVertex3f(v1.x, v1.y, v1.z);
        glVertex3f(v3.x, v3.y, v3.z);
        glVertex3f(v1.x, v1.y, v1.z);
        glVertex3f(v2.x, v2.y, v2.z);
        glVertex3f(v3.x, v3.y, v3.z);

        glEnd();
        glPopMatrix();
    }
}

Comment: Sorry for the misunderstanding on the concept of what my question was trying to say. I wasn't manually changing the vertex coords but subtracting the coordinates of the model location from the vertex coordinates so the vertex remained constant. My error was i didn't understand that you had to call your translations and rotations in backwards order. All the forums and tutorials i had seen didn't have them as you did but for my case it worked. Thank you for your time and sorry for your struggles.


Reversing mod for a function?

Question: I'm trying to solve this equation:
(b(ax+b ) - c) % n = e

Where everything is given except x
I tried the approach of :
(A + x) % B = C
(B + C - A) % B = x

where A is (-c) and then manually solve for x given my other subs, but I am not getting the correct output. Would I possibly need to use eea? Any help would be appreciated! I understand this question has been asked, I tried their solutions but it doesn't work for me.
Answer: (b*(a*x+b) - c) % n = e
can be rewritten as:
(b*a*x) % n = (e - b*b + c) % n
x = ((e - b*b + c) * modular_inverse(b*a, n)) % n

where the modular inverse of u, modular_inverse(u, n),  is a number v such that u*v % n == 1. See this question for code to calculate the modular inverse.
Some caveats:

When simplifying modular equations, you can never simply divide, you need to multiply with the modular inverse.
There is no straightforward formula to calculate the modular inverse, but there is a simple, quick algorithm to calculate it, similar to calculating the gcd.
The modular inverse doesn't always exist.
Depending on the programming language, when one or both arguments are negative, the result of modulo can also be negative.
As every solution works for every x modulo n, for small n only the numbers from 0 till n-1 need to be tested, so in many cases a simple loop is sufficient.
Answer: What language are you doing this in, and are the variables constant?
Here's a quick way to determine the possible values of x in Java:
for (int x = -1000; x < 1000; x++){
    if ((b*((a*x)+b) - c) % n == e){
    System.out.println(x);
    }
}

Reversing mod for a function?


Payment Information on hook_commerce_checkout_complete

Question: I am developing module which connects Drupal Commerce with 3rd party invoicing system. For this purpose I need to send payment information (has it been paid? how much? in what way?) after the order is complete. I guess the hook_commerce_checkout_complete() hook is the best place to do that but I can't figure out how to obtain this payment information from an $order object/entity.
Answer: You can see the payment method the customer selected in the $order->data array, and to determine if the order was paid in full you'd use commerce_payment_order_balance(). Any additional information would have to come from payment transaction entities whose order_id match $order->order_id.


What Are Some Historical Applied Stats Problems

Question: What are some interesting, historical applied statistics problems ?   i.e. sometime in the past that statistics have been used to affect the course of events?
The kind of problems I am looking for are things like

German Tank Problem - bayesian statistics applied to estimate number of enemy tanks
Florence Nightingale - showing that disease is the largest killer
Abraham Wald Memo - armor the parts of the airplanes that do not have holes in them (selection bias)

I have been able to find a lot of classic statistic "paradoxes"   like the 2 envelope problem, or the 2 daughters problem.  But not that many actually applied.   I am interested in the paradox problems only in so much as they are historically relevant for instance.

Monty Hall Problem -  great "paradox", and interesting because of its famous use an an actual game show

to clarify,  the examples I gave were war & destruction themed.  But I would be just as interested in a clever example of a company exploiting stats to make money.
Thanks!
Comment: There are multiple reasons to close this question, as appealing is it might be: it is too broad, it does not fit the framework of this site, it is vague, and it solicits opinion (what exactly does "interesting" mean?).  It would be a nice subject for a chat.
Answer:
In the 60s a Bayesian search methodology was used to find the lost submarine USS Scorpion.
"Big Data" has revolutionized many industries including sports and marketing; changing their course forever.
The Los Alamos National Laboratory has been able to predict flu outbreaks based on Wikipedia page views - potentially saving lives.


How apply auth restriction in JSPUI?

Question: How apply auth restriction in JSPUI? I was wanting in JSPUI apply when the user tries to access the feedback form, the dspace require authentication, but I could not understand how the pages that require authentication as in 'mydspace' works in JSPUI.
It is possible for jsp pages? or need change java class?
Answer: The authentication requirement is set up in web.xml (link to 5.x version). It may be enough to add another filter-mapping clause for the feedback URL, eg
<code><filter-mapping>
  <filter-name>registered-only</filter-name>
  <url-pattern>/feedback</url-pattern>
</filter-mapping>
</code>
But I haven't tried it! This may not work.

How apply auth restriction in JSPUI?


A complex conjugation mulplication

Question: Compute ||a|| given that e/ā=5/4+i/4 and ea=10+2i
I found sqrt(13) as answer, but the solution says its 2sqrt(2), am I doing something wrong?
Thanks a lot!
Answer: $$e\cdot a=10+2i$$
$$\frac e {\bar a} =\frac{5+i}4$$
On division $$a\cdot \bar a=\frac{4(10+2i)}{5+i}=8\cdot \frac{5+i}{5+i}=8$$
If  $a=x+iy, \bar a=x-iy,$ so, $a\cdot \bar a=(x+iy)(x-iy)=x^2+y^2=\mid a\mid ^2$
So, $$\mid a\mid ^2=8\implies |a|=2\sqrt2 $$
As $$e\cdot a=10+2i, \mid e\cdot a \mid=\sqrt{10^2+2^2}=\sqrt {104}$$
As $\mid e\cdot a \mid= \mid e\mid\cdot \mid a \mid, $
so, $\mid e\mid\cdot \mid a \mid= \sqrt {104}$
but, $\mid a \mid=\sqrt 8,$ so, $\mid e\mid=\frac{\sqrt{104}}{\sqrt{8}}=\sqrt{13}$
Comment: Ohhh I see, so if the question asked for ||e||, it would be sqrt(13) right?
Comment: @user1561559, yes, please find in the edited answer.

A complex conjugation mulplication


How to solve this particular linear system?

Question: So I have this linear system:
$$
\begin{align*}
-u + v &= y_1\\
u + v &= y_2 \\
2u + v &= y_3
\end{align*} $$
After doing gaussian elimination, I get:
$$
\begin{align*}
u = y_3 - y_2 \\
v = 2y_2 - y_3 \\
y_1 -3y_2 + 2y_3 = 0
\end{align*} $$
I'm asked to find for what values of $y_1, y_2, y_3$ this system has a solution. The answer to that would be:
$$\left[ \begin{array}{ccc}
1 & -3 & 2 \\
 \end{array} \right] * \left[ \begin{array}{ccc}
y_1 \\
y_2 \\
y_3
 \end{array} \right] = 0$$
i.e. the null space. How do I find a basis for the null space though?
Answer: Clearly two independent vectors from the null space are $a_1 = (3, 1, 0)^t$ and $a_2 = (2, 0, -1)^t$.
Comment: And we know that you only need two because the dimension of the null space is 3-1 = 2, right?
Answer: The easiest solution by far is just to guess two linearly independent vectors that satisfy the condition, such as $(3,1,0)$ and $(2,0,-1)$.
If that is not systematic enough for you, take $(1,-3,2)$ and append a known basis for the entire space, such as $\mathbf e_1, \mathbf e_2, \mathbf e_3$. Then use the Gram-Schmidt process on the resulting list of 4 vectors. You'll need to throw out one when it turns out it is not linearly independent of the precedent ones. In the resulting basis for $\mathbb R^3$, remove the first one (which will be proportional to $(1,-3,2)$); the other two are a basis for the orthogonal complement.
Comment: Thanks for the description! I didn't realize it could be done that way, but it appears guessing seems to be the simplest approach.
Answer: If you're in 3 dimensions, then $y_1-3y_2+2y_3=0$ is the cartesian equation of a plane. Choose values for any two of the three parameters and that will determine the third one.


How to rotate Decal over more then one axis at moment

Question: I'm working on Libdx app using Decals.
Decals are 2d sprites in 3d world.
I have problem that when I say:
decal.setRotationX(angle)

everything works fine, but when I say:
decal.setRotationX(angle);
decal.setRotationY(angle2);

The decal rotates over Y axis only.
How to manage that problem?
I have found that Decal in source code uses Quaternion for rotation, but currently I don't know how to customize that to face my requirements.
Tnx in advance!
EDIT:
I have managed to rotate decal around multiple axis with:
decal.getRotation().setEulerAngles(yaw,pitch,roll);
Now my question is how to animate this with TweenEngine?
In get values method I have:
returnValues[0] = target.getRotation().getYaw();
returnValues[1] = target.getRotation().getPitch();
returnValues[2] = target.getRotation().getRoll();

In set values method I have:
target.getRotation().setEulerAngles(newValues[0], newValues[1],
                newValues[2]);

But decal is not moving or animating, it's stucked in one position (slightly rotated over XYZ axis).
Any idea, values in TweenEngine are correct but somehow decal is not refreshing and rotating.
Answer: If you want to do it only once, you can do it like this:
decal.rotateX(angleX);
decal.rotateY(angleY);
decal.rotateZ(angleZ);

This will "add" the given angle to the current one though.
An alternative way would be to use the rotation Quaternion of the Decal:
decal.getRotation().setEulerAngles(yaw, pitch, roll);

The following image shows what "yaw", "pitch" and "roll" means:
Roll, pitch, yaw http://i.msdn.microsoft.com/dynimg/IC79189.gif
EDIT: I've just seen the JavaDoc of Decal.getRotation() and it says that the returned quaternion should not be modified! I've also checked the code and every other method of Decal sets an internal update flag which will cause the decal to change the next time it's rendered. Decal.getRotation() does not set this flag and thus the changes to it won't get recognized.
It seems like currently there is no really clean and easy way to set the rotation on all three axes at the same time. A workaround might look like this:
decal.setRotationX(0);
decal.setRotationY(0);
decal.setRotationZ(0);
decal.rotateX(angleX);
decal.rotateY(angleY);
decal.rotateZ(angleZ);

It first resets all angles to 0 and then rotates on each axis while not overwriting any other axis.
Comment: Can you provide some code for rotating decal with TweenEngine?
I'm trying this...but nothing happens:

In get values:
returnValues[0] = target.getRotation().x;
returnValues[1] = target.getRotation().y;

In set values:
target.getRotation().setEulerAngles(newValues[0], newValues[1],target.getRotation().z);
Comment: Sorry, I haven't used TweenEngine myself.
Comment: Ok, tnx! I will update my question. Your aproach works, but it's not animatable yet :)
Comment: I have managed to get correct values from TweenEngine, but decal is not refreshing. Why I cant rotate decal continiously?
Comment: Oops, I've just noticed the JavaDoc of the `getRotation()` method. I'll update my answer.
Comment: Tnx for an idea. I will try that way.
Comment: It works. It's not the cleaneast way, but for now it's good enough. If someone finds out better way, I'm happy to hear about it.  Tnx again.
Comment: @Veljko I made a PR to add a method which does this in one line. (https://github.com/libgdx/libgdx/pull/2111)
Comment: Good idea! Now we just need to wait for devs to merge it. In the mean while I will use your aproach. Tnx again.


Proof that posterior does not depend on data breakdown

Question: Suppose one calculates a posterior distribution on some parameter $P(\theta\mid x)$ based on some prior. Now suppose we take that data and divide it into two parts, such that $x = x_1 \cup x_2$. Intuitively, breaking up the data must lead to the same posterior given the same prior, i.e. $$P(\theta\mid x) = P(\theta\mid x_1, x_2)$$
However it's not obvious from Bayes' Law that this is correct.
What are some ways to formally prove this?
Comment: This has nothing to do with Bayes, because it's just a statement about conditional probabilities.  It follows *immediately* from the standard definition, because the sigma-algebras generated by $x$ and $(x_1,x_2)$ are the same.
Comment: https://stats.stackexchange.com/questions/312474 explains the terminology and https://stats.stackexchange.com/questions/452524 explains what a product sigma algebra is.
Comment: @whuber - Woha. Would you be able to post a brief answer explaining that comment?
Answer: I don't think this is a proof, but just from playing around with Bayes' rule here's what I got:
$$
P(\theta|x_{1}, x_{2}) = \underbrace{P(x_{1}, x_{2}|\theta)}_{\text{Likelihood}} \, \underbrace{P(\theta)}_{\text{Prior}} \, c^{-1}_{1}
$$
where $c_{1} = P(x_{1},x_{2})$ is the normalization constant. But also,
$$
P(\theta|x_{1}) = P(x_{1}|\theta) \, P(\theta) \, c^{-1}_{2} \quad \Rightarrow \quad P(\theta) = c_{2} \, \frac{1}{P(x_{1}|\theta)} \, P(\theta|x_{1})
$$
where $P(\theta|x_{1})$ is the posterior of $\theta$ after only updating with $x_{1}$. Now you can plug this into the first equation:
$$
P(\theta|x_{1}, x_{2}) = \frac{c_{2}}{c_{1}} \, \frac{P(x_{1},x_{2}|\theta)}{P(x_{1}|\theta)} \, P(\theta|x_{1})
$$
But the second term is just conditioning the joint likelihood: $\frac{P(x_{1},x_{2}|\theta)}{P(x_{1}|\theta)} = P(x_{2}|x_{1},\theta)$. So overall,
$$
P(\theta|x_{1}, x_{2}) = c^{-1}_{3} \, P(x_{2}|x_{1},\theta) \, P(\theta|x_1)
$$
So the Bayesian updating in the second step (with $x_{2}$) is just Bayes' rule applied to a prior that is already conditioned on $x_{1}$, i.e. the posterior from the first updating.
Comment: The constants are determined by the probability adding to 1, so they can't be wrong. That is, if two densities are equal up to a multiplicative constant they must be identical
Comment: @NathanielBubis in my notation, $c_{3} = \frac{c_1}{c_{2}} = \frac{P(x_1,x_2)}{P(x_1)} = P(x_{2}|x_{1})$, which makes sense since this is exactly the normalizing constant you would expect when updating prior/posterior $P(\theta|x_1)$ with $x_{2}$.
Comment: The last step can be simplified further if you assume $x_2$ is independent of $x_1$, but you still have a term depending on $x_1$. It's not clear how this dependence fully cancels out with $c_1, c_2, c_3$.
Comment: @thomasLumley I realize that, but it would be nice to see that this is so directly.
Comment: With conditional independence of $X_1,X_2$ given $\Theta=\theta$ and just looking at proportionalities, I would have thought you have $\mathbb P(\Theta=\theta \mid X_1=x_1,X_2=x_2 )$ $\propto \mathbb P(X_1=x_1,X_2=x_2 \mid \Theta=\theta)\mathbb P(\Theta=\theta)$ $\propto \mathbb P(X_2=x_2 \mid \Theta=\theta) \Big(\mathbb P(X_1=x_1 \mid \Theta=\theta) \mathbb P(\Theta=\theta)\Big)$, i.e. updating the prior with the first set of data to give an intermediate posterior and then updating that with the second set of data to give the final posterior.
Answer: Start with the posterior given $x_1$:
$$P(\theta\mid x_{1})=\frac{P(x_{1}\mid\theta)P(\theta)}{\int_{\theta}P(x_{1}\mid\theta)P(\theta)d\theta}$$
Now the posterior given both $x_1$ and $x_2$:
$$P(\theta\mid x_{2},x_{1})=\frac{P(x_{2}\mid\theta,x_{1})P(\theta\mid x_{1})}{\int_{\theta}P(x_{2}\mid\theta,x_{1})P(\theta\mid x_{1})d\theta}=\dfrac{P(x_{2}\mid\theta,x_{1})\frac{P(x_{1}\mid\theta)P(\theta)}{\int_{\theta}P(x_{1}\mid\theta)P(\theta)d\theta}}{\int_{\theta}P(x_{2}\mid\theta,x_{1})\left(\frac{P(x_{1}\mid\theta)P(\theta)}{\int_{\theta}P(x_{1}\mid\theta)P(\theta)d\theta}\right)d\theta}$$
Because the internal integral is no longer a function of $\theta$, we can remove it outside the external integral in the denominator and it cancels out the same factor in the numerator. Moreover, since $x_{1}$ and $x_{2}$ are independent, we have that:
$$\begin{align}
P(\theta\mid x_{2},x_{1})&=\dfrac{P(x_{2}\mid\theta,x_{1})P(x_{1}\mid\theta)P(\theta)}{\int_{\theta}P(x_{2}\mid\theta,x_{1})P(x_{1}\mid\theta)P(\theta)d\theta}\\
       &=\dfrac{P(x_{2},x_{1}\mid\theta)P(\theta)}{\int_{\theta}P(x_{2},x_{1}\mid\theta)P(\theta)d\theta}=P(\theta\mid x) \quad\blacksquare
\end{align}$$


ERR_EMPTY_RESPONSE from web browser when accessing a URL in A Docker container

Question: I have set up a Docker container with a web server on port 5000 (HTTP).
What doesn't work:

When I try to access the web service from a web browser on my PC (which hosts the Docker), I get the error 'ERR_EMPTY_RESPONSE'
I have tried connecting with: http://localhost:5000, http://127.0.0.1:5000, http://<PC_IP_Address:5000, http://<Docker_Container_IP_Address>:5000, http://<Ethernet_adapter_vEthernet_(WSL)_IP_Address:5000>, but get the same error ('ERR_EMPTY_RESPONSE') with all these

What does work:

From my PC, I can run the container and telnet to 'localhost 5000' (it connects and shows a blank screen). When the container is offline, I cannot telnet to 'localhost 5000'.
From bash on the Docker container, I can run 'curl http://localhost:5000' and it returns HTML

These tests prove that the web service is running and there are no firewall issues.
The Docker image was built with:
# syntax=docker/dockerfile:1
##This is the Long Time Support (LTS) version, runs on Debian (https://hub.docker.com/_/node)
FROM node:16.16.0

# install app dependencies
#Install .net (https://learn.microsoft.com/en-us/dotnet/core/install/linux-debian)
##Add the Microsoft package signing key to your list of trusted keys and add the package repository.
RUN wget https://packages.microsoft.com/config/debian/11/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
RUN dpkg -i packages-microsoft-prod.deb
RUN rm packages-microsoft-prod.deb
##Install the runtime
RUN apt-get update && \
    apt-get install -y aspnetcore-runtime-6.0

# install app

# final configuration
ENV Authentication__FB__ClientId=myKey
ENV Authentication__FB__ClientSecret=myKey
ENV Authentication__Google__ClientId=myKey.apps.googleusercontent.com
ENV Authentication__Google__ClientSecret=myKey
ENV Authentication__Microsoft__ClientId=myKey
ENV Authentication__Microsoft__ClientSecret=myKey
ENV SendGridKey=myKey
ENV StorageConnectionString__blob=DefaultEndpointsProtocol=https;AccountName=mysite;AccountKey=myKey==;BlobEndpoint=https://mysite.blob.core.windows.net/;TableEndpoint=https://mysite.table.core.windows.net/;QueueEndpoint=https://mysite.queue.core.windows.net/;FileEndpoint=https://mysite.file.core.windows.net/
ENV Stripe__PublishableApiKey=mySecret
ENV Stripe__SecretApiKey=mySecret
ENV Stripe__WebhookSecret=mySecret
ENV Url=localhost
ENV VaultUri=https://mysite.vault.azure.net/

EXPOSE 5000

I have also run within the container:
cd wwwroot
npm install
curl -sL https://aka.ms/InstallAzureCLIDeb | bash
az login
dotnet Web.dll

The Container is started with both port 5000 mapped as port 5000.
Please can you let me know why I can't see the HTML page from my PC's web browser.
Comment: result of `docker logs ` please
Comment: Welcome to Node.js v16.16.0.
Type ".help" for more information.
Welcome to Node.js v16.16.0.
Type ".help" for more information.
Comment: What's the `CMD` the image runs?  If `docker logs` is just printing out the Node REPL banner, do you need to set something like `CMD node index.js`?  It also seems like you might not be `COPY`ing your code into the image so there might not be anything there to run.
Answer: I had to enter this from bash:
dotnet Web.dll --urls "http://:5000;https://:5001"


How do I avoid "anti-aliasing effect" when creating a PGraphics object that's smaller than the window, then scale it up to the windows size?

Question: When ran, the program displays a 3D sphere rendered in a P3D environment in the PGraphics object 'g', which is shown by taking the rendered PGraphics object and displaying it through the image() method in the main graphics context, which happens to be P2D.
The purpose of the program is to show how window size doesn't always correlate with render size. If you play an old Widows98 game in full screen, the game most likely will be rendered at 480p no matter what, so taking it into full screen just decreases the pixels per inch, plus making the image appear blurry. Which is fine, since fullscreen at 480p is preferred over windowed mode ( esp. if you're on 4K X_X )
the mouse's y position in the window changes the 3d camera's field of view, and the x position changes the rendering resolution of the P3D context used to display the sphere. Additionally, the P3D context is drawn in the main (P2D) context through the image() method, and is 'forcefully'. displayed at the size of the window. So if the P3D render resolution is smaller than the window, then it will start to look blurry and more pixelated, and if the render resolution is larger, you get a strange sharpening effect.
Now, my program works fine as it is, but. Another purpose of the program is shadowed by this issue, it's how the 'crispness' of the sphere fades as the render resolution decreases. You might say that it's clearly shown, but what I'm looking for is an image where there is no "anti-alias" effect going on. I want the image to preserve the pixels as the resolution gets smaller, so you can see the actual shape of the sphere at say, 50 x 50 pixels.
The noSmooth() method doesn't seem to work, and before you tell me to just do
g.loadPixels();

and then do a double for loop to draw the raw pixels to the 2d context. No, it's sloppy. I know that there must be some reason why this blurring is going on. I'm hoping that it's the image() method and that I should be using a different method or I should add another method before it to remove image blurring.
PGraphics g;

void setup(){
  size(1000,1000,P2D);
  frameRate(1000);
  noSmooth();
}

void draw(){
  background(200);
  float res = map(mouseX,0,width,0.75,128);
  if (res==0) {
    res=1;
  }

  g = createGraphics((int)(width/res),(int)(height/res),P3D);
  g.noSmooth(); // is this thing working?????
  float cameraZ = ((height/2.0) / tan(PI*60.0/360.0));

  g.beginDraw();
    g.perspective(radians(map(mouseY,0,height,0.1,160)), width/height, cameraZ/10.0, cameraZ*10.0);
    g.camera(g.width/2.0, g.height/2.0, (height/2.0) / tan(PI*30.0 / 180.0), g.width/2.0, g.height/2.0, 0, 0, 1, 0);

    g.background(200);
    g.translate(g.width/2 ,g.height/2);
    g.sphere(100);
  g.endDraw();

  image(g, 0, 0, width, height); // this is where it all comes together
  text("rendering resolution: "+g.width+" x "+g.height,0,14);
  text("fps: "+frameRate,0,14*2);
}

Answer: Replace g.noSmooth() with ((PGraphicsOpenGL)g).textureSampling(2);
Credits go to Vallentin as I oddly enough had the same question with the P3D renderer
Comment: I knew you would come along to save the day! +1
Comment: Oh cool, I'll have to update my code now when I get the chance.
Answer: (Edit: This solution fixes the problem in the default renderer, but the OP is using the P2D renderer. The solution should be similar, so if somebody knows how to change the image interpolation mode in opengl, that's the answer.)
This is not really caused by anti-aliasing. It's caused by image scaling.
Also, it's much easier to help if you provide a MCVE, like this one:
PGraphics buffer;

void setup() {

  size(1000, 1000);

  buffer = createGraphics(100, 100);
  buffer.noSmooth();
  buffer.beginDraw();
  buffer.background(255);
  buffer.line(0, 0, width, height);
  buffer.endDraw();
}

void draw() {
  background(0);
  image(buffer, 0, 0, mouseX, mouseY);
}

This code exhibits the same problem, but it's much easier to understand and work with.

Anyway, tracing through Processing's code, we can see that the image() function eventually calls the imageImpl() function in the PGraphics class here.
This function then draws your image using this code:
beginShape(QUADS);
texture(img);
vertex(x1, y1, u1, v1);
vertex(x1, y2, u1, v2);
vertex(x2, y2, u2, v2);
vertex(x2, y1, u2, v1);
endShape();

The endShape() function is then implemented in the renderer, specifically the PGraphicsJava2D class, which calls the drawShape() function here:
protected void drawShape(Shape s) {
    if (fillGradient) {
      g2.setPaint(fillGradientObject);
      g2.fill(s);
    } else if (fill) {
      g2.setColor(fillColorObject);
      g2.fill(s);
    }
    if (strokeGradient) {
      g2.setPaint(strokeGradientObject);
      g2.draw(s);
    } else if (stroke) {
      g2.setColor(strokeColorObject);
      g2.draw(s);
    }
}

Finally, that shows us that the Graphics2D.fill() function is being called, which is what actually draws your function.
The "problem" is that Graphics2D.fill() is scaling your image using an algorithm that causes some blurriness. We can consult the Java API and Google to figure out how to fix that though.
Specifically, this tutorial shows you how to set various rendering hints to change the scaling algorithm. We can use that in Processing like this:
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import processing.awt.PGraphicsJava2D;

PGraphics buffer;

void setup() {

  size(1000, 1000);

  buffer = createGraphics(100, 100);
  buffer.noSmooth();
  buffer.beginDraw();
  buffer.background(255);
  buffer.line(0, 0, width, height);
  buffer.endDraw();
}

void draw() {

  if (mousePressed) {
    Graphics2D g2d = ((PGraphicsJava2D)g).g2;

    g2d.setRenderingHint(
      RenderingHints.KEY_INTERPOLATION,
      RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
  }

  background(0);
  image(buffer, 0, 0, mouseX, mouseY);
}

First, we import the classes we're going to need. Then we get to the Graphics2D instance in the renderer, and finally we call its setRenderingHint() function. I wrapped it in an if(mousePressed) so you could easily see the difference. When you click the mouse, interpolation is set to nearest neighbor, and you no longer see the blurriness.

Also notice that my code uses the g variable that's inherited from the PApplet superclass, so you would have to change your g variable so it's no longer hiding it.
Comment: Thank you, sorry for being rude. I just don't like when people give me solutions that don't fix the problem directly, and instead just skip around the problem. I like your answer.
Comment: also, it throws a ClassCastException PGraphics2D can't be casted to PGraphicsJava2D. I think it's because I'm using P2D, and i can't remove that.
Comment: @Andrew900460 You'll have to find the corresponding render-specific class then. It's all in the GitHub link I included.
Comment: @Andrew900460 You'll have to figure out how to set the image scaling algorithm in the OpenGL renderer. The process is the same as I outlined in my answer though: trace through the code to find what the code is actually doing, and then use Google to figure out how to change the image scaling algorithm.
Comment: My searching has led to this. http://processing.github.io/processing-javadocs/core/processing/opengl/PGraphics2D.html#hint-int-

I added this ((PGraphics2D)getGraphics()).hint(2);
to my code and nothing changed.

if I used 1 instead of 2 it would throw an error telling me it was a different enum. I can't find where the enums are defined.
Comment: I know I can't give up, but I have looked through all relevant pages and I can't find anything that works
Comment: after a little more searching I came up with this. It doesn't work... Unless I'm using it incorrectly.

`((Graphics2D)((BufferedImage)g.getNative()).getGraphics())`

This will return a Graphics2D object that technically came from the PGraphics2D objects.

and called the rendering hint method on it. No errors, but no results.

`.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);`

I'm probably just gonna resize it manually.
Comment: @Andrew900460 You might also try calling the `scale()` function instead of resizing manually.
Comment: @Andrew900460 Here's another idea: You can create a `PGraphics` with the `P2D` renderer, and draw whatever you want to that. But keep the default renderer for the main sketch, so that my answer would still work.


Alinhar textos com divs diferentes na mesma linha

Question: Olá, estou com um problema, criei uma popup apenas para newsletter, porém ao passar ela para o html, com css, precisei usar 2 divs (tentei usar todas as formas possiveis, fonts, p, span) diferentes para mudar a cor e sombra do texto. Não sei se vão conseguir entender mas preciso alinhar 2 divs na mesma linha. Sem querer, segue como está:  agora segue como deveria estar:
Peço que levem em conta apenas o título "Promoções exclusivas direto no seu email" o resto irei passar assim que solucionar esse problema.
Obrigado a todos que leram e tenham um ótimo dia.
Comment: Votando para fechar por ter sido [um erro de digitação](http://pt.stackoverflow.com/a/117246/4808).
Answer:

.text p{
  font-size 20px;
  color: #000;
}
.text p i{
  font-size: 30px;
  color: #ff0;
}
.text{
  float: left;
  width: 100%;
  }

Promoções exclusivas direto no seu email

Tenta colocar algoo assim para o texto, coloca dentro de alguma tag e aplica o css na tag. Irá funcionar, trabalhe com os floats!
Comment: Funcionou certinho e deixou mais organizado kk obrigado
Answer: Apesar de você já ter se auto respondido, acho interessante deixar uma resposta para quem sabe lhe tirar uma duvida que restou, ou ajudar a esclarecer melhor.
O seu problema estava ocorrendo pois ambos os elementos estavam com a propriedade display: block, e quando se assume essa propriedade não é possível alinhar dois elementos lado a lado. Sendo assim, bastava você colocar esta propriedade como display:inline-block que o problema estaria resolvido.
Obs: É importante lembrar que existem elementos que já são criados com a propriedade display:block e outros não. A seguir estão dois links para você dar uma olhada...

https://jsfiddle.net/j1agndmc/2/
http://pt-br.learnlayout.com/display.html
Comment: Obrigado pela complementação e pela ajuda, agradeço
Comment: De nada cara, estamos aqui para isso!
Answer: Sempre que eu faço uma pergunta por aqui, o problema se soluciona sozinho haha, bom pra quem tem o mesmo problema que eu e já tentou muitas formas em css e nenhuma dava certo, é bem improvável que alguém vai ser tão "lesado" como eu de esquecer que adicionou tag  no próprio HTML dando conflito e bugando tudo, não sei se display: block faz isso, porém deu esse problema e só foi retirar que o problema foi solucionado.
Obrigado a todos !!!


Pandas - Merge and Groupby different dataframes and create new columns

Question: Have  n  number of dataframes with n number of City columns.
df1:
 ID      City      City1    City2     ....   CityN
 444x    Lima                DC
 222x    Rica      Dallas
 555x    Rio       London
 333x    NYC       Tokyo
 777x    SF                 Nairobi

df2:
 ID      City      City1    City2     ....    CityN
 000x    Lima                Miami
 888x    Cct      Texas
 999x    Delhi
 444x    Tokyo     Ktm
 333x    Aus                 Paris

dfN:
 ID      City      City1    City2     ....   CityN
 444x    Lima                DC
 333x    Rica      Dallas
 555x    Rio       London
 666x    NYC       Tokyo
 777x    SF                 Nairobi

I have tried merging the dataframes one by one but the City column values get overwritten by the last dataframe values.
dfOutput=df1.merge(df2, how='left', on='ID')
What I would like is retain all these City1, City2, ...CityN  column values. I have listed the example output below.
 ID      City1    City2    City3  City4     City5     City6
 444x    Tokyo     Lima     DC     Miami     Ktm
 333x    NYC       Tokyo     Aus     Paris   Rica     Dallas

And so on for the remaining IDs. I also tried using groupbyID provided from another question here in SO.
cities = df.groupby('ID')['City'].apply(lambda x: pd.Series([city for city in x])).unstack()
Thanks for your help.
Comment: Where's KTM for 444x?
Comment: Thanks @itzy, edited it. I have some sensitive values so had to use placeholder values.
Comment: It looks like you just want unique cities for each ID. Might be easier to just iterate over rows and read values into a dictionary and then create a DataFrame at the end.
Comment: Yeah, I thought of that and am currently working on it. I was wondering if SO could help with another solution as well.
Answer: IIUC you could use pd.merge without left parameter:
In [14]: df1
Out[14]:
     ID  City   City1    City2
0  444x  Lima       -       DC
1  222x  Rica  Dallas        -
2  555x   Rio  London        -
3  333x   NYC   Tokyo        -
4  777x    SF       -  Nairobi

In [15]: df2
Out[15]:
     ID   City  City1  City2
0  000x   Lima      -  Miami
1  888x    Cct  Texas      -
2  999x  Delhi      -      -
3  444x  Tokyo    Ktm      -
4  333x    Aus      -  Paris

In [16]: pd.merge(df1, df2, on='ID')
Out[16]:
     ID City_x City1_x City2_x City_y City1_y City2_y
0  444x   Lima       -      DC  Tokyo     Ktm       -
1  333x    NYC   Tokyo       -    Aus       -   Paris

Then you could rename your columns for the resulting dataframe:
cols = ['ID'] + ['City' + str(i) for i in range(1, len(df3.columns))]

In [21]: cols
Out[21]: ['ID', 'City1', 'City2', 'City3', 'City4', 'City5', 'City6']


Sharepoint Tracing Service lost trace events

Question: I have a problem of a Sharepoint Server that regularly stops logging, instead the logfiles (in 12\LOGS) only contain

05/05/2009 14:17:09.12    wsstracing.exe (0x0B24)                     0x0254  ULS Logging                     Unified Logging Service         uls1    Monitorable Tracing Service lost trace events.  Current value 11.

(Current value fluctuates a lot)
Any ideas how that can be troubleshooted? Restarting the service or server fixes, but only for a few days, and I don't know what could be the cause of this?
Comment: We have the same problem. The tracing service also would't stop sometimes, so a reboot is needed.
Answer: There is a bug open for this issue:
https://connect.microsoft.com/feedback/ViewFeedback.aspx?FeedbackID=408671&SiteID=428
No fix available yet I'm afraid other than restarting the services.
Comment: The link seems to be broken.
Comment: hmm, after I enter my Windows Live ID - it works fine here...
Answer: It's usually due to low memory conditions on the server. However it can sometimes just happen...
Comment: The logging stops _completely_ when you have less than 200MB of free space on C: regardless of where you've set up the log to be written. But it writes a notification to the application events about that.


How does data synchronization work and how do I use it in server-client applications?

Question: I will demonstrate the problem on a real example so the situation:

there is a website (eg: real example:
http://www.news.com.au/breaking-news)
From the website I want to parse data "last breaking news". This
should be a service (based on php, c # aspx ...) do that is by our
side written off. The data are parsed and prepared in XML or
similar.
There are a number of clients (desktop variant, mobile ...), when
the news with a new PUSH (like an exchange server does that) should
be notified.

I do not know exactly how to do the connection / synchronization between 2) and 3).
One idea would be sent by a client in an interval and then requests for the service needs to make a PUSH.
Or is there some other variant to solve this? Maybe so that the client is waiting and the only large part of the service intervals made without the requests?
Are there any specific approaches, ideas, proposals?
Thanks in advance,
best regards.
Answer:
The client (i.e. Android app) is quering the server periodically, sending a timestamp value. The server compares the timestamp with its data and replies only with relevant (newest) data.
Push notifications: on Android you can use C2DM. How to do it in PHP? See:
C2DM implementation PHP code


How to connect sql azure with android app and sql server

Question: Wanna know how to connect sql azure with android app and sql server?
STEP 1: I want to use real-time sync between exist database (dbo schema and other) in sql server and azure mobile services/azure sql database.

If I use Microsoft SQL Data Sync Agent to connect it, What do I have
to do? e.g. add an id column to an existing table.
Do you have other way better than this or any other suggestions ?

STEP 2: I want to connect android app to azure mobile services or azure sql database.

How to connect android app to an existing Azure SQL table (from previous step) with Windows Azure Mobile Services.
I'm trying to connecting SQL Azure from my android application with jdbc and jtds, But it doesn't work. Do you have other way or any other suggestions ?
Answer: You are working with Android . So, you need to go as:-
switch to Android Studio , if you already did it then it's fine.
Use tutorials provided by Microsoft Azure Mobile Services.
Here is the link to get started for Android :-
For brand new DataBase and new Mobile Services :-
https://github.com/Azure/azure-mobile-services/blob/master/docs/mobile-services-android-get-started.md
EDIT : Broken links updated
Comment: Links are broken
Answer: This is the answer to your step 2
If you don't want to use a brand new database and want to use your existing azure database then follow this link. This is a jtds method and I followed it and it worked for me.
You will use your jdbc connection url that comes with your database instance on azure portal with minor changes in it which are explained in the link. Your portal profile password and username will also be used in the connection url so keep in mind hackers might get a peak to it if they examine your application apk.
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. [Answers that are little more than a link may be deleted](https://stackoverflow.com/help/deleted-answers).


How to prove "the position of any subset range of an ordered set, after random permutation, cannot be determined if the permutation unknown"?

Question: To clarify the problem, for example, the subset (consecutive) range $S=\{2, 3, 4\}$ of the set $U=\{1, 2, 3, 4, 5, 6, 7\}$. Given $U$ is ordered, the position of $S$ corresponding to $U$ can be determined, i.e., the starting position is $2$. Consider that $S$ is obfuscated by some random permutation, say $\delta(S)$. If the permutation $\delta$ is unknown to a distinguisher $P$, only given $U$ and $\delta(S)$, $P$ will not be able to infer the position of $S$ corresponding to $U$.
The conclusion seems straightforward, but I would like a rigorous mathematical proof. Intuitively, the mathematical induction can be used. I have a rough idea like, assume $|U|=m$, for any $|\delta(S)|=1$, the position of $\delta(S)$ corresponding to $U$ cannot be determined. Then suppose it holds for $|\delta(S)|=m-2$. Then when $|\delta(S)|=m-1$, it is still valid. Anyone can help me with it? Better provide a complete proof or at least some rough ideas.
Comment: What is exactly a position? Do you mean minimal element? Also, what does "given $\delta(S)$" mean? Note that speaking about sets and permutations seem problematic, since the order in a set does not matter.
Comment: maybe "set" is not a good term here. What I am trying to say is an ordered sequence U. $\delta(S)$ means applying the permutation to S.  The position of S according to U can be referred to as which part of U, S belongs to. Or can use the starting element of S to indicate the position as  shown in the question.
Answer: Let me rephrase your problem: you consider a finite sequence $U=(u_1,\dots,u_N)$ and a subsequence $S=(u_p,u_{p+1},\dots,u_{p+l})$ of consecutive (*) terms of $U$ is extracted from $U$, without your knowledge. The only thing you know is a permutation $S_\sigma=(u_{\sigma(p)},\dots,u_{\sigma(p+l)})$ of $S$ by a permutation $\sigma$.
Your question is: can I recover $S$ knowing $U$? How to prove that I cannot recover $S$?
The thing is: in general, you cannot recover $U$. To justify it, a counter-example is enough: imagine that $U=(1,2,3,2,1,3,2,3,1,2)$ and $S_\sigma=(1,2,3)$. Since $U$ contains all possible permutations of $(1,2,3)$, then you cannot know which one you started from.
Can you prove that you can never recover $S$? Nope, since if $U$ has some very precise structure, you may be able to do it. For example, if $U$ is ordered as the example above, $S$ is also ordered, so you can determine it by reordering $S_\sigma$.
(*): correct me if I am wrong on that point, but it doesn't really change the problem.
Comment: Thank you. I think it is still my fault that some additional conditions are missed in the original question. With your notations, the terms of the sequence $U$ increases monotonically without duplication, like integer sequence   $\{1,2,3,...,N\}$, so the subsequence  $S$ is also monotonically increasing. Apart from applying a random permutation \sigma to S, a masking one-way function $f$ is also used to hide the original term u_i in U and you cannot find u_i given f(u_i). For example, U={1,2,3,4,5,6} and S={2,3,4}. After applying f and \sigma, maybe S_{sigma&f}={f(3),f(2),f(4)}.
Comment: Given only U and without the knowledge of f and \sigma, you cannot recover S


Join Production Server 2008 to 2003 domain

Question: I administer a production server for a .com. It is live right now.
Server 2008 x64
IIS 7
SQL 2008
PHP
MYSQL
I have another server which is a DC Server 2003 x86 and a warm standby for the website, sql, DFS, exchange queue.
In order to get DFS going to transfer user photos and other content I need it in the domain.
My question is,
What preparations do I need to do to the production server to allow a smooth transition onto the domain?
Things such as permissions for the website. I do not want to be running around resetting all the permissions. The Group Policy on the DC is completely default.
Should I add the DNS manually or allow it to add itself?
Anything else I left out.
Answer: You should just join the server to the DC's domain; if there are no custom GPOs (as you said), almost nothing will change in the server's behaviour. You will of course be able to log on to the server using domain user accounts, but it will keep all of its current local user database.


How to theme a list based field

Question: I have a text field attached to my node.
The user can add an unlimited number of values.
I want to out put all the values as a HTML list in my node.tpl.php file.
Contemplate module suggests to use the following code to out put the field:
<?php print $node->field_body_list['und'][0]['safe_value'];?>

This, however, has two problems:
1) It only outputs the first value of the field.
2) It uses UND, which is apparently bad.
I have tried using theme developer, but it doesn't produce any code that I can use in my node.tpl.php file.
Any help would be greatly appreciated it.
Answer: It's easiest to stay out of node.tpl.php for this one and instead use a field specific template file.
You'll need two copies of /modules/field/theme/field.tpl.php in your theme folder. The first is an exact duplicate with no changes and the same filename. The second you should rename to field--field-body-list.tpl.php. Consult Drupal 7 Template Suggestions if that filename doesn't work for you.
In field--field-body-list.tpl.php I would change the div with class="field-items" to
 and the div with class="field-item" to
.

How to theme a list based field


Manipulating variables in Processing.js from outside the canvas element

Question: I made a certain piece of Processing code that draws a symbol based on parameters set in setup().
I want to make a web page, using Processing.js, that will allow me to change those parameters (all floats) from text boxes in the browser and then redraw.
Is it possible to do?
Comment: Sure it's possible, go for it!
Answer: Yes, you can. Please check out the example and read the official documentation. JSFiddle code:

Your message!

<canvas id="processing-canvas"></canvas>


"Cannot read property 'icons' of null"

Question: With Drupal 8.0.0-rc2, no matter what, I get this error in the JS console:

Uncaught TypeError: Cannot read property 'icons' of null

I think I have defined everything correctly, so I don't know what causes this error or what I missed.
Plugin definition:
<code>/**

* @file
 * Contains \Drupal\codesnippet\Plugin\CKEditorPlugin\CodeSnippet.
 */

namespace Drupal\codesnippet\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginBase;
use Drupal\ckeditor\CKEditorPluginConfigurableInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\editor\Entity\Editor;
use Drupal\Core\Url;

/**
 * Defines the "codesnippet" plugin.
 *
 * @CKEditorPlugin(
 *   id = "codesnippet",
 *   label = @Translation("CodeSnippet"),
 * )
 */
class CodeSnippet extends CKEditorPluginBase implements CKEditorPluginConfigurableInterface {
  /**
   * {@inheritdoc}
   */
  public function getFile() {
    return drupal_get_path('module', 'codesnippet') . '/js/plugins/codesnippet/plugin.js';
  }

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {
    return array(
      'codeSnippet_dialogTitleAdd' => t('Insert Code'),
      'codeSnippet_dialogTitleEdit' => t('Edit Code'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getButtons() {
    return array(
      'CodeSnippet' => array(
        'label' => t('CodeSnippet'),
        'image' => drupal_get_path('module', 'codesnippet') . '/js/plugins/codesnippet/codesnippet.png',
      ),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state, Editor $editor) {
    $form_state->loadInclude('editor', 'admin.inc');

    $styles = $this->getStyles();

    $form['highlight_style'] = array(
      '#type' => 'select',
      '#title' => 'Highlightjs Style',
      '#description' => t('Select a style to apply to all highlighted code snippets. You can preview the styles at !link.', array('!link' => \Drupal::l('https://highlightjs.org/static/demo', Url::fromUri('https://highlightjs.org/static/demo/')))),
      '#options' => $styles,
      '#default_value' => !empty($form_state->storage['editor']->settings['plugins']['codesnippet']['highlight_style']) ? $form_state->storage['editor']->settings['plugins']['codesnippet']['highlight_style'] : 'arta.css',
    );

    return $form;
  }

  /**
   * Returns available stylesheets to use for code syntax highlighting.
   */
  private function getStyles() {
    $styles = preg_grep('/\.css/', scandir(drupal_get_path('module', 'codesnippet') . '/js/plugins/codesnippet/lib/highlight/styles'));
    $style_options = array();

    foreach ($styles as $stylesheet) {
      $style_options[$stylesheet] = $stylesheet;
    }

    return $style_options;
  }
}
</code>
The icon on the toolbar when editing the text format appears just fine, I can drag it in and out of the active toolbar, and my settings form shows. But due to the JS error generated, it does not work.
The plugin used is available on ckeditor.com, I dropped it into the plugins/codesnippet/js folder untouched.
I can't find any other examples of custom plugins using anything called 'icons'.
Answer: @Kevin are you sure the fix was due to CKEditor being upgraded in that Drupal version? I'm getting the same kind of issue trying to add the Link plugin, on Drupal 8.1.1, which is using CKEditor version 4.5.8.
Trying to find more insight on this issue.
edit: upon manually upgrading CKEditor to version 4.5.9 I'm getting much more illuminating error messages:

Uncaught Error: [CKEDITOR.resourceManager.add] The resource name "link" is
already registered.
Uncaught TypeError: Cannot set property 'getLinkAttributesParser' of undefined
Uncaught TypeError: Cannot read property 'icons' of null

So looks like this is colliding with the Link plugin that comes with Drupal (which is lacking some features). So I'll find a way to sidestep this name space collision and will update here.
edit: renaming the plugin proved unfruitful. Still getting:

Uncaught TypeError: Cannot read property 'icons' of null
Comment: I still see it sometimes, but not as much as before.
Answer: Latest release of Drupal (8.0.0-rc3) fixes this. CKEditor was upgraded.
Answer: You can check the Click to tweet module here-> ( https://www.drupal.org/project/tweet_text)
It also does somewhat like you need:

The easiest way to promote, share & track your content on Twitter.
Provides an input filter and CKEditor plugin for making text in
  content tweetable, just by clicking on the sentence or phrase itself!
  It uses the CKEditor plugin through which you can add the link for
  text ,userhandle and the description in any sentence or paragraph
  ,which is to be tweeted.

Disclaimer: I wrote this module.

"Cannot read property 'icons' of null"


(1/√π)/√⅔ as a time signature?

Question: I recently found this article on wikipedia about lists of musical works in unusual time signatures and the first unusual time signature is (1/√π)/√⅔.  I looked up the piece that was listed as having that time signature  which was Conlon Nancarrow's Study for Player Piano 41a and listened to it and could not begin to count it at all.
So is the time signature actually useful and if it is, is there a specific name for time signatures like this?
Comment: A key feature of this is that both the top and bottom are irrational numbers, thus no notated beat ever aligns exactly with the beat, nor do any of the bars.
Comment: For those interested, here's a link that discusses the study. It includes an image of the first page of the original manuscript: http://depthome.brooklyn.cuny.edu/isam/publications/AMR/2012_Fall/article3.html
Here's a rendition of the piece on youtube: https://www.youtube.com/watch?v=Y3qO6-Cqzhg
Answer: I think the author of that Wikipedia page has rather misinterpreted Nancarrow's title page for the Study (linked on Roland Bouman's comment to the question). (1/√π)/√⅔ refers to a tempo ratio between two voices, not a time signature.
Nancarrow was rather obsessed with canons. The canon is a form where multiple voices each play the same music at some time offset (i.e. the second voice enter a bar after the first). Nancarrow wrote tempo canons where the voices are at various tempo ratios growing more and more complex over his career.
The Study for Player Piano No. 41 is structured in 3 movements, 41A and 41B are two voice canons and 41C is both 41A and 41B played together.
41A has a tempo ratio of (1/√π)/√⅔, which is what the Wikipedia page mentions. This does not refer to a time signature, a regular grouping of beat stressing, but to the ratio between the two voices in the canon. So, for example, if the first voice was at ♩=100, the second would be at ♩= 100 * (1/√π)/√⅔ ≈ 69.098829894267098
41B is in a similarly ridiculous ratio of (1/(π^1/3)) / ((13/16)^1/3) and the final movement Nancarrow notates as having a ratio of 41B/41A = [(1/(π^1/3)) / ((13/16)^1/3)] / [(1/√π)/√⅔]
The article Roland Bouman mentions has much more detail and analysis of what Nancarrow actually intended by these numbers, and how precise he was actually intending to be. The most interesting section, especially for those noting how pretentious such notation is (which I think is an accurate observation) is a quote from Nancarrow about how he picked the ratio:

At that time [of the composition of Study No. 41], I was looking for some irrational relationships. I had this book of engineering, and I looked up some relations that were roughly what I wanted. I didn't want something that was so separated they didn't even relate, or too close that you couldn't hear it. I found that those particular numbers, transferred into simple numbers, gave the proportion more or less that I wanted. Not exact, but near enough. This was before I had written a note.

and the author's commentary:

Of course, by their very definition, irrational numbers cannot be specified; in order to have produced the Study Nancarrow had to approximate the proportions. Why not, then, simply use the rational equivalents? Part of the attraction must have been the gorgeous complexity of the original proportional structure. For a lover of numbers like Nancarrow, the proportion is a thing of beauty. And, of course, π means something even to the lay person: it is the ratio of the circumference of a circle to its diameter. Nancarrow gives no indication, however, that he had anything grander in mind than simply finding "some relations that were roughly what I wanted."
Comment: Hey thanks! I didn't have the time or urgence to read the article, I think you did a great summary. Much obliged :)
Comment: Even if metronomes were only accurate to +/- 10%, the ratio between the tempos of two parts might be meaningfully expressed much more accurately.  Although ratios like 3:2 or 2:1 would be more common, an irrational tempo ratio, if played accurately, would denote rather specific timing; a change of 0.03% in the tempo ratio would by the end of a five-minute piece represent a very audible (90ms) difference in timing.  I think using two unrelated irrational numbers in the ratio was probably overly pretentious, but...
Comment: ...it's not hard to imagine how transcendental ratios, if played accurately, could lead to interesting patterns where one voice sometimes seems to lead the other and sometimes trail it.
Answer: I would say that the specific name is "experimental."  My feeling is that it comes from the school of thought that attempts to turn the back on musical tradition and come up with something new.  There's a certain arrogance to it in my opinion (famously, Schönberg said upon coming up with his rather superficial tone-row concept that he had assured the supremacy of German music for the next hundred years); musical architecture is based on a great deal of trial and error and it's unlikely that some inspiration would turn it all on its head and replace it just because someone wants that to happen.
For example, there's John Cage working with randomness.  He would do things like drop a string to determine the shape of a musical line, and often used the I Ching as a means of composing music.  (Please note that I take wisdom where I find it, and there's plenty in the I Ching IMHO.)  The thinking behind using randomness is to get oneself out of one's own way, so to speak, and allow some deeper influence to contribute to the composition.  However, people have been doing that in some way ever since music began; more common is the idea of standing aside and inviting "the Muse" to enter.  Then there's Bach, with his "I play the notes as they are written, but it is God who makes the music."
I guess my feeling is that there came a point where we decided that "anything goes" and wound up having this rather adolescent departure from the core of music (whatever that is), and we're hopefully getting back to work.
Comment: You criticize Nancarrow for being arrogant and adolescent in his desire to revolutionize music and replace all that had gone before him. There's just one problem: he had no such desire; it's all in *your* head, not his. You're criticizing a strawman. He wasn't trying to revolutionize anything; he was just writing the kind of music he liked to write. He barely even showed it to the world because nobody seemed to be interested and he was living practically as a recluse. To accuse him of arrogance is quite breathtaking. He was quite close to disappearing without a trace.
Comment: I would argue that this is not arrogant or adolescent.  Einstein had to turn his back on the scientific conventions to come up with Relativity, no?  How does one take the next step?  To conform to the standards and conventions of today, is to merely take baby steps forward.  Yes, all of these conventions exist for a reason but how will we ever know what is out there if no one ever takes the 'arrogant' step outside? Further, Schönberg may have been arrogant with his statement of German supremacy but the step to create tone rows was a brave and creative one, however unpopular serialism has been.
Comment: David is correct about Nancarrow's reclusiveness. The comparison to make with Einstein is not that he had to "turn his back on convention" or anything of the sort, but that in order to make any sense of what he discovered, you needed a Ph.D. in theoretical physics--a layperson to this day may say the notion of curved spacetime is "arrogant", "nonsensical", or "juvenile". There may well be composers who spew out garbage that to the layperson is indistinguishable from Nancarrow, Berio, Schoenberg, etc... but it's not up to the layperson to make that judgement.
Comment: Einstein didn't try to refute Newtonian physics (nor did he), just to expand on it (which he of course did). Now, it isn't the entire body of 20th century music that is arrogant, nor is it Schönberg's entire body of music: he succeeded in spite of himself. But it is arrogant to say things like we can do whatever we want, because music can't be logically defined. We have, for example, John Cage's 4'33" presented as music, and also the inherent superficiality of serialism. These strike me as clever rather than profound, and it is that confusion of cleverness and profundity that I find arrogant.
Comment: Just want to point out that there is **nothing** superficial about using tone rows to create music.  If they are superficial, then so too are all other scales and systems of musical creation.
Comment: Enough of the physics comparison. The idea is that the new standards are based on taking the next step. Sometimes that step is a little exaggerated but that is how we get to the next level. 4'33" is certainly an exaggeration on the concept of indeterminism but arguably genius. It seems more like performance art than music but the concept is that the noise of the room that is the result of a lack of sound is the music, which works well in a Classical venue. The exaggeration may not become the new norm but one must be brave to take the step, not necessarily arrogant.
Comment: After rereading this I want to make clear I am in no way calling Bob or anyone else here a layperson, but I think it's fair to say none of us are renowned avant garde composers.
Comment: Einstein did not refute Newtonian physics in the same way that Nancarrow didn't refute the convention of having a time signature to begin with. He did disregard a lot of the conventions of the time, such as those of time.
Comment: a wonderful answer to a absolute irrational question!
Answer: This is either compositional wanking or a composer having a joke at literalists' expense.  Since any metronome (or human) can only approximate any time period to some precision, the beat will always be a rational part of a second.  For that matter, the repeatability of the beat will only be exact to some rational limit.  So claiming you want the beat to be, say, the first real root of an N-th order polynomial divided by the value of the j-th Bessel function of the second kind evaluated at sqrt(37) ,  is pointless.
Personally, I view it as a cute joke, and would go on to play the piece at whatever speed felt appropriate.
Answer: Wow, what a great question!
Sorry, I don't know of a specific name for this kind of time signature.  Judging whether this is a useful time signature is almost a philosophical question.  If the main function of a time signature is to provide performance information to the performer, then no, this isn't very useful.  But, a time signature can also be used to describe an aspect of the rhythmic organisation of a piece, independently of any performance considerations.  I would argue that this is the sole purpose of the time signature in this case.  After all, the score originally served little purpose as a performance guide, as the piece is written for player piano - no score, and so time signature, was originally needed for performance of the piece, with the piano roll supplying the information necessary for performance.
Instead, the time signature here is merely descriptive, giving information about this piece.
And, of course, because no performer has to use the time signature, there is no need for the time signature to actually reflect rhythms actually found in the music.  Equally, the actual rhythms of this piece could be forced to fit into another time signature, or be presented in a score with no time signature.
I love the idea of trying to count along with a piece in this time signature!  I haven't listened to Nancarrow pieces for a while, so can't remember this one, but presumably one of the most interesting aspects of a piece like this is the rhythmic complexity allowed by mechanical performance; the ear is presented with something which we can't easily count along with.  And so, if there is no easily discernible pulse or simple rhythmic organisation, the time signature becomes essentially meaningless; any time signature would do in this case, so why not one as outlandish as this?  I can't help thinking that this is supposed to be humorous, like one of Satie's performance markings, even if it does clearly relate to specific temporal relationships in the music.
Comment: I can think of a few names for this time signature, but none that I will mention here.
Comment: Right! It would be good to see how many beats Nancarrow fits into each bar in the score. But, the piano roll itself could have any arbitrarily complex bar lengths and note lengths, as long as they are measurable when creating the piano roll. It doesn't really matter if this then makes perfect sense when presented in conventional notation.
Comment: But how is it interpreted? It could be seen as somewhere between 5/8 and 6/8-ish, but what that information would give anyone is not clear.

(1/√π)/√⅔ as a time signature?


how to display the machine name of module at /admin/modules?

Question: I use Drush to enable and disable module, to do this I need to know the machine name of the module.
At /admin/modules I can see the list of modules, but this list doesn't show the machine name, jut the human readable name.
I created a view to list the machine name of modules but I'd like to have it at /admin/modules. Is there any way to do this?
Comment: The folder name will always be the machine name.
Comment: incorrect. The machine name is the .info's filename.
Answer: If you don't mind going low-tech you can just look at the value of the checkbox next to each module; it contains a string like:
modules[Core][aggregator][enable]

In that example, aggregator being the machine name of the module.
If you don't want to go low-tech you'll need to implement hook_form_alter(), loop through the module data in the form and add the machine name somewhere.
For example, the following code will add the machine name in brackets after the title of each module:
function MYMODULE_form_system_modules_alter(&$form, &$form_state, $form_id) {
  foreach (element_children($form['modules']) as $group_key) {
    foreach (element_children($form['modules'][$group_key]) as $module_key) {
      $machine_name = " ($module_key)";
      $form['modules'][$group_key][$module_key]['name']['#markup'] = $form['modules'][$group_key][$module_key]['name']['#markup'] . $machine_name;
    }
  }
}

Screenshot of the results on a blank Drupal installation:
Comment: I´ll try to implement hook_form_alter().
Comment: I've just updated the answer with an example, turns out it's fairly easy :)
Comment: i get this error (one for each module) `Notice: Undefined index: name en utilities_form_system_modules_alter() (line 14 of...)`. Line 14 is: `$form['modules'][$group_key][$module_key]['name']['#markup'] = $form['modules'][$group_key][$module_key]['name']['#markup'] . $machine_name;`
Comment: The code is for Drupal 7...are you using Drupal 6 by any chance?
Comment: no, I'm using D7. Do you want me to dpm some values and paste them here?
Comment: I've just pasted the code into a blank Drupal site and it works perfectly...you must have something else interfering with that page. I'd try disabling contrib modules until you find the culprit, it's impossible to say what the problem will be from here
Comment: ok, I'll do that.
Answer: Try the development snapshot of the Module Filter module. It overrides the entire modules page and displays the machine name below the human name.

The modules list page can become quite big when dealing with a fairly large site or even just a dev site meant for testing new and various modules being considered. What this module aims to accomplish is the ability to quickly find the module you are looking for without having to rely on the browsers search feature which more times than not shows you the module name in the 'Required by' or 'Depends on' sections of the various modules or even some other location on the page like a menu item.
Comment: Module Filter module is great stuff (shame on me, I didn't know about it). But I cannot see any machine names. Is there something that needs to be configured?
Comment: The code isn't present in 1.6. You have to use the 2.x-dev version.
Answer: FYI you can get the same info with drush pm-list, you can even filter extensions by status or other criteria.
Also, to see the extension's description and dependencies use for example drush pm-info views_ui.


Instabilidade ao carregar JQuery dinamicamente em window.load() no Firefox

Question: Tenho uma funcionalidade onde dependendo da situação devo declarar a biblioteca do JQuery e alguns outros scripts, como por exemplo o script Alert.js que uma classe de mesmo nome. Tenho testado esta funcionalidade no Google Chrome e no Firefox, no primeiro os scripts sempre são carregados corretamente antes da execução da função/classe Alert(), porém no Firefox os scripts são carregados de maneira instável, ou seja, quando a função Alert é executada, muitas vezes o jQuery ainda não está disponível, sendo necessário recarregar a página para que na segunda vez ele funcione corretamente.
Para esclarecer melhor, o erro retornado pelo Firefox no console são os seguintes:
Primeiro:
ReferenceError: jQuery is not defined

Segundo:
TypeError: $(...).dialog is not a function
$("#dialog-message").dialog(arrayPropriedades);

O código do segundo erro está dentro da classe Alert, sendo que $.dialog() é uma função nativa do JQuery UI que não foi carregado devido ao primeiro erro que informava que o jQuery ainda não tinha sido carregado.
Veja abaixo o código desta funcionalidade:
if (typeof (Alert) === 'undefined') {

    var scripts = [
        DIR_JS_LIB + 'lib/jquery/jquery.min.js',
        DIR_JS_LIB + 'lib/jquery/jquery-ui/jquery-ui.min.js',
        DIR_JS_LIB + 'scripts/componentes/dialog/AcaoJanela.js',
        DIR_JS_LIB + 'scripts/componentes/dialog/Botao.js',
        DIR_JS_LIB + 'scripts/componentes/dialog/Dialog.js',
        DIR_JS_LIB + 'scripts/componentes/dialog/Alert.js'
    ];

    for (var i = 0; i < scripts.length; i++) {
        include(scripts[i]);
    }

}
window.onload = function () {

    Alert(window.mensagem, window.titulo, window.botoes);
}

function include(file_path) {
    var j = document.createElement("script");
    j.src = file_path;
    document.getElementsByTagName('head')[0].appendChild(j);
}

Código PHP que executa o script acima (cujo nome é definido pela variável $this->path_load_script):
$str .= '<link rel="stylesheet" type="text/css" href="/app/assets/css/styles.css"/>'
                . '<link rel="stylesheet" type="text/css" href="' . DIR_JS_LIB . 'lib/jquery/jquery-ui/jquery-ui.custom.min.css" />'
                . "\n";

Comment: Se precisa sempre do jQuery sugiro que o carregue na head com link próprio. Na head o carregamento é sincrono, e evita estes erros. Quando diz "no template o jQuery já é carregado instantâneamente" quer dizer que há outro jQuery ou refere-se ao que está no seu código na pergunta?
Comment: Tente colocar as funções dentro do `ready` do jQuery.
Comment: Não teria como, pois o erro ocorre quando o JQuery ainda não foi carregado, dessa forma a função ready ainda não está disponível.
Comment: Hmm, entendi. Pra verificar se o jQuery foi carregado apenas faça `if (window.jQuery) { / jQuery carregado }`
Comment: @mayconfsbrito desses ficheiros precisa sempre do jQuery? ou tem casos em que não quer carregar o jQuery?
Comment: @Sergio este script acima precisa sempre do JQuery sim. A sua função basicamente é exatamente essa, para exibir Dialogs (Alert) em páginas que estão fora do template da aplicação, pois no template o jQuery já é carregado instantâneamente.
Comment: @Sergio na verdade existem duas situações na minha aplicação. Páginas que são exibidas dentro de um template com cabeçalho, figura e menu, sendo que neste caso os scripts são carregados estaticamente dentro do  no template. E a outra situação são páginas que são carregadas fora do template, somente para exibição de Dialogs, de forma que tenho de declarar os scripts dinamicamente conforme o código acima.
Comment: Dica: você pode ir editando sua pergunta e incluir essas informações que está passando através dos comentários. Assim fica melhor para as outras pessoas entender o problema. ;)
Comment: @mayconfsbrito e esses diálogos são iFrames? ou conteúdo que faz parte do HTML da página?
Comment: @Earendul obrigado pela dica, vou atualizar a pergunta em breve.
Comment: @Earendul boa sugestão. E eu vou apagando as perguntas/comentário assim que a resposta estiver na pergunta.
Comment: @Sergio são Dialogs do JQuery-UI, inclusive percebi um outro erro dizendo que a função $.dialog() não existe, sendo esta nativa do JQuery UI. Vou inserir esta informação na pergunta.
Comment: @mayconfsbrito se esses diálogos são `.dialog()` então junte o jQuery e o UI na head (assim carregam sincronos), e o resto como tem na pergunta e problema resolvido. Certo?
Comment: @Sergio seria possível não adicionar o jQuery e jQueryUI diretamente na head de forma estática? Pois este código é gerado pela minha aplicação PHP que imprime o dialog tanto fora do template quanto dentro.
Comment: @mayconfsbrito junte o código PHP em questão. Mas se em qualquer dos casos precisa do jQuery então o melhor é juntar no head. Senão vai precisar de `setInterval` para saber quando o script carregou e poder carregar os proximos, tipo em cascata, e fica menos elegante (se não estritamente necessário).
Comment: @Sergio editei e coloquei o código PHP lá, o problema é que esta app é um framewok bem grandinho e uma coisa vai puxando a outra. Mas acredito que o problema concentra-se somente ali no javascript e jquery.
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/18394/discussion-between-mayconfsbrito-and-sergio).
Answer: Em paralelo a este tópico eu abri outro post no Stack Overflow internacional e obtive a resposta a partir da solução sugerida pelo usuário Master Slave. Clique aqui para ver o tópico com a solução proposta.
Para ilustrar melhor postarei abaixo o código que solucionou o meu problema:
window.onload = function () {

    var scripts = [
        DIR_JS_LIB + 'lib/jquery/jquery.min.js',
        DIR_JS_LIB + 'lib/jquery/jquery-ui/jquery-ui.min.js',
        DIR_JS_LIB + 'scripts/componentes/dialog/AcaoJanela.js',
        DIR_JS_LIB + 'scripts/componentes/dialog/Botao.js',
        DIR_JS_LIB + 'scripts/componentes/dialog/Dialog.js',
        DIR_JS_LIB + 'scripts/componentes/dialog/Alert.js'
    ];

    include(scripts[0], function () {
        include(scripts[1], function () {
            include(scripts[2], function () {
                include(scripts[3], function () {
                    include(scripts[4], function () {
                        include(scripts[5], function () {
                            Alert(window.mensagem, window.titulo, window.botoes);
                        });
                    });
                });
            });
        });
    });

}

function include(filename, callback) {
    var fileref = document.createElement('script');
    fileref.setAttribute("type", "text/javascript");
    fileref.setAttribute("src", filename);
    if (fileref.readyState) {
        fileref.onreadystatechange = function () { /*IE*/
            if (fileref.readyState == "loaded" || fileref.readyState == "complete") {
                fileref.onreadystatechange = null;
                callback();
            }
        }
    } else {
        fileref.onload = function () {  /*Other browsers*/
            callback();
        }
    }

    if (typeof fileref != "undefined")
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(fileref)
}

Obrigado a todos pela ajuda.


Conditionally delete individuals from longtidunal data

Question: I have a longitudinal data set where I want to drop individuals (id) if they do no fulfill the criterion indicated by criteria == 1 at any time points. To put it in context we could say that criteria denotes if the individual was living in the region of interest at any time during.
Using some toy-data that have a similar structure as mine:
id <- c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5)
time <-  c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3)
event <- c(0,1,0,1,0,0,0,0,0,0,1,0,1,0,1)
criteria <- c(1,0,0,0,0,0, 0, 0, 0, 1, 1, 1,0,0,1)

df <- data.frame(cbind(id,time,event, criteria))

> df
   id time event criteria
1   1    1     0        1
2   1    2     1        0
3   1    3     0        0
4   2    1     1        0
5   2    2     0        0
6   2    3     0        0
7   3    1     0        0
8   3    2     0        0
9   3    3     0        0
10  4    1     0        1
11  4    2     1        1
12  4    3     0        1
13  5    1     1        0
14  5    2     0        0
15  5    3     1        1

So by removing any id that have criteria == 0 at all time points (time) would lead to an end result looking like this:
   id time event criteria
1   1    1     0        1
2   1    2     1        0
3   1    3     0        0
4   4    1     0        1
5   4    2     1        1
6   4    3     0        1
7   5    1     1        0
8   5    2     0        0
9   5    3     1        1

I've been trying to achieve this by using dplyr::group_by(id) and then filter on the criterion but that does not achieve the result I want to. I'd prefer a tidyverse solution! :D
Thanks!
Answer: df %>%
  group_by(id) %>%
  # looking for the opposite (i.e. !) of criteria == 1 at least 1 time
  mutate(is_good = !any(criteria == 1)) %>%
  filter(is_good)

Comment: Worked with one modification.  Remove the acclamation mark. Thanks!
Answer: If you'd be willing to look into data.table's, which I recommend, it would be as simple as this:

library(data.table)
setDT(df) # make it a data.table

df[ , .SD[ !all(criteria==0) ], by=id ]

See this page for a general introduction and an explanation of the .SD idiom:
https://cran.r-project.org/web/packages/data.table/vignettes/datatable-intro.html


Who will put on last of the grid if many drivers get back grid penalty in F1?

Question: At the 2022 Belgian Grand Prix, six drivers are due to start at the back of the grid due to power unit penalties. So, these drivers will occupy places P15 to P20 on the grid.
How is it determined which driver will be in P15 and which driver will be in P20 if all six drivers got the penalty simultaneously?
Answer: They will be ordered by their qualifying position
From the Sporting Regulations, for race weekends without a Sprint Race:

42.3
(d) Once the grid has been established in accordance with Article 42a), 42b) and 42c), grid penalties for any driver required to start the race from the back of the grid after incurring a penalty under Article 28.3) will be applied.

i) If more than one (1) driver is required to start the race from the back of the grid they will be arranged in qualifying order.

Any driver who incurs a penalty under in accordance with Article 28.3) or Article 29) will take precedence over any driver whose qualifying practice times have been deleted for any reason.

And, in the case that multiple drivers do not set a qualifying time at all:

If more than one (1) driver falls into a single category in Article 42.3b) or Article 42.3e) above they will be arranged on the grid in the order they were classified in the previous period of the qualifying practice session or, in the case of Q1, the order they were classified in P3.

For weekends with a Sprint Race, the rules are mostly the same, in that the drivers will be placed in relation to their finishing place in the Sprint Race. However, if they do not participate in the Sprint Race, then it goes back to the Sprint Qualifying placing.

41.4
[...]
If more than one driver falls into a single category in b) or e) above they will be arranged on the grid in the order they were classified in the sprint session or, in the order they were classified in the qualifying practice session.

And, although not expressly stated, I imagine that if the drivers did not participate in Sprint qualifying, then it would go by the P1 standings, similar to the non-sprint race weekends.


Undefined symbol after linking C driver dynamically

Question: I am using the following make file to build an application that links against libbson and libmongoc:
CURRENT_DIR=$(shell pwd)

INC=-I/usr/local/include/libbson-1.0
INC+=-I/usr/local/include/libbson-1.0/bson
INC+=-I/usr/local/include/libmongoc-1.0/mongoc
INC+=-I$(CURRENT_DIR)/thpool
INC+=-I$(CURRENT_DIR)/cJSON

LIBS=/usr/local/lib/

all     :       request.o db_manager.o main.o
    +$(MAKE) -C cJSON all
    +$(MAKE) -C thpool all
    mkdir build
    mv cJSON/*.o build/
    mv thpool/*.o build/
    mv request.o build/
    mv db_manager.o build/
    mv main.o build/
    cp -R libs build/ #make copy of local static libs
    cd build && \
    cc $(INC) -w -pthread main.o request.o db_manager.o cJSON.o cJSON_Utils.o \
    thpool.o $(LIBS)libbson-1.0.so $(LIBS)libmongoc-1.0.so \
    -o ghost-chat

request.o       :       request.c
    cc -w $(INC) -c request.c

db_manager.o    :       db_manager.c
    cc -w $(INC) -c db_manager.c

main.o  :       main.c
    cc -w $(INC) -c main.c

clean   :
    rm -rf build

The application builds correctly, but during execution, when I make a call to a libmongoc function, it returns the following error:
./build/ghost-chat: symbol lookup error: ./build/ghost-chat: undefined symbol: mongoc_collection_insert_one

Am I correctly linking the libmongoc-1.0.so library? I have built the libmongoc driver from the latest tarball - hence the installation directory of /usr/local/*. I have tested the application successfully - using Xcode on macOS, using it's own build system, but I have written this make file to allow building on our *Nix server.
Any advice would be greatly appreciated.
Answer:
I have built the libmongoc driver from the latest tarball - hence the installation directory of /usr/local/*

Is there also libmongoc-1.0.so in a standard system directory (/usr/lib, or whatever the default is for your system) ?
If so, you are probably loading the wrong libmongoc-1.0.so at runtime (and that system version lacks the mongoc_collection_insert_one symbol).
Running ldd ./build/ghost-chat should show which libmongoc the runtime loader finds, and running nm -D libmongoc-1.0.so | grep mongoc_collection_insert_one on that version should confirm that the symbol is not defined.
What you want to do is link your binary with -Wl,-rpath=$(LIBS), so that /usr/local/lib is searched before /usr/lib.
Answer: You are using "libmongoc" version 1.0, so you should use the same examples for this version. Please, get the related example form this like:
http://mongoc.org/libmongoc/1.0.0/index.html!
for example to insert a record use this:
#include <bson.h>
#include <mongoc.h>
#include <stdio.h>

int
main (int   argc,
      char *argv[])
{
    mongoc_client_t *client;
    mongoc_collection_t *collection;
    mongoc_cursor_t *cursor;
    bson_error_t error;
    bson_oid_t oid;
    bson_t *doc;

    mongoc_init ();

    client = mongoc_client_new ("mongodb://localhost:27017/");
    collection = mongoc_client_get_collection (client, "test", "test");

    doc = bson_new ();
    bson_oid_init (&oid, NULL);
    BSON_APPEND_OID (doc, "_id", &oid);
    BSON_APPEND_UTF8 (doc, "hello", "world");

    if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
        printf ("%s\n", error.message);
    }

    bson_destroy (doc);
    mongoc_collection_destroy (collection);
    mongoc_client_destroy (client);

    return 0;
}


Tmux scroll mode: vim keybindings?

Question: So if I am in Tmux and a bunch of output came to the terminal, I can scroll through it by pressing:
ctrl-b [

Now, I have to pick my hands up and go to the arrow keys to scroll up.
How do I map the vim keys in scroll mode?
Answer: Update in 2020: I don't think anyone should be using any version of tmux below 2, so the concise configs for modern tmux is just
set-window-option -g mode-keys vi
bind-key -T copy-mode-vi v send -X begin-selection
bind-key -T copy-mode-vi V send -X select-line
bind-key -T copy-mode-vi y send -X copy-pipe-and-cancel 'xclip -in -selection clipboard'

Previous answer
Unsure which tmux you have. This works for both 1.8 and 2.6, which are the two I'm forced to use.
run-shell "tmux setenv -g TMUX_VERSION $(tmux -V | cut -c 6-)"
if-shell -b '[ "$(echo "$TMUX_VERSION < 2.4" | bc)" = 1 ]' \
  "setw -g mode-keys vi; \
  bind-key Escape copy-mode; \
  bind-key -t vi-copy v begin-selection; \
  bind-key -t vi-copy V select-line; \
  bind-key -t vi-copy y copy-pipe 'xclip -in -selection clipboard'"

if-shell -b '[ "$(echo "$TMUX_VERSION >= 2.4" | bc)" = 1 ]' \
  "set-window-option -g mode-keys vi; \
  bind-key -T copy-mode-vi v send -X begin-selection; \
  bind-key -T copy-mode-vi V send -X select-line; \
  bind-key -T copy-mode-vi y send -X copy-pipe-and-cancel 'xclip -in -selection clipboard'"

The relevant section here for hjkl is just setw -g mode-keys vi for 1.8 and set-window-option -g mode-keys vi for 2.6 (these might even be aliases and work in both versions, not sure). That being said, the v and V mappings with xclip are definitely useful.
Comment: +1. Out of dozens of tmux SO questions I read, this is the first one that differentiates well between versions when it comes to scrolling with vim keys. Exactly the information I needed (to solve a different problem though). Thanks a lot!
Comment: related answer: [Use system clipboard in vi-copy mode in tmux](https://unix.stackexchange.com/questions/131011/use-system-clipboard-in-vi-copy-mode-in-tmux#131187)
Comment: To use this answer first install `xclip` package. for Debian based `apt install xclip`
Comment: We're still tied down to tmux 1.8 for some reason, so the different config is useful.
Comment: tmux config is located in ~/.tmux.conf if you want to run these lines when the server starts
Answer: To supplement the accepted answer, I found the following .tmux.conf lines accomplished most of what I needed:
set-window-option -g mode-keys vi
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R

Tmux scroll mode: vim keybindings?


jQuery unique, diferença no Chrome e Firefox?

Question: Estou tendo um comportamento inesperado com o uniquedo jQuery.
O seguinte comando:
 var x = [1,2,1,2];
 var y = $.unique(x);
 document.write(y);

No Chrome tem como resultado 1,2 (o que está correto), mas no Firefox aparece 1,2,1,2.
Isto é um bug, ou era para ser assim mesmo?
Segue exemplo no jsfiddle, abra primeiro no Chrome (funciona corretamente) e depois no Firefox (não funciona).
OBS: jQuery 2.1.0; Firefox 24.5.0; Google Chrome 34.0.1847.131 m.
Comment: Encontrei na página de bugs de jQuery o seguinte: `$.unique() is only designed to work on DOM nodes, not on arrays of strings.` http://bugs.jquery.com/ticket/7036
Comment: @Sergio olha só, o bug tá fechado como inválido > "closed bug: invalid"
Comment: @guisantogui O bug é inválido justamente porque a função está sendo usada de forma diferente do que foi projetada.
Comment: Uma sugestão: para obter elementos únicos de um Array, converta-o para um objeto. Todo objeto em Javascript é praticamente um dicionário, assim você pode garantir a unicidade ;) Exemplo com todos os valores como `true`: `var z = {"1": true, "2": true};`
Answer: O .unique()do jQuery não foi desenhado para numeros ou strings. Na documentação do jQuery pode ler-se:

Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.

na nossa língua sería:

Ordena uma array de elementos DOM, removendo os duplicados. Note que isto só funciona em elementos DOM e não numeros ou strings.

Aqui fica código em javascript para fazer o que precisa: http://jsfiddle.net/4SBVQ/
var arrayUnique = function(a) {
    return a.reduce(function(p, c) {
        if (p.indexOf(c) < 0) p.push(c);
        return p;
    }, []);
};

Fonte: https://stackoverflow.com/a/4833835/2256325


Testing Trend Stationarity against Stationarity

Question: I am trying to find a test where null hypothesis is that the series is trend stationary. I can assume that the trend is linear if that is going to help. So the series for null hypothesis is given by:
$y_t = a + bt + x_t$
Where $x_t$ is a stationary time series which we take it to have zero mean without loss of generality.
Comment: Can you please clarify on what trend stationarity is?
Comment: @Galen https://en.m.wikipedia.org/wiki/Trend-stationary_process#:~:text=In%20the%20statistical%20analysis%20of,not%20have%20to%20be%20linear.
Comment: Thank you! I had been using this concept for quite a while but didn't have a term for it.
Answer: The Kwiatkowski-Phillips-Schmidt-Shin test is a unit root test that actually has the unit root as the alternative (so not $I(0)$ or $I(1)$), and trend-stationarity as the null.
Can you also assume the absence of seasonality? In my experience, series that contain multiple periodicities can mess with unit root tests. The (augumented) Dickey-Fuller test can get pretty confused. e.g. on completely unprocessed temperature data over a year, a very nonstationary process but with complicated periodicities, it can fail to reject the null of stationarity.
Edit: Hmm, if the only 2 cases are stationarity or linear trend-stationarity with the latter as the null, then that's the same as equivalence testing $b \neq 0$ on the regression coefficient of a simple linear regression of the series on time.
Because in this case the errors are stationary and thus can be autocorrelated, you'll have to use HAC robust standard errors though, such as Newey-West. Typical equivalence testing procedures like TOST do require you to specify a range around $b = 0$ that is still consistent with the alternative. (i.e. an effect size that is small enough to be unimportant).
Comment: Thanks for the answer. I want to test whether $b\neq 0$ or not. I am very confident that there is no unit root in the data I am dealing with so I believe KPSS is not useful. Am I missing something?
Comment: @Bronsteinx I didn't realize the presence of a unit root was already ruled out, I edited my answer.
Comment: Thanks again, I read about Newey-West. It seems that this basically solve problem when you use autoregressive models but when you have a moving average part you cant use it. Am I missing something?