Correlation as a time series

Question: I have been studying a few simple statistical models for (univariate) time series. From my understanding,

ARIMA and its siblings are used to model the mean of a time series. Rather than a static measure like mean(), the result is a series estimating the mean.
ARCH and its brothers are used to model the volatility of a time series. Rather than the usual sd(), the result is a series estimating the variance.

Question
What would be a credible model for the correlation of two time series?
Notes
While mean models explore the idea of regressing lagged values of the time series, volatility models (eg. ARCH model) explore the idea of regressing lagged residuals where residuals are the difference of a mean model to its original time series.
In its general sense and for a variety of reasons, ARIMA and ARCH are superior models than rolling windows with mean() (popularly known as moving averages outside statistics world) and sd().
However, there is no such a thing for the correlation of two time series X and Y to my knowledge.
The closest thing would be rolling a sad, straight window with cor(), Pearson's coefficient function in R, and work around the resulting series.
A poor solution
Trying to replicate Pearson's correlation model,
p_(X,Y) = cov(X,Y) / (sd(X) sd(Y))
        = E((X-mean(X))(Y-mean(Y))) / (sd(X) sd(Y)),

to the time series world, I had the above without the intended success.
library('forecast')
library('fGarch')

X <- 1:200 + rnorm(200, sd=10)
Y <- 50 + (1:200)/100 + rnorm(200, sd=5)

plot(1:200, X, t='l', main="What would be a resulting ts correlation of X and Y?")
lines(1:200, Y, t='l', col='blue')

# Mimic Pearson correlation, cov(X,Y)/(sd(X)*sd(Y)).
Xm <- as.vector(X) - as.vector(fitted(Arima(X, order=c(2,0,1))))
Ym <- as.vector(Y) - as.vector(fitted(Arima(Y, order=c(2,0,1))))

Xv <- garchFit(formula=~arma(2,1) + garch(2,1), data=X)@sigma.t
Yv <- garchFit(formula=~arma(2,1) + garch(2,1), data=Y)@sigma.t

correlation <- Xm * Ym / (Xv * Yv)    # this can be forecast

plot(correlation, t='l', col='blue', ylim=c(-2, 2), main='Correlation models')
abline(h=c(-1, 1))
abline(h=cor(X, Y), col='red', lwd=5)

# Correlation rolling window of size 10.
df <- data.frame(X, Y)
crw <- rep(NA, 10)
for (i in 11:nrow(df))
  crw <- c(crw, cor(df[(i-10):i, 1], df[(i-10):i, 2]))

lines(crw, col='darkgreen', lwd=5)

legend('topright',
  c('pearson mimic', 'static cor()', 'rolling cor() like moving averages'),
  col=c('blue', 'red', 'darkgreen'), lwd=c(1, 5, 5))

Comment: Check out multivariate volatility models with focus on conditional correlations. E.g. Engle's dynamic conditional correlation (DCC) model [here](http://www.tandfonline.com/doi/abs/10.1198/073500102288618487#.VhYat_mqpBc). Good general overview of multivariate volatility models are [this](http://onlinelibrary.wiley.com/doi/10.1002/jae.842/pdf) and [this](http://link.springer.com/chapter/10.1007/978-3-540-71297-8_9). Note that ARCH-type of conditional variances is *not* a prerequisite for considering conditional correlations.
Comment: Your `correlation` looks weird when plotted because it actually does not match the definition of Pearson correlation that you refer to above. In `correlation <- Xm * Ym / (Xv * Yv)`, the part `Xm * Ym` should be replaced by `(X-Xm) * (Y-Ym)`. Also, you ignore the presence of the linear trends in `X` and `Y` when fitting the ARIMA models; that clearly yields a poor fit.
Comment: Have you looked at the cross correlation function ccf?  That is a good exploratory approach.  I think the corresponding model might be a VAR model as implemented in R package vars.
Answer: In the context of multivariate time series, there is a mean vector and a variance-covariance matrix. The conditional mean vector and/or the conditional variance-covariance matrix vary over time. Then it is natural to be interested in the conditional correlation rather than unconditional one.
Given a model for the conditional mean vector and the conditional variance-covariance matrix, a particular conditional correlation between variables $x_i$ (in your case X) and $x_j$ (in your case Y) at time $t$ can be immediately retrieved as the ratio of the conditional covariance over the product of the conditional standard deviations: $\rho_{i,j,t}=\frac{ \text{Cov}(x_{i,t},x_{j,t}) }{ \text{sd}(x_{i,t}) \cdot \text{sd}(x_{j,t}) }$.
While the models for the conditional mean of a multivariate time series (e.g. VAR, VARMA, VECM, but also other model classes) might not need an introduction, the models for the conditional variance are perhaps less broadly used and less well known. Therefore you may benefit from a couple of reviews of multivariate GARCH models here and here. For a particular example, you could check out Engle's dynamic conditional correlation (DCC) model.

Your correlation looks weird when plotted because it actually does not match the definition of Pearson correlation that you refer to above. In correlation <- Xm * Ym / (Xv * Yv), the part Xm * Ym should be replaced by (X-Xm) * (Y-Ym). Also, you ignore the presence of the linear trends in X and Y when fitting the ARIMA models; that clearly yields a poor fit.

Correlation as a time series


Use datefield year as condition in Entity Query

Question: I'm performing an entity query that searches for nodes of my custom content type called 'news'.
The content type has a date field called 'field_date'. I want to be able to perform the query in a way that only produces the 'news' nodes that have a 'field_date' that fits within a specified year. Here is an attempt I made below.
<code>$year = 2015;
$query = \Drupal::entityQuery('node')
  ->sort('field_date', 'DESC')
  ->condition('type', 'news')
  ->condition('field_date', [date('Y','field_date'), $year], '=')
  ->range(0, 10);
</code>
In the code above I'm attempting to only grab the year from the 'field_date' datefield and compare that to $year, 2015 in this case. However I receive SQL errors like:

Invalid parameter number: number of bound variables does not match
  number of tokens

I'm guessing part of it is date('Y','field_date') doesn't know what 'field_date' is but I'm not sure how to go about it.
How do I make a year comparison on a datefield in a entityquery condition?
Answer: Assuming the data in the database looks like this: "2015-10-12T21:30:00", you can use a like query
<code>->condition('field_date', $year . '%', 'like')
</code>
Your code revised with the change:
<code>$year = 2015;
$query = \Drupal::entityQuery('node')
  ->sort('field_date', 'DESC')
  ->condition('type', 'news')
  ->condition('field_date', $year . '%', 'like')
  ->range(0, 10);
</code>
Comment: This is pretty inefficient, you're treating dates as text and running a full table scan. Dates are stored as either `DATETIME_DATETIME_STORAGE_FORMAT` or `DATETIME_DATE_STORAGE_FORMAT` (see datetime.module) and both of those have been designed so that they sort numerically, and the column is indexed, so you can build a `new DateTime('2015-0-0...')` - i.e. first second of the year - and just compare `$mydt->format('DATETIME_DATETIME_STORAGE_FORMAT')` to the column with a more than query. Add a "less than last second of 2015" condition and you've got "in 2015".
Comment: Awesome worked. But I had to change fieldCondition to condition.
Comment: oops, that's correct, updated.


Dart find string value in a list using contains

Question: I have a list of numbers like below -
List contacts = [14169877890, 17781231234, 14161231234];

Now I want to find if one of the above list element would contain the below string value -
String value = '4169877890';

I have used list.any to do the search, but the below print statement inside the if condition is not printing anything.
if (contacts.any((e) => e.contains(value))) {
     print(contacts[0]);
}

I am expecting it to print out the first element of the contacts list as it partially contains the string value.
What is it I am doing wrong here?
Answer: Not sure if contacts is an integer and value is a string on purpose or mistake, but this works in dart pad if you convert it to string:
if (contacts.any((e) => e.toString().contains(value))) {
     print(contacts[0]);
}

DartPad Link.
Comment: Finally found the issue, Thanks to all who helped figure it out.
Comment: You probably intend `e.toString() == value`.  If you use `contains`, then `'123'` would be "found" in `[1234]`.
Comment: I thought so, but `Error: The method 'contains' isn't defined for the class 'int'.`
Comment: Huh? I'm telling you to *not* use `contains`.
Comment: So I made sure every single value in that list and list itself is a string. Also made sure the value I am searching for inside the list is also a string.
Answer: contacts isn't a List<String>, so your any search can't be true, you need turn element of contracts to string to able to use contains.
void main() {
  var contacts = [14169877890, 17781231234, 14161231234];
  print(contacts.runtimeType);
  var value = '4169877890';
  print(value.runtimeType);
  var haveAnyValid = contacts.any((element) {
    return "$element".contains(value);
  });
  print(haveAnyValid);

  // result

  // JSArray<int>
  // String
  // true
}

Comment: I checked the runtimetype, it says contacts is a dynamic list and those values are pulled in from an api call.
Comment: If you make sure it is a **List of String** using type cast, or just use `toString()` or `"$value"` to turn them to `String` before use `contacts`
Comment: Yes I made it a list of strings, now I see the runtimetype as String. Still I haven't been able to make it work.


Como definir o valor de uma variavel do css pelo java Script

Question: Quero definir a css progress via java script, fazendo com que ela se altere com um valor que eu colocar no input do Html. deem uma olhada:
HTML:
    <link rel="stylesheet" type="text/css" href="HPCSS.css">

<input id="vida" onchange="update()">

CSS:
.teste{
 --progess:2000;
 height: 50px;
 padding: 5px;
 background-color: #ccc;
 display: flex
}
.teste::before{
content: "";
width: calc(var(--progess)*1%);
background-color: red
}

JavaScript:
function update(){
var vida= document.getElementById("vida")
var value= vida.value
}

Já consegui passaro valor do input pro JS, agora quero saber como definir esse valor como valor da variável progress no CSS
Quem puder me ajudar eu agradeceria
Comment: use a propriedade style: `document.querySelector(".teste").style["progress"] = valor;`
Comment: Não deu certo não
Answer: Você pode usar o método .setProperty(), que altera uma propriedade dentro de um bloco de estilo CSS:

function update(){
   var vida= document.getElementById("vida")
   var value= vida.value
   document.querySelector(".teste").style.setProperty('--progess', value);
}
.teste{
 --progess:5;
 height: 50px;
 padding: 5px;
 background-color: #ccc;
 display: flex
}
.teste::before{
content: "";
width: calc(var(--progess)*1%);
background-color: red
}

<input id="vida" onchange="update()">
Comment: DEU CERTO CARA OBRIGADO!!!


Verificar um padrão de caracteres para login

Question: Ao usar a classe Regex do C#
Eu queria que a string nomeLogin

não permitir que comece com números ou caracteres especiais.
apenas permitir "_" ou "-" ou "." como caracteres especiais.
mínimo de 2 caracteres sendo o primeiro letra e minúsculo.
máximo de 20 caracteres.
Answer: Eu acho que isto dá certo, não testei e não garanto que está pegando todas situações:
var regex = new Regex("^[a-zA-Z][-a-zA-Z0-9_\.]*$");

Coloquei no GitHub para referência futura.
Também não sei se você especificou corretamente o que precisava. A especificação já está esquisita dizendo o que não pode, o mais correto é dizer o que pode.
Answer: bom eu consegui resolver, então pra quem precisar ta aí a resposta testada:
var regex = new regex("^[a-z][A-Za-z0-9_.-]{1,19}$");


How can the alpha channel be -1?

Question: I am wondering how the alpha channel of a single pixel can be -1? I am going through each pixel of a PNG image (loaded in a buffered image, ARGB type). Many of the alpha values are -1 (the others are larger than zero) - how is that possible? Shouldn't the value be between 0 and 255? Code follows below. Thanks for any hint!
<code>// imagine some great loop for x and y before this code
int a = (scaledImage.getRGB(x, y) & 0xff000000) >> 24; // kill all bits except for the first 8, shift 24 to the right to get them
System.out.println("" + a);
</code>
Answer: You are running into a sign extension problem. Use the unsigned shift operator <code>>>></code> instead.
Comment: Thank you for also delivering the solution to the problem!
Answer: If you treat it as unsigned int, -1 = 0xFF = 255. It's just another way of interpreting a 255 value for the alpha channel.
Comment: Thank you for the explanation, Adam! Unfortunately I can't see if you or erickson was faster, will accept ericksons answer as it also provides a solution to this problem, but yours is also very helpful!

How can the alpha channel be -1?


Overhead vs. Speed of Code (java.io.File array vs. java.lang.String array)

Question: just trying to sort out a small delimma I'm having here.
Currently, I'm working on an application that involves gathering a list of files into memory, to be deleted.  Now, at this point, I thought that a java.io.File array would perhaps take up too much memory, since the list of Files in this context could be in the hundreds of possible entries.
Rather than eat excessive amounts of memory up with a list of File objects, I figured that gathering a list of filenames and storing them as a java.lang.String would be cheaper to memory.  Now, here's my problem: With the goal in mind that these files are to be deleted, which of these would be cheaper:

Storing an array of File objects rather than String objects, and calling .delete(); on each one in a loop (too much memory used).
Storing an array of String objects with the filenames, but for each iteration of the loop, create a new File object using the list of filenames, and call .delete(); on that file (which means each time the loop iterates, a new File object is created and destroyed--possibly too much processor power being used).

I want to make the program as fast as possible, so either approach has its merits, and I just want to see which of these has the least overhead.  Thanks in advance!
Comment: Have you confirmed that the `File` array takes up too much memory? Java's `File` objects have more than zero size, of course, but they're only references to filesystem locations. They doesn't implicitly transfer the contents of files into your program.
Comment: Have you tried both? Which was faster? This is a pretty tough question to answer in theory.
Comment: premature optimization is the root of all evil
Comment: @Kevin: With proper emphasis on *premature*; on weaker Droids, this may be actually relevant (not sure if this actually *is* the case, the OP didn't share enough context there).
Comment: Going with the `File` array, unless post-deployment benchmarking shows that there's an issue with that approach.  Thanks.
Answer: The java.io.File represents the filename information/metadata about an entry in the filesystem, it does not contain the contents of the file.
In other words, code like new File("somelarge.txt") does not load the somelarge.txt file into memory.
The only real data that each File object contains is a String path to the File (along with a transient int prefixLength) - consider the File class merely a wrapper around the String path that knows how to invoke all of the filesystem operations.
The best choice here, barring some other requirements, is the code that is the easiest to read and conveys your intent the best.
Comment: +1: A `File` contains a `String` and an `int`, so memory footprint should not be an issue. Go for readability.
Answer: I don't want to be rude, but let me start by invoking the "Avoid Premature Optimizations at all costs" mantra. Is your code performance sensitive? Do you have memory usage constraints? Neither hundreds of File objects or hundreds of File object creations in a loop sounds that bad. Still, if you really feel like optimizing, go with a Profiler and run some benchmarks using both strategies. I would personally recommend Netbeans Profiler.
Answer: A File is largely a wrapper for a String and consumes up to 32 bytes more than the String itself.  If you have 1000 of these in a server where memory costs about $70/GB, the extra memory it consumes is worth about 0.22 cents.  This is about the same as 1 second of your time if you are on minimum wage.
Unless you have a memory limited device, it is likely you don't need to worry about anything which consumes less than 1 MB.
Answer:
Now, at this point, I thought that a
  java.io.File array would perhaps take
  up too much memory, since the list of
  Files in this context could be in the
  hundreds of possible entries.

Unless you are working with a seriously resource-starved system, you do not have the problem that you think you have.
Remember that a Java File object is only "an abstract representation of file and directory pathnames."  As such, it represents a fixed memory cost for any file, no matter how large.  If you are dealing with only hundreds of Files, you are almost certainly not approaching any sort of limit on heap space.
If you create a solution and find that you are facing memory limitations using profiling and monitoring, this implementation is one of the last places that you should look.  It's simply not that much memory.
So, in short, you should write the code that you understand the best and will be able to maintain in the future.  Simple code is your friend.
Answer: Sounds like premature optimization to me unless

You are working with a resource-constrain mobile device, or
The number of elements (file paths) in the array might be very large.

Having said that, an array of String objects beat an array of File objects in terms of memory and speed. And there are several reasons for this:

A File object has a number of private attributes, including but not limited to

a private String field attribute
a transient prefix length field for filesystem-specific prefixes

A File object instantiation relies on a static reference to an concrete implementation of java.io.FileSystem, to which the File constructor(s) make calls to it

At a minimum, construction of a File object requires a call to FileSystem.normalize() and FileSystem.prefixLength() (in addition to instantiating its own private references to the path and prefix length.

So, the cost of creating an array of n File instances equals
n * (expense_of_constructor + avg_construction_of_individual_path_strings_off_filesystem)

expense_of_constructor = init_of_local_vars + expense_of_path_normalization + expense_of_prefix_length_computation

With an array of n String pathnames, the cost is just
 n * (avg_construction_of_individual_path_strings_off_filesystem)

In terms of space, the memory footprint of an array of n File objects will be:
 n * (avg_string_path_size + 32_bits_of_prefix_length + size_of_File_object_itself)

whereas an array of n String objects will be
 n * avg_string_path_size

For simplicity and convenience, I'd go with an array of Strings. I wouldn't even had bothered to do any estimation. Simpler tends to be better most of the time. And this minutia will only matter if you are working with a very constrained device (a mobile phone for instance.)
Comment: Nevertheless to delete a file, you will create a `File` object _n_ times.
Comment: Correction: To delete `a` file, you create `1` File object. To delete `n` files, you create `n` File objects. Do we want to create *n* File objects at once, or only one at a time at the moment of deletion? Yes, indeed we have to create *n* number of File objects, but there is a  big difference between carrying them around in an array all at once and doing so in a staggered, on a need-basis fashion. In general, you create a resource only at the time that is is needed.
Comment: Yes, that's true. The array of _n_ `File` objects takes more memory than array of _n_ `String` objects.


Generate All Triangular Square Numbers Recursively?

Question: We define a triangular number as follows:
$$\sum_{n=1}^{n} x_{i}$$
As in $T_3$ = $3+2+1$, or $6$.
Generating these triangular numbers is rather simple and done by the equation:
$$T_n ={(n^2 + n)}/{2}$$
I am asking a question about how to generate Triangular Square numbers, those numbers that are both triangular and perfect squares. As in,
$$ s^2 = {(t^2 + t)}/{2}$$
Completing the square yields the following:
$$(2t + 1)^2 - 8s^2 = 1$$
Which is known as an instance of the pell equation, or
$$x^2 -2y^2 = 1$$
This is where I kind of get stuck. I thought about taking the line $y = mx - m, m \in Q$ searching for the other intersection point. Is that a way to go about this? If so,
Substituting y from the line into the pell equation yields:
$$x^2 -2m^2(x-1)^2 -1$$
Which, when divided by the other intersection point $x-1$ should yield another intersection point:
$$ \dfrac{x^2 -2m^2(x-1)^2 -1}{x-1} = -2 m^2 x+2 m^2+x+1 $$
Solving for x,
$$ x = \dfrac{2 m^2+1}{2 m^2-1} $$
Substituting back into the line equation we can get the ordered pair of the other intersection point:
$$ (x,y) = \Big(\dfrac{2 m^2+1}{2 m^2-1}, \dfrac{2 m}{2 m^2-1}\Big)  $$
Though, how can I generate integer solutions? I see that some people say to take $$m = \dfrac{v}{u}, u^2 -2v^2 = 1$$
Following this advice, one gets the denominator $2 m^2-1$ to be
$$ 2\big(\dfrac{v^2}{u^2}\big) - 1 = \dfrac{-u^2 + 2v^2}{u^2} = -1/u^2  $$
Therefore, the point comes out as follows:
$$ (x,y) = \Big(-u^2 - 2v^2, -2vu\Big)  $$
Which for some reason is very similar to the generating function of pythagorean triples, but I think thats besides the point? Well, we have somewhat done what we set out to with this function. Take the solution to the equation (3,2) for example, using our new point we get (17,12) which yields the triangular square 36. Keeping this up recursively will keep us going! Woohoo!
But why? What does this tell us? I tried to work it out and don't see those always being integer solutions. How can I generate all of these triangular square numbers. Does continuing with this method guarantee there are infinitely many? How do you prove every triangular square is of this form?
Comment: To generate integer solutions, you want your denominator $2m^2 - 1$ to be an integer. As $m$ is your (presumably rational) slope, you might as well call $m = u/v$. Then your denominators become $2v^2 - u^2 = 1$, which is morally the same Pell Equation as you started with. So you have travelled in a circle thus far.
Comment: I added a little more info @mixedmath
Comment: The $m$th square number is equal to the $n$th triangular number if
$m={{\left(3+2\sqrt 2\right)^u-\left(3-2\sqrt 2\right)^u}\over{4\sqrt 2}}$
 and
$n={{\left(3+2\sqrt 2\right)^u-2+\left(3-2\sqrt 2\right)^u}\over 4}$.
Comment: Ah I have indeed seen that @SenexÆgyptiParvi. Though is this way not also valid? I am more interested in proving how this generating strategy proves the questions at the bottom. I will clarify.
Comment: I would suggest substituting the expression for $m$ into the formula for square numbers $m^2$ and the expression for $n$ into the formula for triangular numbers $\frac{n^2+n}2$. If the two results are equal, then the assertion is proved. It's simpler than you think. It is easy to prove, but to render it in MathJax is a pain in the kiester. If $u$ is an integer, then $m$ and $n$ will be, too.
Comment: http://math.stackexchange.com/questions/855300/distribution-of-integer-solution-pairs-x-y-for-2x2-y2-y/855342#855342
Answer: If $A_n$ is the $n$th triangular square, then for $n \ge 2$ the recursion $$A_n = 34A_{n-1} - A_{n-2} + 2$$ holds, with initial conditions $A_0 = 0$ and $A_1 = 1$.
And, yes, having such a recursion guarantees that there are infinitely many, and that they are all integers.
EDIT: https://oeis.org/A001110
Comment: A proof, or at least a reference, might be useful for this.
Comment: Good point. OEIS link added.


Identificador no Apache ActiveMQ

Question: Estou tentando integrar um consumidor à uma fila que utiliza o message broker Apache ActiveMQ. No entanto, para consumir essas filas é preciso configurar um identificador, usuário e senha. Não consigo setar esse identificador, o código que estou usando é este:
<code>    using Apache.NMS.Util;
    using System;
    using System.Threading;

 namespace Apache.NMS.ActiveMQ.Test
 {
    public class TestMain
    {
        protected static AutoResetEvent semaphore = new AutoResetEvent(false);
        protected static ITextMessage message = null;
        protected static TimeSpan receiveTimeout = TimeSpan.FromSeconds(10);

        public static void Main(string[] args)
        {
        string conexao = "tcp://IP-DA-FILA-DO-SISTEMA";
        string FILA = "FILA-DO-SISTEMA";

        string identificador = "IDENTIFICADOR-FILA-SISTEMA";

            Uri connecturi = new Uri(conexao);

            Console.WriteLine("Conectando com: " + connecturi);

            IConnectionFactory factory = new NMSConnectionFactory(connecturi);

            using (IConnection connection = factory.CreateConnection("ADMIN", "ADMIN"))
            using (ISession session = connection.CreateSession())
            {
                IDestination destination = SessionUtil.GetDestination(session, FILA);

                Console.WriteLine("Usando o destino: " + destination);

                using (IMessageConsumer consumer = session.CreateConsumer(destination))
                //using (IMessageProducer producer = session.CreateProducer(destination))
                {
                    // Iniciar a conexão que as mensagens serão processadas
                    connection.Start();

                    //producer.DeliveryMode = MsgDeliveryMode.Persistent;
                    //producer.RequestTimeout = receiveTimeout;

                    consumer.Listener += new MessageListener(OnMessage);

                    //producer.Send(request);

                    semaphore.WaitOne();
                }
            }
        }

        protected static void OnMessage(IMessage receivedMsg)
        {
            message = receivedMsg as ITextMessage;
            Console.WriteLine(message.Text);
        }
    }
}
</code>
O usuário, senha e endereço da fila estão corretos (não são esses que estão no código acima), mas não consigo configurar esse identificador que está faltando.
Mensagem de erro:
<code>Apache.NMS.ActiveMQ.BrokerException: 'java.lang.Exception : Invalid consumer for username + password combination!
</code>
O erro é exibido na seguinte linha:
<code> using (IMessageConsumer consumer = session.CreateConsumer(destination))
</code>
Aparentemente a conexão é feita, mas está faltando inserir esse identificador para conseguir criar o consumer.
Comment: Alguma mensagem de erro? Você debugou o código? De onde você pegou esse trecho de código?
Comment: Leandro, editei a postagem. Esse trecho de código foi disponibilizado pela apache neste link:https://activemq.apache.org/components/nms/examples/nms-simple-asynchronous-consumer-example
Comment: Não está faltando coisa na sua connection string? tipo `activemq:tcp`, assim como na declaração das filas e consumers?
Comment: Já tentei inserindo a string `activemq` antes do endereço tcp e ainda ocorre o mesmo erro. Em alguns teste que realizei, o código activemq que antecede o endereço da conexão é opcional.
Answer: Estou respondendo minha própria pergunta para ajudar pessoas que tenham o mesmo problema no futuro.
O erro de conseguir fazer a conexão e não conseguir criar o consumidor é um problema de permissões no message broker. Após resolver esse problema de permissão, foi gerado novos endereços de fila e agora é possível consumir os dados.

Identificador no Apache ActiveMQ


Terrible performances using a remote Azure SQL Database

Question: We're currently evaluating Azure's SQL Database service (vs local installation) because we would like to have the "Always Encrypted" feature integrated in our (java-based) application.
Problem is, performances are terrible.
I'm connecting from a physical server located in the same area (Paris) to the database created in the "France Central" region.
I wrote a very simple java application which does 5000 inserts (prepared statements) in a very simple table, it's using the Microsoft jdbc driver and the Azure's provided connection string.
It takes nearly a minute to complete, whatever the type of SQL Database I use (last test with S6 Standard). The java application ran on a production server (8 cores).
I would expect some latency from using a remote database, but not to this level. (the same test is running in 5 seconds with SQL Server on the local server).
Is it what's to be expected ? I though our case was the case addressed by the SQL Database service (remote SQL server). I also created a VM in the same region, connecting through the public IP of the database, and it was nearly as bad. I tried to create SQL Databases in other european countries, and it was just worse.
Answer: Seems reasonable. Especially if the inserts are being run in serial. Breaking it down:
Say there's 30ms RTT between the app and db server. Since SQLServer is an ACID compliant database, and the database driver honors this, the theoretical maximum amount of TPS is 33 per second as the driver will block until it receives an ACK from the database. (1000ms / 30ms = ~33 TPS)
You are achieving around 83 TPS, so I'm guessing the latency between the app server and the db is around 12ms.
On the local server, you probably have sub millisecond timings.
Remote databases are just a bad idea. But if you have to do it, try to batch operations into a single transaction as you can pack more data into a RTT hop. With that said, it means a failure is much more expensive (retrying 1 insert vs retrying all 100). Take it all into consideration, but anything you can do to reduce latency (or increase parallelism) will make a substantial difference.
Comment: It's one of my favorite interview questions ;) - finding good resources that discuss this is hard, but this article from the Galera team does a great job highlighting the phenomena in action: http://galeracluster.com/2015/07/cant-be-any-faster-than-that-a-real-life-experiment-with-latency-in-a-geo-distributed-environment/
Comment: Great answer, Learn something new everyday. 33 TPS seems so low though
Comment: Thank you ! On a hunch, I've done a mtr to the database sever. I got a lot of drops (nearly 50%), even with a 1s delay. Don't know if this test is meaningful though.


Custom post using angular rails resource

Question: Hi I'm using rails and angularjs with the angularrailsresource gem. I need to do a custom post request to a rails resource I have defined called 'Comment'. I tried using the $post method like this:
  Comment.$post('some_method', {comment_id: comment.id, username: username, type: 'mention'}).then(function(result){
    console.log(result);
  });

and it makes a request but it always makes it under the root of the page I'm on. So I want to make a request to '/comments/', but it tries to make a request to '/patients/some_method' and if I do this:
  Comment.$post('comments/do_stuff', {comment_id: comment.id, username: username, type: 'mention'}).then(function(result){
    console.log(result);
  });

it will try to post to 'patients/comments/some_method', or whatever else the root of the page I'm on is. Is there a way to tell it to post directly to the resource and not through the the url context that I am currently on? Thank you for your help.
Answer: You have to use the path with a / before it, otherwise it will trigger the action using the relative path. Try this:
Comment.$post('/comments/do_stuff' ....

Notice the / before comments.


Copy all fields of one object type to other object type in C#

Question: I have two objects but having different types. The information stored in them are almost similar, i.e. all field names are almost same in both objects,  its only the type that differs. I want to copy the values of one object to other. The object also have complex types as fields for ex: a list. Please suggest me some library or framework to do that or if there is a native method available in .net C#.
Comment: "Questions asking us to **recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic** for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it."
Comment: Have a read of [Which is the best approach? AutoMapper against implicit (C# Reference)](http://stackoverflow.com/questions/29257215/which-is-the-best-approach-automapper-against-implicit-c-reference)
Comment: Field names are almost same in both objects?
Comment: @Paparazzi Yes! but few complex types inside the object like list are again of different types from other object  but contain the same fields again.
Comment: "only the type that differs" - that is the point which will prevent a "duck copy" approach like that suggested by Adil. With that constraint, there is no general way available.
Answer: This code requires some modifications to suit your needs. But overall it looks like.
<code>    private void button1_Click(object sender, EventArgs e)
    {
        classA A = new classA("test");
        classB B = new classB();

        foreach (var field in A.GetType().GetProperties())
        {
            PropertyInfo pi = B.GetType().GetProperty(field.Name);
            pi.SetValue(B, field.GetValue(A, null));
        }

    }

public class classA{
    public string name { get; set; }

    public classA(string name)
    {
        this.name = name;
    }
}

public class classB
{
    public string name { get; set; }
}
</code>


Triangular Numbers that are odd, less than 2000

Question: The diagram below shows the $1$st, $2$nd, $3$rd and $4$th triangular numbers.

(1 spot)  : $1$
(3 spots) : $3$
(6 spots) : $6$
(10 spots) : $10$

The formula $n(n + 1)/2$ can be used to find the $n$th triangular number.
For example the fifth triangular number is
$5(5 + 1) / 2 = 5 \times 6 / 2 = 15$
How many of the triangular numbers that are less than $2000$ are odd?
My thought: So I can see a pattern here: $1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78 \ldots$. So after the first $3$ there is an equal number of odds and evens.
But that is a problematic way to calculate it. What is the easier way?
Comment: Where is the diagram? Have you copied this question from somewhere?
Comment: Sorry, yes, it is from a test sheet I am studying. The diagram is just of spotted triangles. I can't think how to show this with text.
Answer:
$\dfrac{n(n+1)}{2}<2000 \implies n^2+n-4000<0 \implies n<\dfrac{-1+\sqrt{16001}}{2}\approx62.75$
$\dfrac{n(n+1)}{2}\not\equiv0\pmod2 \implies n(n+1)\not\equiv0\pmod4$
$\implies [n\not\equiv0\pmod4]\wedge[(n+1)\not\equiv0\pmod4]$
$\implies [n\not\equiv0\pmod4]\wedge[n\not\equiv3\pmod4]$
$\implies [n\equiv1\pmod4]\vee[n\equiv2\pmod4]$
Therefore $n\in\{1,2,5,6,9,10,\dots,61,62\}$
Hence there are $\dfrac{62}{2}+1=32$ odd triangular numbers smaller than $2000$
Comment: I can't seem to suggest an edit to this from my phone but the second bullet point is: $\dfrac{n(n+1)}{2}\pmod2\equiv1 \implies$$ [n\equiv1\pmod4]\vee[n\equiv2\pmod4]$
Comment: @BeaumontTaz: And the point in quoting this bullet here is...?
Comment: It may just be the app on my phone, but that line of MathJax is showing a math processing error on my end.
Comment: @BeaumontTaz: Well, your first comment looks like you've simply copy-pasted that bullet from the answer.
Comment: I broke it into two math tags. For some reason it has to do with the '\implies' and the '[' after. So I just broke it into two different math tags. I was only trying to fix the MathJax, not the math. So it's supposed to look the same. Again, I'm on my phone and it may only be an issue on this end.
Comment: @BeaumontTaz: There is no change in the contents, and the "edited" link doesn't indicate that it was edited recently... And it looks fine from here (running in FF on a desktop).
Comment: I was able to borrow a computer for a second to check and it looks fine in Chrome too. But I'm using the StackExchange App for iPhone and it was throwing an error. I'm sure it's a problem with the app and not with the post. But it now here for anyone who uses the app and not a true browser.
Comment: Sorry, how do you get from: n2+n−4000<0 to n<63
Comment: @user1495024: I added that to the answer (though it's a simple quadratic equation to solve, which I would have expected you to know).
Answer: Note that amongst the even numbers, multiples of $4$ alternate with multiples of $2$ which are not multiples of $4$.
If the even number out of $n$ and $n+1$ is a multiple of $4$, the triangle number will be even, otherwise it will be odd.
You can use this to show rigorously that pairs of odd triangle numbers alternate with pairs of even triangle numbers. Then you simply have to check what happens at the beginning of the list and at the end of the list to adjust for the boundary effects.
I don't know why you think that is a problematic way to calculate - it would also work for $2,000,000$ for example.
Comment: @user1495024 So $\sqrt {4000} \approx 63$ (note that $64^2=4096$ if you know your powers of $2$, and that $4000=2\times 2000$) so that the possibilities for the last triangle number before $2000$ are $64\cdot 63/2 = 2016$ or $62\cdot 63/2= 1953$
Comment: I don't think the question is well worded, but the hardest part (for me) is calculating the number of triangular numbers that are less than 2000 (i.e. they do not want the 2000th triangular number but the triangular numbers that are less than 2000)
Comment: The $n$th triangular number is given by $n(n+1)/2$ as noted above.  So to find how many triangular numbers are less than $2000$ you solve $n(n+1)/2 < 2000$.  That's a quadratic inequality, so you can use the quadratic formula to find the roots.  If you're still not sure which one you want, substitute them back into $n(n+1)/2$ and take $n$ which yields an answer less than 2000.
Answer: Let's take the number to be:
$$N=\frac {n(n+1)}2$$
If it is odd it must not be divisible by two, so $n(n+1)$ must be divisible by 2 only once. As  when we take two consequtive numbers one of them must be even always, so, suppose:
Case I
$n$ is even and divisible by two only once, then $n+1$ must be odd;
Possible numbers are:
$2,2\times3,2\times5,2\times7,...$
Or put it other ways it is of the form $2\times p$ where $p$ is a prime no., the pattern to which is not possible.
CaseII
Consider similiarly (n+1)...


Force autoCompleteTextView dropdown to show in a different view

Question: Usually the dropdown is visible as a dropdown with the autoCompleteTextView or you can anchor it to some other view.
What I need is to show the dropdown list as a listView below the autoCompleteTextView and not as a dropdown itself
something like this:

So when I start typing "Ap", the only thing  that shows is Apps and no dropdown shows at all
Answer: Auto Complete cannot do this but you can use filters.
A simple TextView (with a TextWatcher) and a ListView with a suitable adapter acting as a filter can achieve your goal. (Suggested by Nguyen Doan Tung)


If $a > 1$, $x >0$, show that $x^a - 1 \ge a(x-1)$.

Question: The question was taken from Serge Lang's "A First Course in Calculus". The particular section where this question was found is Exponents and Logarithms.
If $a > 1$, $x >0$, show that $x^a - 1 \ge a(x-1)$.
I let $f(x) = x^a - 1- ax + a$. Note that $f(0) = a - 1 > 0$ and if we can prove that $f' \ge 0$ for $x>0$ then the inequality holds. Now consider the first derivative $f'(x) = ax^{a-1} - a = a(x^{a-1} -1)$. It suffices to show that $x^{a-1} - 1 \ge 0$.
I was tempted to say that since $a-1 > 0$, then $x^{a-1} > x^0 = 1$ for $x >0$ and therefore $x^{a-1} - 1 \ge 0$. However, I do not really know how true my previous assertion is.
Comment: This doesn't work if $x<1$. A concrete example is that $\left(\frac{1}{2}\right)^{2-1} = \frac{1}{2} < 1$.
Comment: @CarlSchildkraut Yes you are absolutely right.
Answer: From your $f'$ formula, it's easy to see $f$ is decreasing on $(0,1)$ and increasing on $(1,\infty)$, that means $f$ achieves minimum at $x=1$, and $f(1)=0$. Therefore $f(x)\geq 0$.
Comment: Yep thanks a lot! Just when I needed someone's help to unclog my mind!


adding all children node flag count to sort parent

Question: i have created two content type parent and child. a parent has children. and each child has own flag count value. like:
under Parent A
   child1 had flag count=5
   child2 had flag count=2
   child3 had flag count=0
under Parent B
    child1 had flag count=3
    child2 had flag count=1
    child3 had flag count=0
    child4 had flag count=6.
now sort the parent according to all children's flag count value.Like here Parent B should come first because he has his children flag count value is 10..
please help me to short out this scenario...
Answer: Is it possible to have a hidden field on parent node value for which updates as per the flag counter on referenced node changes.In that case it will be easier to build custom query or even if you use views you can sort by the hidden field  value.
Updated:

Child node 1 has a node reference to Parent Node.
Keep flag count as hidden field on parent content type
The time flag is updated on Child node, you can grab all parent nodes on the updated child node.
Change the hidden field value on parent node from hidden field value to +1.

Code that can be used to update parent node field
 - you will have all parent node id in child node object, grab the ids.
 - Use the following code to update the parent fields.
<code>  $node = node_load($nid);
  $node->field_flag_count['und'][0]['value'] += 1;
  field_attach_presave('node', $node);
  field_attach_update('node', $node);
</code>

This will save lot more node save processing and unnecessary node
  revisions

SO this way the total flag count will all be present on parent node and sorting will be lot more easier that way!.
Comment: but i have reference node, in child to point the parent. according you, should i create the node reference field in Parent to his adding child.can u suggest me clearly step to do this task
Comment: Please check the updated answer if it helps you


How do I get the assigned values for enum members?

Question: The following code returns One, Two, Three, where I expect GetNames to do that and GetValues to return 2, 5, 10:
enum Nums
{
  One = 2,
  Two = 5,
  Three = 10
}

class Program
{
  static void Main()
  {
    var vals = Enum.GetValues(typeof(Nums));
  }
}

What is up here? How do I get the values 2, 5, 10 from the type Nums?
Answer: cast it to an int like this:
int value = (int)Num;

Answer: You need to cast it to an int:
int val = (int)Nums.One;

Or to answer your question for getting all of the items in the enum:
IEnumerable<int> values = Enum.GetValues(typeof(Nums)).Cast<int>();

Answer: You can do it like this:
int[] vals = Enum
    .GetValues(typeof(Nums)) // Thus far, this is your code
    .Cast<int>()             // Cast individual elements to int
    .ToArray();              // Convert the result to array

Here is a demo on ideone.
Answer: I haven't fully wrapped my head around C# Enums yet, but the Enum.GetValues documentation has an example that shows that casting has some very interesting and powerful effects on them.  http://msdn.microsoft.com/en-us/library/system.enum.getvalues(v=vs.110).aspx
using System;

enum SignMagnitude { Negative = -1, Zero = 0, Positive = 1 };

public class Example
{
   public static void Main()
   {
      foreach (var value in Enum.GetValues(typeof(SignMagnitude))) {
         Console.WriteLine("{0,3}     0x{0:X8}     {1}",
                           (int) value, ((SignMagnitude) value));
}   }
}
// The example displays the following output:
//         0     0x00000000     Zero
//         1     0x00000001     Positive
//        -1     0xFFFFFFFF     Negative


HackerRank Big Sorting segmentation Fault in C++

Question: I have a question about the BigSorting task from HackerRank.
My code successfully runs all tests except 3. (I located files on which my program does not work under the names input03.txt, input04.txt and input05.txt on my google drive. Here is the link to the drive.) https://drive.google.com/drive/u/1/folders/1psno2RbeYXX5ohHjs5BWke6E-K2cJl-3
My program crashes with a "Segmentation fault" error. I've been sitting for 2 hours and can't understand what the mistake is. This is my first question on StackOverflow, so I apologize right away if I did something wrong.
Here is the code.
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>

bool isShorter(const std::string& s1, const std::string& s2)
{
    if (s1.size() != s2.size())
    {
        return s1.size() < s2.size();
    }
    else
    {
        for (int i = 0; i < s1.size(); ++i)
        {
            int x = s1[i] - '0';
            int y = s2[i] - '0';
            if (x != y)
            {
                return x < y;
            }
        }
    }
    return true;
}

std::vector<std::string> bigSorting(std::vector<std::string> unsorted)
{
    std::sort(unsorted.begin(), unsorted.end(), isShorter);
    return unsorted;
}

Comment: Compiling your code with debug symbols and then running it through a debugger might help.
Comment: Please show a full [repro] of the problem. That means code, including a `main`, that can be compiled and executed as is. Without it, while I see an error in your code, I cannot tell whether it is the only one and responsible for the segmentation fault.
Comment: Ok, thanks for you answer! Next time I will show full code, including main.
Answer: The function given to std::sort is supposed to induce a strict weak ordering on the elements in the iterator range, see std::sort, Compare requirements and strict weak ordering on wikipedia.
Your isShorter induces an order that is not strict. In particular it does not have the property that isShorter(x, x) == false for all x.
The problem is that you return true when you cannot find either string to come before or after the other in the order, but you should return false.
The function is supposed to model <, not <=.
Whether this is the cause of the segmentation fault is unclear since you haven't given a full code example, but violating the std::sort requirements does cause undefined behavior.


Is a positive definite matrix times a positive semidefinite matrix positive semidefinite?

Question: I have a couple questions actually, couldn't get both of them in the title.
First suppose I have a positive definite matrix H and a positive semidefinite matrix D.  I believe that H*D would be a positive semidefinite matrix.  Is this correct?
Second suppose I have a vector $g$.  If I were to multiply $g$ by its transpose so that I get a matrix and not a single value, would the resultant matrix be positive semidefinite?  I believe that it will be.
I'm not looking for a proof (though it wouldn't be out of place for others looking for answers to similar questions) just yes or no answers and a brief explanation of why I am wrong, if am wrong.  I am working on a proof and want to make sure that my intuition is correct.
Comment: For the second question, use the fact that a real symmetric matrix $S$ is PSD iff $x^TSx\geq 0$ for all appropriately sized real vectors $x$. If $S=gg^T$, then $S$ is symmetric since $(gg^T)^T=(g^T)^Tg^T=gg^T=S$ and for any vector $x$, $x^Tgg^Tx=(g^Tx)^T(g^Tx)=(g^Tx)^2\geq 0$. Hence $S$ is PSD.
Answer: The matrix $uu^T$ is a special case of $\mathsf{PSD}$, (Positive semidefinite), matrices called a symmetric dyad.
Indeed, if $A = uu^T$ for some vector $u \in \mathbf{R}^n$, then for every $x$:
$$q_A (x)  = x^T uu^T x = (u^Tx)^2 \ge 0.   $$

Another way to look at this is thus:
$$\begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{bmatrix} \cdot \begin{bmatrix} x_1 & x_2 & \ldots & x_n \end{bmatrix} = \begin{bmatrix}x_1^2 & x_1x_2 & \ldots & x_1x_n \\ x_2x_1 & x_2^2 & \ldots & x_2x_n \\ \vdots & \vdots & \ddots & \vdots \\ x_nx_1 & x_nx_2 &\ldots &x_n^2 \end{bmatrix}$$
What can you say about the above matrix? In particular, it's symmetric, and what property do all of its leading principal minors have in common?
To answer your first question, I would direct you to an answer of Plainview's in
the following question: Is the product of symmetric positive semidefinite matrices positive definite?

The product of two symmetric $\mathsf{PSD}$ matrices is $\mathsf{PSD}$, iff the product is also symmetric. More generally, if $A$ and $B$ are $\mathsf{PSD}$, $AB$ is $\mathsf{PSD}$ iff AB is normal, ie, $(AB)^T AB = AB(AB)^T$.

Since your matrix $H$ is positive definite, it is also positive semidefinite. Therefore, the product $HD$ is positive semidefinite iff
$$
(HD)^T HD = HD(HD)^T
$$
Comment: I read the wiki article as well.  That is for pos def matrices.  I am not making any conclusions with pos def, only pos semi def.  What would be a counter example?
Comment: @user2736423 For example, $H = 2I$, and $D$ contains only ones (both of the same arbitrary order).


Intellij 2021 Cannot resolve symbol if it's from a custom maven repo?

Question: I have a project where I'm using a dependency from a custom repository. This is what my build.gradle looks like (I have blurred out some dependencies for privacy):
plugins {
    id 'org.springframework.boot' version '2.5.6'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'groovy'
}

group = 'com.myproject.projectx.sms'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
    maven {
        url "s3://myproject-maven-repo"
        authentication {
            awsIm(AwsImAuthentication)
        }
    }
}

dependencies {
    implementation 'org.postgresql:postgresql'

    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.security:spring-security-core'

    implementation 'com.myproject.top:secret-project:1.2' <------------ Gradle won't download this. why?

    testImplementation 'org.spockframework:spock-spring:2.0-groovy-3.0'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
        exclude group: 'org.junit', module: 'junit'
    }

    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
}

test {
    useJUnitPlatform()
}

There are red squiggly underlines when I hover over code that's using the top:secret-project dependencies. This used to work in old projects, but why can't intellij recognize it in this project? Also I can run the project successfully in ubuntu terminal with gradle bootRun. It's just intellij cannot recognize it. It also able to recognize spring, postgres, lombok & spock dependencies.
Cannot resolve symbol 'com.myproject.top.secret.TopSecretService'.

When click on build for gradle, I keep getting this error.
Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied;)

I already exported the correct secret and keys in my .bashrc file. I also already configured ~/.aws/credentials. But I'm still getting the error above.
Answer: Am not really familiar with AwsImAuthentication nor the s3:// , but as it mentioned in the official doc that you need to add user/pass , or user/token as following
maven {
         url 'https://my_domain-111122223333.d.codeartifact.region.amazonaws.com/maven/my_repo/'
         credentials {
             username "aws"
             password System.env.CODEARTIFACT_AUTH_TOKEN
         }
}

where CODEARTIFACT_AUTH_TOKEN is enviroment variable to store your password/session .
You can also use the gradle.properties to retrive the value , just make sure to replace System.env.CODEARTIFACT_AUTH_TOKEN with
 project.findProperty.CODEARTIFACT_AUTH_TOKEN where CODEARTIFACT_AUTH_TOKEN is store the password/token in your gradle properties .


Counting in base 13

Question: So, I was counting in base $8$:
$1,2,3,4,5,6,7,10,11,12,13,14,15,16,17,20,21,22,23,24,25,26...$
Then I tried counting in base $13$ and got confused:
$1,2,3,4,5,6,7,8,9,10,11,12$ (confused here, maybe:) $1(01),1(02),1(03),....1(12),2(00).$
Is there a nice or more standard way list the counting numbers in a base above $10$?
Comment: For new digits, either use new symbols or (for large number bases) use decimal numbers separated by a separator. For example, $n=12\cdot13^2+12\cdot13+12$ would be $ccc_{13}$ or $12:12:12_{13}$ (or $(12,12,12)_{13}$).
Comment: It is perhaps more common to use letters, e.g., a=10, b=11, c=12. For instance the hexadecimal (16) base has 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f as "digits".
Comment: $10_{13}$ would be $13_{10}$.  You need new symbols.  You could write, e.g., $a_{13}, b_{13}, c_{13}$ for $10,11,12$ in base $10$.
Comment: Base $16$ (used in computing contexts) takes "ABCDEF" as extra digits.
Comment: Indeed, in the computer world, where base $16$ is common, we use $$A=9+1,B=9+2,C=9+3,\\D=9+4,E=9+5,F=9+5$$ But in theory, you could use any symbols, as long as everybody with whom you are conversing in a base agree.
Answer: In order to work in base $13$, you need three extra symbols, which represent $10$, $11$, and $12$. Suppose that these symbols are $A$, $B$, and $C$ respectively. Then you have:$$1,2,3,4,5,6,7,8,9,A,B,C,10,11,12,13,14,15,16,17,18,19,1A,1B,1C,20,\ldots$$
Answer: The standard way (at least as it's used conventionally in base 16 in computing contexts) is to start using letters. So you get
$$
0,1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C,\\
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C,\\
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 2A, 2B, 2C, \\
\vdots
$$
Some prefer to use lower case instead, and that's fine too. And of course you're free to invent your own symbols if you'd like, or steal symbols from somewhere other than the Latin alphabet. Just be sure to inform your readers which symbol means what.
Answer: The standard way to count this (which is used in hexadecimal: base-$16$) is to use the letters of the alphabet like so:
$$
1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E ...
$$
So in base-$13$ it would be:
$$
\begin{align}
&1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C \\
&10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C \\
&20...
\end{align}
$$

Counting in base 13


How to allow multiple values in a single value textfield

Question: I am using views_conditional module for Drupal 7 and would like to use a comma separated array (i think this is called an array?) of values in the "This value" textfield.
For example, I would like to add a views conditional field that checks for:
If this field...
[type] == Content Type
Is...
Contains
This value...
Apples, (or) Oranges, (or) Bananas
As it is right now, (unless I am missing something) I would need to add 3 separate conditional field. One for each content type (apples, oranges, and bananas) though they are all executing the same function.
(I think) The current definition for the value field is:
<code>$form['equalto'] = array(
  '#type' => 'textfield',
  '#title' => t('This value'),
  '#description' => t('Input a value to compare the field against.  Replacement variables may be used'),
  '#default_value' => $this->options['equalto'],
);
</code>
I also think the logic for the "Is..." operator in this use case would technically need to be something like "Contains Any".
(I think) The "Contains" function is defined here:
<code>      // Contains
  case 7:
    if (mb_stripos($r, $equalto) !== FALSE) {
      return $then;
    }
    else {
      return $or;
    }
    break;
</code>
Is there a way to simply write a couple of hooks to alter the form, or would i need a full blown module patch?
Any help or pointers would be greatly appreciated! I am pretty new to backend code. I also posted a support request at Drupal.org
Answer: There is a patch for this for anyone else looking for a solution.
https://www.drupal.org/project/views_conditional/issues/2690167


Insufficient Privileges :Error in Generating WSDL File For Salesforce API

Question: I am trying to get WSDL File For Consuming Salesforce API But As Per their docs here - generate wsdl docs salesforce
After clicking on generate enterprise WSDL i am getting below error page
Insufficient Privileges
You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary. For more information, see Insufficient Privileges Errors.
Comment: Whats your question?
Comment: @superfell its quite clear i am unable to generate wsdl file for salesforce api and question is why ? do i missing something . I have logged in as free salesforce developer account . and followed the link (provided in question ) to generate wsdl file ( file required to use their soap api )
Comment: Are you sure you have a developer edition account and not a free trial account [dev edition includes API access, free trial accounts do not]. FWIW, i just signed up a new dev edition account and downloaded the enterprise WSDL fine.
Comment: @superfell
you can see discussion in question - http://salesforce.stackexchange.com/questions/138196/how-to-get-customers-and-opportunities-info-through-salesforce-api
Comment: @superfell i am having Professional Edition . do i need to pay to consume salesforce API . to get opportunities info and customer info .  if you see comments there you will find problem
Comment: You have to buy an API add-on for Prof Edition.
Comment: @superfell thanks i got it found a pdf will be sharing it in answer
Answer: To use the APIs you need them to be enabled.
Some editions come with API Access - See Salesforce editions with API Access.
By default a professional edition org doesn't have API access, but it can be purchased as an add-on by contacting your Account Executive.
Once you do have the API enabled, you also need the "API Enabled" Administrative Permission.


If $q_1<q_2\in(0,\frac{1}{2})\subset\mathbb{Q}$, then $f(q_1,q_2)=\cos(q_1\pi)-\cos(q_2\pi)$ is bijective between the domain and the image set?

Question: When I was studying on a conjecture, I noticed this problem:

If $q_1<q_2\in(0,\frac{1}{2})\subset\mathbb{Q}$, then $f(q_1,q_2)=\cos(q_1\pi)-\cos(q_2\pi)$ is bijective between the domain and the image set?

I find the only counter example with the help of wolfram mathematica:
$$
\cos \left(\frac{2 \pi }{7}\right)-\cos \left(\frac{3 \pi }{7}\right)=\cos \left(\frac{\pi }{7}\right)-\cos \left(\frac{\pi }{3}\right)
$$
It is confused why there has the only counter example.
This reflects a somehow special property of trigonometric functions, because it does not always hold in other functions, for example:

If $q_1<q_2\in\mathbb{Q}$, then $f(q_1,q_2)=q_2^2-q_1^2$ is not bijective because there are counter examples : $25^2-20^2=39^2-36^2$and so on.

More details: I find another conjectures with the help of wolfram mathematica.
$\textbf{Conjecture 1.}$ If integer $n\geq 9,n=2^a p^b, a,b \geq 0$, p is a prime and $a\geq2$ if $b=1$, then when there are linear relationships in $\left\{ \cos(\frac{k\pi}{n}):k\in \left[1,\left\lfloor \frac{n-1}{2}\right\rfloor \right]\subset \mathbb{Z}\right\}$, the number of $\cos(\frac{k\pi}{n})$ in each set of linear relationships is $p$.
For example, if $n = 40$, we have
$$
\cos \left(\frac{3 \pi }{8}\right)+\cos \left(\frac{\pi }{40}\right)-\cos \left(\frac{7 \pi }{40}\right)-\cos \left(\frac{9 \pi }{40}\right)+\cos \left(\frac{17 \pi }{40}\right)=0\\
-\cos \left(\frac{\pi }{4}\right)+\cos \left(\frac{\pi }{20}\right)-\cos \left(\frac{3 \pi }{20}\right)+\cos \left(\frac{7 \pi }{20}\right)+\cos \left(\frac{9 \pi }{20}\right)=0\\
-\cos \left(\frac{\pi }{8}\right)+\cos \left(\frac{3 \pi }{40}\right)-\cos \left(\frac{11 \pi }{40}\right)+\cos \left(\frac{13 \pi }{40}\right)+\cos \left(\frac{19 \pi }{40}\right)=0
$$
each set of linear relationships is $5$, $5$ is the largest prime factor of $40$.
I'm just an undergraduate student at the university and I don't have any idea to prove these two conjectures. It would be very useful if someone could give a counter example or provide some ideas for proof.
Comment: Shouldn't the function be calculated $q2-q1$ if $q1<q2$ because $A-B ≠ B-A$
Answer: Here is the case when the rational numbers have denominators a prime (a similar approach may work for the general case). That is, let $p$ be a prime, so that
$$\cos(\frac{2\pi k_1}p)-\cos(\frac{2\pi k_2}p)=\cos(\frac{2\pi\ell_1}p)-\cos(\frac{2\pi \ell_2}p)$$
for integers $k_1,k_2,\ell_1,\ell_2\in(0,\frac{p-1}2]$. Now, since the Galois orbit of $\zeta_p=e^{2\pi i/p}\in\mathbb Q(\zeta_p)$ is a normal basis (see this), the Galois orbit of $$\zeta_p+\zeta_p^{-1}=2\cos(\frac{2\pi}p)\in\mathbb Q(\zeta_p+\zeta_p^{-1})=\mathbb Q(\cos(\frac{2\pi }p))$$ is a normal basis. That is, $\{\cos(\frac{2\pi k}p):k\in(\mathbb Z/p)^\times/\{\pm1\}\}$ are linearly independent, since $\mathbb Q(\cos(\frac{2\pi}p))/\mathbb Q$ has Galois group $(\mathbb Z/p)^\times/\{\pm1\}$.
Thus, we must have that $k_1=k_2$, so $\ell_1=\ell_2$ as well.
Comment: Thanks for your reply, I think your idea is right. However, when I consider the general case, there are some difficulties (see the update on the question for more details).
Answer: I find a counter example:
$$
\cos \left(\frac{2 \pi }{7}\right)-\cos \left(\frac{3 \pi }{7}\right)=\cos \left(\frac{\pi }{7}\right)-\cos \left(\frac{\pi }{3}\right)
$$
Comment: If you want to modify the problem, this should appear as an edit to the original question (or as a new question altogether).


How to prove continuity of the retraction map in proof of Brouwer's fixed point theorem?

Question: I was reading Allen Hatcher's proof of the Brouwer's fixed point theorem using the no retraction theorem. That is, we want to prove that every continuous $f: \mathbb{D}^n \to \mathbb{D}^n$ has a fixed point $f(x) = x$, by contradiction.
The no retraction theorem says there is no continuous $r: \mathbb{S}^{n-1} \to \mathbb{D}^n$ such that $r \mid_{\mathbb{S}^{n-1}}(y) = y$. i.e. $r$ restricted to $\mathbb{S}^{n-1}$ is the identity functon.
Suppose a continuous $f$ exists with no fixed point. Then, define $r(x)$ by the point on the line $tx + (1-t)f(x)$ intersecting $\mathbb{S}^{n-1}$. The book, and lecture notes that I looked up, say this is clearly continuous.
Question: How do we proof that $r(x)$ is continuous?
Comment: @AymanHourieh - this IS an exact duplicate. Thanks for finding that question!
Answer: You could try the following: Take the function
$$g(t,x) = |tx+(1-t)f(x)|$$
and apply the implicit function theorem to get a continuous $t(x)$ with
$$g(t(x),x) = 1.$$
Then
$$r(x) = t(x) x + (1-t(x))f(x)$$
clearly is continuous since it is constructed from continuous functions.
Comment: Nice! Too bad the question is about to be deleted.
Comment: @JeanValjean It won't be deleted. Closing only prevents new answers from being added.
Comment: Remarkably elegant *hat tip*
Answer: One way is by showing that : i ) Multiplication is a continuous function  ii)so is sum, i.e., they are both continuous functions $\mathbb R \times \mathbb R \rightarrow \mathbb R$. And iii) The sum of continuous functions is continuous. Then $r(t)$ is a sum of the continuous functions $tx$ and $(1-t)f(x)$. If you want to make sure that the restriction to $S^{n-1}$ is continuous, you can either just say that a continuous function in a space restricts to a continuous function in a subspace, or you can divide $r(t)$ by the (continuous )norm function.


SQL select query with multiple conditions issue

Question: I have a problem with a SQL select query, I can't figure out what it needs to be.
This is what my items table look like:
| id |   i_id   |      last_seen       |   spot    |
----------------------------------------------------
| 1  |   ls100  | 2017-03-10 15:30:40  |  spot800  |
| 2  |   ls100  | 2017-03-10 16:20:15  |  spot753  |
| 3  |   ls200  | 2017-03-10 16:33:10  |  spot800  |
| 4  |   ls300  | 2017-03-10 15:30:40  |  spot800  |
| 5  |   ls300  | 2017-03-10 12:10:30  |  spot800  |
| 6  |   ls400  | 2017-03-10 10:30:10  |  spot800  |

This is what I'm trying to obtain:
 | id |   i_id   |      last_seen       |   spot    |
 ----------------------------------------------------
 | 3  |   ls200  | 2017-03-10 16:33:10  |  spot800  |
 | 5  |   ls300  | 2017-03-10 12:10:30  |  spot800  |

So I need to have the rows where spot= 'spot800', last_seen = MAX(but only if the DateTime is the newest compared to all spots with the samei_id`), and at last the DateTime must be bigger than '2017-03-10 11:00:00'.
This is what I have so far:
SELECT *
  FROM items
 WHERE spot = 'spot800'
HAVING MAX(`last_seen`)
   AND `last_seen` > '2017-03-10 11:00:00'

Comment: You forgot grouping by i_id
Comment: whether your query returning any records?
Answer: E.g.:
DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,i_id   INT NOT NULL
,last_seen       DATETIME NOT NULL
,spot    INT NOT NULL
);

INSERT INTO my_table VALUES
(1,100,'2017-03-10 15:30:40',800),
(2,100,'2017-03-10 14:20:15',753),
(3,200,'2017-03-10 16:33:10',800),
(4,300,'2017-03-10 15:30:40',800),
(5,300,'2017-03-10 12:10:30',800),
(6,400,'2017-03-10 10:30:10',800);

    SELECT [DISTINCT] x.*
      FROM my_table x
      LEFT
      JOIN my_table y
        ON y.i_id = x.i_id
       AND y.last_seen < x.last_seen
     WHERE x.last_seen > '2017-03-10 11:00:00'
       AND x.spot = 800
       AND y.id IS NULL;
----+------+---------------------+------+
| id | i_id | last_seen           | spot |
+----+------+---------------------+------+
|  3 |  200 | 2017-03-10 16:33:10 |  800 |
|  5 |  300 | 2017-03-10 12:10:30 |  800 |
+----+------+---------------------+------+
2 rows in set (0.00 sec)

Comment: I still get id 1 returned and this one shouldn't be returned because its date is  older than that from id 2
Comment: Also the date in row 2 should be '2017-03-10 16:20:15'
Comment: @SerAkd You're welcome. You wanted rows with ids 3 & 5. It makes no sense (to me) to return a time and id that don't correspond.
Comment: Indeed I wanted those rows, but when I execute the query it also returns id 1?
Comment: Plainly, that's not true. See above.
Comment: I don't do pictures, sorry. See rextester or sqlfiddle.
Comment: It is a screenshot from this query:
SELECT DISTINCT x.*
FROM `items` x
LEFT
JOIN `items` y
ON y.i_id = x.i_id
AND y.last_seen < x.last_seen
WHERE x.last_seen > '2017-03-10 11:00:00'
AND x.spot = 'spot800'
AND y.id IS NULL
And the result
Comment: I cannot replicate the finding, which is why I say provide a rextest or fiddle.
Comment: I think it works..THANKS! Had to switch the y.last_seen with x.last_seen in the line: y.last_seen > x.last_seen
Answer: Use MAX and GROUP BY.
SELECT id, i_id, MAX(last_seen), spot
FROM items
WHERE spot = 'spot800'
AND last_seen > '2017-03-10 11:00:00'
GROUP BY id, i_id, spot

Comment: because that matches your logic, id 1 is returned because it is the MAX last_seen for the ls100s
Comment: My apologies, I forgot to edit it, id 1 shouldn't be the MAX last_seen
Comment: If i use : GROUP BY `i_id` instead of GROUP BY `id`, `i_id`, `spot` then it returns the rows with id 1,3 and 5
Answer: There is several things wrng with your statement.
Firstly, HAVING must be accompanied with a GROUP BY clause, so it's not what you are looking for.
Also, MAX is an aggregate, not a boolean, function. That is, it cannot be used in filters, such as a where clause or a having clause. Also, if it did work, MAX would only return the entry that contains the time as '2017-03-10 16:33:10'. Not what you expected.
Try this instead:
SELECT * FROM items WHERE (spot='spot800' AND last_seen > '2017-03-10 11:00:00');

Comment: HAVING doesn't have to follow a GROUP BY clause - although that is its primary purpose. And your solution is incomplete, but otherwise, good.
Comment: This query returns the rows with id 1,3,4,5 and it only needs to return the rows with id 3 and 5


Playing video streams - smoothstream / playready / hasplayer.js

Question: I am trying to play a source encoded in microsoft smoothstream and encrypted with playready using the hasplayer.js.
I can get a microsoft test stream to play but when I try to use my encrypted stream the player just sits there showing the dots for loading and does not return an error or show any video or audio.
My javascript function.
<code>(function () {
    console.log("Setting video url");

    var onError = function (e) {
        console.error("ERROR: " + JSON.stringify(e));
    };
    // Microsoft sample stream
    //var url = "http://playready.directtaps.net/smoothstreaming/SSWSS720H264/SuperSpeedway_720.ism/Manifest";

    // my  test stream smoothstream & playready
    var url = "http://stream.abcdef.net/stream/file/hd/smooth/file_encrypted.ism/manifest";

    var context = new MediaPlayer.di.Context();
    var player = new MediaPlayer(context);
    player.startup();
    player.attachView(document.querySelector("#videoPlayer"));
    player.addEventListener("error", onError);
    player.attachSource(url);
})();
</code>
Comment: Should have added that i know the stream is good as it plays in the silverlight demo at http://playready.directtaps.net/pr/doc/slee/.
Answer: After using the hasplayer debug and contacting the hasplayer team. it was found that our stream had a box type that was unknown to the hasplayer and this caused an error.
The hasplayer team are looking at a fix and we are looking at our stream generation.


How do I run a Sinatra app as a deamon from the command line?

Question: How do I run a Sinatra app as a deamon from the command line?
It is using Thin:
ruby app.rb -p 3000 -e production

I don't like to set it up in the app.rb itself. I want to deamonise it from the command line.
Answer: From Start Sinatra app in the background with stdout and stderr redirected (append) to a file:
nohup ruby app.rb -p 3000 -e production >> log/log_file 2>&1 &

Answer: I don't know if it's possible with Ruby. But it's an easy task with rackup.
Just add a config.ru:
require './app'
run Sinatra::Application

And with this in place you can start it as a daemon:
rackup -p 3000 -E production -D

Comment: *Tried n true™* with a few small sinatra 2.0 apps on my VPS. It works out of the box and let rack handle the webserver: i use (oh God i'm saying it publicly) *webrick* and the method above for any small app i deploy (capistrano).


When is unsafeInterleaveIO unsafe?

Question: Unlike other unsafe* operations, the documentation for unsafeInterleaveIO is not very clear about its possible pitfalls. So exactly when is it unsafe? I would like to know the condition for both parallel/concurrent and the single threaded usage.
More specifically, are the two functions in the following code semantically equivalent? If not, when and how?

joinIO :: IO a -> (a -> IO b) -> IO b
joinIO  a f = do !x  <- a
                    !x'  <- f x
                    return x'

joinIO':: IO a -> (a -> IO b) -> IO b
joinIO' a f = do !x  <- unsafeInterleaveIO a
                    !x' <- unsafeInterleaveIO $ f x
                    return x'

Here's how I would use this in practice:

data LIO a = LIO {runLIO :: IO a}

instance Functor LIO where
  fmap f (LIO a) = LIO (fmap f a)

instance Monad LIO where
  return x = LIO $ return x
  a >>= f  = LIO $ lazily a >>= lazily . f
    where
      lazily = unsafeInterleaveIO . runLIO

iterateLIO :: (a -> LIO a) -> a -> LIO [a]
iterateLIO f x = do
  x' <- f x
  xs <- iterateLIO f x'  -- IO monad would diverge here
  return $ x:xs

limitLIO :: (a -> LIO a) -> a -> (a -> a -> Bool) -> LIO a
limitLIO f a converged = do
  xs <- iterateLIO f a
  return . snd . head . filter (uncurry converged) $ zip xs (tail xs)

root2 = runLIO $ limitLIO newtonLIO 1 converged
  where
    newtonLIO x = do () <- LIO $ print x
                           LIO $ print "lazy io"
                           return $ x - f x / f' x
    f  x = x^2 -2
    f' x = 2 * x
    converged x x' = abs (x-x') < 1E-15

Although I would rather avoid using this code in serious applications because of the terrifying unsafe* stuff, I could at least be lazier than would be possible with the stricter IO monad in deciding what 'convergence' means, leading to (what I think is) more idiomatic Haskell. And this brings up another question:why is it not the default semantics for Haskell's (or GHC's?) IO monad? I've heard some resource management issues for lazy IO (which GHC only provides by a small fixed set of commands), but the examples typically given somewhat resemble like a broken makefile:a resource X depends on a resource Y, but if you fail to specify the dependency, you get an undefined status for X. Is lazy IO really the culprit for this problem? (On the other hand, if there is a subtle concurrency bug in the above code such as deadlocks I would take it as a more fundamental problem.)
Update
Reading Ben's and Dietrich's answer and his comments below, I have briefly browsed the ghc source code to see how the IO monad is implemented in GHC. Here I summerize my few findings.

GHC implements Haskell as an impure, non-referentially-transparent language. GHC's runtime operates by successively evaluating impure functions with side effects just like any other functional languages. This is why the evaluation order matters.
unsafeInterleaveIO is unsafe because it can introduce any kind of concurrency bugs even in a sigle-threaded program by exposing the (usually) hidden impurity of GHC's Haskell. (iteratee seems to be a nice and elegant solution for this, and I will certainly learn how to use it.)
the IO monad must be strict because a safe, lazy IO monad would require a precise (lifted) representation of the RealWorld, which seems impossible.
It's not just the IO monad and unsafe functions that are unsafe. The whole Haskell (as implemented by GHC) is potentially unsafe, and 'pure' functions in (GHC's) Haskell are only pure by convention and the people's goodwill. Types can never be a proof for purity.

To see this, I demonstrate how GHC's Haskell is not referentially transparent regardless of the IO monad, regardless of the unsafe* functions,etc.

-- An evil example of a function whose result depends on a particular
-- evaluation order without reference to unsafe* functions  or even
-- the IO monad.

{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE BangPatterns #-}
import GHC.Prim

f :: Int -> Int
f x = let v = myVar 1
          -- removing the strictness in the following changes the result
          !x' = h v x
      in g v x'

g :: MutVar# RealWorld Int -> Int -> Int
g v x = let !y = addMyVar v 1
        in x * y

h :: MutVar# RealWorld Int -> Int -> Int
h v x = let !y = readMyVar v
        in x + y

myVar :: Int -> MutVar# (RealWorld) Int
myVar x =
    case newMutVar# x realWorld# of
         (# _ , v #) -> v

readMyVar :: MutVar# (RealWorld) Int -> Int
readMyVar v =
    case readMutVar# v realWorld# of
         (# _ , x #) -> x

addMyVar :: MutVar# (RealWorld) Int -> Int -> Int
addMyVar v x =
  case readMutVar# v realWorld# of
    (# s , y #) ->
      case writeMutVar# v (x+y) s of
        s' -> x + y

main =  print $ f 1

Just for easy reference, I collected some of the relevant definitions
for the IO monad as implemented by GHC.
(All the paths below are relative to the top directory of the ghc's source repository.)

--  Firstly, according to "libraries/base/GHC/IO.hs",
{-
The IO Monad is just an instance of the ST monad, where the state is
the real world.  We use the exception mechanism (in GHC.Exception) to
implement IO exceptions.
...
-}

-- And indeed in "libraries/ghc-prim/GHC/Types.hs", We have
newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))

-- And in "libraries/base/GHC/Base.lhs", we have the Monad instance for IO:
data RealWorld
instance  Functor IO where
   fmap f x = x >>= (return . f)

instance  Monad IO  where
    m >> k    = m >>= \ _ -> k
    return    = returnIO
    (>>=)     = bindIO
    fail s    = failIO s

returnIO :: a -> IO a
returnIO x = IO $ \ s -> (# s, x #)

bindIO :: IO a -> (a -> IO b) -> IO b
bindIO (IO m) k = IO $ \ s -> case m s of (# new_s, a #) -> unIO (k a) new_s

unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
unIO (IO a) = a

-- Many of the unsafe* functions are defined in "libraries/base/GHC/IO.hs":
unsafePerformIO :: IO a -> a
unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)

unsafeDupablePerformIO  :: IO a -> a
unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)

unsafeInterleaveIO :: IO a -> IO a
unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)

unsafeDupableInterleaveIO :: IO a -> IO a
unsafeDupableInterleaveIO (IO m)
  = IO ( \ s -> let
                   r = case m s of (# _, res #) -> res
                in
                (# s, r #))

noDuplicate :: IO ()
noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)

-- The auto-generated file "libraries/ghc-prim/dist-install/build/autogen/GHC/Prim.hs"
-- list types of all the primitive impure functions. For example,
data MutVar# s a
data State# s

newMutVar# :: a -> State# s -> (# State# s,MutVar# s a #)
-- The actual implementations are found in "rts/PrimOps.cmm".

So, for example, ignoring the constructor and assuming referential transparency,
we have

unsafeDupableInterleaveIO m >>= f
==>  (let u = unsafeDupableInterleaveIO)
u m >>= f
==> (definition of (>>=) and ignore the constructor)
\s -> case u m s of
        (# s',a' #) -> f a' s'
==> (definition of u and let snd# x = case x of (# _,r #) -> r)
\s -> case (let r = snd# (m s)
            in (# s,r #)
           ) of
       (# s',a' #) -> f a' s'
==>
\s -> let r = snd# (m s)
      in
        case (# s,  r  #) of
             (# s', a' #) -> f a' s'
==>
\s -> f (snd# (m s)) s

This is not what we would normally get from binding usual lazy state monads.
Assuming the state variable s carries some real meaning (which it does not), it looks more like a concurrent IO (or interleaved IO as the function rightly says) than a lazy IO as we would normally mean by 'lazy state monad' wherein despite the laziness the states are properly threaded by an associative operation.
I tried to implement a truely lazy IO monad, but soon realized that in order to define a lazy monadic composition for the IO datatype, we need to be able to lift/unlift the RealWorld. However this seems impossible because there is no constructor for both State# s and RealWorld. And even if that were possible, I would then have to represent the precise, functional represenation of our RealWorld which is impossible,too.
But I'm still not sure whether the standard Haskell 2010 breaks referential transparency or the lazy IO is bad in itself. At least it seems entirely possible to build a small model of the RealWorld on which the lazy IO is perfectly safe and predictable. And there might be a good enough approximation that serves many practical purposes without breaking the referential transparency.
Comment: Here's a relevant message from `haskell-cafe`: http://www.haskell.org/pipermail/haskell-cafe/2009-March/057802.html
Answer: At the top, the two functions you have are always identical.
v1 = do !a <- x
        y

v2 = do !a <- unsafeInterleaveIO x
        y

Remember that unsafeInterleaveIO defers the IO operation until its result is forced -- yet you are forcing it immediately by using a strict pattern match !a, so the operation is not deferred at all.  So v1 and v2 are exactly the same.
In general
In general, it is up to you to prove that your use of unsafeInterleaveIO is safe.  If you call unsafeInterleaveIO x, then you have to prove that x can be called at any time and still produce the same output.
Modern sentiment about Lazy IO
...is that Lazy IO is dangerous and a bad idea 99% of the time.
The chief problem that it is trying to solve is that IO has to be done in the IO monad, but you want to be able to do incremental IO and you don't want to rewrite all of your pure functions to call IO callbacks to get more data.  Incremental IO is important because it uses less memory, allowing you to operate on data sets that don't fit in memory without changing your algorithms too much.
Lazy IO's solution is to do IO outside of the IO monad.  This is not generally safe.
Today, people are solving the problem of incremental IO in different ways by using libraries like Conduit or Pipes.  Conduit and Pipes are much more deterministic and well-behaved than Lazy IO, solve the same problems, and do not require unsafe constructs.
Remember that unsafeInterleaveIO is really just unsafePerformIO with a different type.
Example
Here is an example of a program that is broken due to lazy IO:
rot13 :: Char -> Char
rot13 x
  | (x >= 'a' && x <= 'm') || (x >= 'A' && x <= 'M') = toEnum (fromEnum x + 13)
  | (x >= 'n' && x <= 'z') || (x >= 'N' && x <= 'Z') = toEnum (fromEnum x - 13)
  | otherwise = x

rot13file :: FilePath -> IO ()
rot13file path = do
  x <- readFile path
  let y = map rot13 x
  writeFile path y

main = rot13file "test.txt"

This program will not work.  Replacing the lazy IO with strict IO will make it work.
Links
From Lazy IO breaks purity by Oleg Kiselyov on the Haskell mailing list:

We demonstrate how lazy IO breaks referential transparency.  A pure
  function of the type Int->Int->Int gives different integers depending
  on the order of evaluation of its arguments. Our Haskell98 code uses
  nothing but the standard input.  We conclude that extolling the purity
  of Haskell and advertising lazy IO is inconsistent.
...
Lazy IO should not be considered good style. One of the common
  definitions of purity is that pure expressions should evaluate to the
  same results regardless of evaluation order, or that equals can be
  substituted for equals. If an expression of the type Int evaluates to
  1, we should be able to replace every occurrence of the expression with
  1 without changing the results and other observables.

From Lazy vs correct IO by Oleg Kiselyov on the Haskell mailing list:

After all, what could be more against
  the spirit of Haskell than a `pure' function with observable side
  effects. With Lazy IO, one indeed has to choose between correctness
  and performance. The appearance of such code is especially strange
  after the evidence of deadlocks with Lazy IO, presented on this list
  less than a month ago. Let alone unpredictable resource usage and
  reliance on finalizers to close files (forgetting that GHC does not
  guarantee that finalizers will be run at all).

Kiselyov wrote the Iteratee library, which was the first real alternative to lazy IO.
Comment: I use lazy IO in 90% of all my code, and it works just fine.  It all depends on your use case.
Comment: My rule of thumb for lazy `IO` is just to imagine that every lazy `IO` function is prefixed with an `unsafe` and program accordingly.
Comment: How so? `unsafeInterleaveIO x` has type `IO a` and should be able to produce different results (e.g. the current time of the evaluation).
Comment: "How so?"  I'm sorry, but please be more specific, or use quotes.  I don't know what part of what you're talking about.
Comment: Sorry, I mean this part:"then you have to prove that x can be called at any time and still produce the same output."
Comment: When you call `getTime :: IO Time` or whatever, that's fine because it's in the IO monad and you get the current time.  But when you use `unsafeInterleaveIO getTime :: IO Time` it *looks* like it does the same thing -- get the current time -- but it doesn't.  It gets the time when the result is forced.  This is surprising.
Comment: Also, I could argue with your statement "Lazy IO's solution is to do IO outside of the IO monad". My naive view is that lazy IO doesn't do any IO outside of the IO monad. They just sometimes help the programmer to perform pure computation on *undefined values* in the sense I implied in the question (namely the failure to specify the precise dependency under which the computed value is well-defined.) What is the modern view on this?
Comment: Could you define the term "undefined value"?  It has no technical meaning in Haskell that I am aware of...
Comment: @mnish: I don't know where you got the idea that lazy IO doesn't do any IO outside of the IO monad.  The entire purpose of `unsafeInterleaveIO` is to defer an IO computation so it is executed outside the IO monad -- in other words, doing IO outside of the IO monad is exactly what characterizes lazy IO.
Comment: Could you wait a minute please? I remember I've recently read Oleg Kiselyov's argument and his examples about this somewhere..
Comment: @mnish: I've posted some of Kiselyov's writings about lazy IO in the body of the answer.
Comment: Ok I've read it throught a stackoverflow link! 'http://firstname.lastname@example.com/msg21782.html'. In the example given there, both `s1` and `s2` are what I mean `undefined values`. They are the results of `hGetContents` for some handles,but their value really depends on the order of read operation,the seek position at the moment of evaluation,etc. In a makefile I would write those dependencies as `s2: s1 h1 h2` or something like that. What I'm asking is, is the lazy-IO (or any evaluation order) the culprit for those undefined-ness of the values?
Comment: Isn't some kind of partial ordering of resource dependencies enough (as in make)? If so, evaluation order per se seems to be irrelevant.
Comment: @mnish: In Haskell, the result of a computation is not supposed to depend on evaluation order.  Evaluation order is indeterminate, and it's okay.  If you use lazy IO, then suddenly you've broken that -- your program depends on evaluation order.  So `s1` and `s2` get the wrong results.  It is the fault of Lazy IO for producing values which depend on evaluation order.
Comment: Well, the error message from your examples speaks the problem itself:"openFile: resource busy (file is locked)". The value of `x` really depends on the closing of the file because there might be some nasty kernel driver that tries to append some gibberish to the file.
Comment: @mnish: That's not quite correct -- the value of `x` is actually not the problem.  The problem is that the evaluation of `x` causes an IO action to occur -- closing the file -- which should not occur, since `x` is not in the `IO` monad.  Since the file is closed at an indeterminate time, it ends up happening *after* the program tries to open the file for writing.
Comment: Dietrich, what I'm arguing is this:isn't the dependency of resources independent of the evaluation order? If some set of augmented IO actions allow me to more precisely specify the conditions the IO actions give valid results (by types), then wouldn't lazy IO compute the perfectly valid, predictable values (again as in make)?  But reading your comments, it looks like I need to understand how IO monad is implemented in ghc.
Comment: Thank you Dietrich, and I'm sorry I think I need a bit of time to understand and accept your answer.
Comment: @mnish: I'm not trying to argue that Lazy IO is never safe here.  But this isn't simple like makefile dependencies.  `s1` does not depend on `s2`, instead, their values both depend on IO state.  It's possible to use lazy IO in a relatively safe manner but it is difficult, and the type system will not help you do it.  Sometimes Lazy IO is good enough and works, but sometimes it will really surprise you so you might want to learn iteratees or conduit or one of the alternatives.  Unlike lazy IO, iteratees and conduit are known to be safe.
Comment: @Dietrich: Thank you for your comments, I think I have a better understanding how Haskell code is run by GHC. But I wonder, how about other implementations? Is there a more 'purer' approach to IO than GHC?
Answer: Laziness means that when (and whether) exactly a computation is actually carried out depends on when (and whether) the runtime implementation decides it needs the value. As a Haskell programmer you completely relinquish control over the evaluation order (except by the data dependencies inherent in your code, and when you start playing with strictness to force the runtime to make certain choices).
That's great for pure computations, because the result of a pure computation will be exactly the same whenever you do it (except that if you carry out computations that you don't actually need, you might encounter errors or fail to terminate, when another evaluation order might allow the program to terminate successfully; but all non-bottom values computed by any evaluation order will be the same).
But when you're writing IO-dependent code, evaluation order matters. The whole point of IO is to provide a mechanism for building computations whose steps depend on and affect the world outside the program, and an important part of doing that is that those steps are explicitly sequenced. Using unsafeInterleaveIO throws away that explicit sequencing, and relinquishes control of when (and whether) the IO operation is actually carried out to the runtime system.
This is unsafe in general for IO operations, because there may be dependencies between their side-effects which cannot be inferred from the data dependencies inside the program. For example, one IO action might create a file with some data in it, and another IO action might read the same file. If they're both executed "lazily", then they'll only get run when the resulting Haskell value is needed. Creating the file is probably IO () though, and it's quite possible that the () is never needed. That could mean that the read operation is carried out first, either failing or reading data that was already in the file, but not the data that should have been put there by the other operation. There's no guarantee that the runtime system will execute them in the right order. To program correctly with a system that always did this for IO you'd have to be able to accurately predict the order in which the Haskell runtime will choose to perform the various IO actions.
Treat unsafeInterlaveIO as promise to the compiler (which it cannot verify, it's just going to trust you) that it doesn't matter when the IO action is carried out, or whether it's elided entirely. This is really what all the unsafe* functions are; they provide facilities that are not safe in general, and for which safety cannot be automatically checked, but which can be safe in particular instances. The onus is on you to ensure that your use of them is in fact safe. But if you make a promise to the compiler, and your promise is false, then unpleasant bugs can be the result. The "unsafe" in the name is to scare you into thinking about your particular case and deciding whether you really can make the promise to the compiler.
Comment: `unsafeInterleaveIO (a >>= b) >>= c` does preserve the explicit sequencing between a and b but not between b and c.
Comment: I can now confirm that you are perfectly right. The point is that unlike the usual state monad where there is a functional relations between states, the 'state' in the IO monad (which is represented as `State# RealWorld`) is actually threaded by _evaluation_, not by any functional relation.
Answer: Basically everything under "Update" in the question is so confused it's not even wrong, so please try to forget it when you're trying to understand my answer.
Look at this function:
badLazyReadlines :: Handle -> IO [String]
badLazyReadlines h = do
  l <- unsafeInterleaveIO $ hGetLine h
  r <- unsafeInterleaveIO $ badLazyReadlines h
  return (l:r)

In addition to what I'm trying to illustrate: the above function also doesn't handle reaching the end of the file. But ignore that for now.
main = do
  h <- openFile "example.txt" ReadMode
  lns <- badLazyReadlines h
  putStrLn $ lns ! 4

This will print the first line of "example.txt", because the 5th element in the list is actually the first line that's read from the file.
Comment: I assume the solution to this would be to remove both `unsafeInterleaveIO` and move them to the beginning of the function, so we get `goodLazyReadLines h = unsafeInterleaveIO $ do { l <- hGetLine h; r <- goodLazyReadLines h; return (l:r)}`? This way traversing the list will also force each element so far in the list.
Answer: Your joinIO and joinIO' are not semantically equivalent. They will usually be the same, but there's a subtlety involved: a bang pattern makes a value strict, but that's all it does. Bang patterns are implemented using seq, and that does not enforce a particular evaluation order, in particular the following two are semantically equivalent:
a `seq` b `seq` c
b `seq` a `seq` c

GHC can evaluate either b or a first before returning c. Indeed, it can evaluate c first, then a and b, then return c. Or, if it can statically prove a or b are non-bottom, or that c is bottom, it doesn't have to evaluate a or b at all. Some optimisations do genuinely make use of this fact, but it doesn't come up very often in practice.
unsafeInterleaveIO, by contrast, is sensitive to all or any of those changes – it does not depend on the semantic property of how strict some function is, but the operational property of when something is evaluated. So all of the above transformations are visible to it, which is why it's only reasonable to view unsafeInterleaveIO as performing its IO non-deterministically, more or less whenever it feels appropriate.
This is, in essence, why unsafeInterleaveIO is unsafe - it is the only mechanism in normal use that can detect transformations that ought to be meaning-preserving. It's the only way you can detect evaluation, which by rights ought to be impossible.
As an aside, it's probably fair to mentally prepend unsafe to every function from GHC.Prim, and probably several other GHC. modules as well. They're certainly not ordinary Haskell.
Comment: I know I'm a couple years late, but bang patterns are *not* implemented using `seq`; in fact, the reverse is true. Bang patterns are translated to `case` forms in GHC Core, and `case` in Core is always strict. For instance, `let !x = foo in bar` will be translated directly to something like `case foo of x {DEFAULT -> bar}`.
Comment: @mnish: it's sort of a matter of perspective what you think of as part of Haskell and what isn't. I think it's reasonable to say that the GHC-internal modules are implementation details and not part of the language – in some sense they are non-Haskell code, but written with Haskell syntax and compiled with a Haskell compiler. The semantics are perfectly okay regardless of little secrets: if you declare any secret-leaking as outside the language, then inside the language, the semantics hold.
Comment: I know I'm still a noob and naive, but I can't resist to say this: those 'semantically' things only make sense
for a pure, referentially transparent language in which the Church-Rosser holds, which (GHC's) Haskell is not.
`unsafe*` are unsafe only because they leak this little secret, not by their inherent nature. Why don't they implement the `IO` as a primitive, and primitive functions as `IO a`?
Comment: But @Ben, the problems is that the unsafety can be viral --- the correctness of the whole calculus can be broken by some innocent-looking operations down below. Who knows that the standard 'lazy IO' functions never break the operational semantics of GHC?
Comment: Well... if they do, it's a bug, just like it would be a bug if any other aspect of GHC's implementation of the semantics was incorrect. I don't see what you mean by implementing the `IO` as a primitive - it *is* primitive, but it's just a primitive written in the "pseudo-Haskell" that all the GHC.* modules are written. (and which functions are "primitive functions?")
Comment: @dfeuer: acknowledged, thanks. I'm not particularly fond of this answer so I'm not going to bother fixing it, but you are welcome to if you like.

When is unsafeInterleaveIO unsafe?