Given $(a_n)$ such that $a_1 \in (0,1)$ and $a_{n+1}=a_n+(\frac{a_n}{n})^2$. Prove that $(a_n)$ has a finite limit.

Question: Given $(a_n)$ such that $a_1 \in (0,1)$ and $a_{n+1}=a_n+(\frac{a_n}{n})^2$. Prove that $(a_n)$ has a finite limit.
Clearly $a_n$ are increasing. Also, $$\frac{1}{a_{n+1}}=\frac{1}{a_n\left(1+\frac{a_n}{n^2}\right)}=\frac{1}{a_n}-\frac{\frac{1}{n^2}}{1+\frac{a_n}{n^2}}$$
From this how to proceed further? Any idea will be appreciated
Comment: Bound this expression from above, and you will get a bounded increasing sequence which always has a finite limit. Use the fact this is an increasing sequence to obtain an upper bound
Comment: $y'=\left(\frac yx \right)^2$ is separable giving $y = \frac{x}{1+ c x}$...
Answer: EDIT. I realized that this problem has been solved (even by myself) several times in the past; see the links above. A bound of the form
$$ \frac{x}{1-x} \leq \lim a_n \leq \frac{x}{1-\sqrt{x}} $$
is also proved there.

Let $x = a_1 \in (0, 1)$.

Claim 1. We have $a_n \leq nx$ for all $n \geq 1$.

Indeed, the base case ($n=1$) is trivial. Next, if $ a_n \leq nx$, then
$$ a_{n+1} \leq nx + \left( \frac{nx}{n} \right)^2 = nx + x^2 \leq (n+1) x. $$
So by the mathematical induction, the claim follows.

Claim 2. We have $a_n \leq Cn^x$ for some constant $C = C(x) \in (0, \infty)$.

Indeed,
$$ a_{n+1}
= a_n \left( 1 + \frac{a_n}{n^2} \right)
\leq a_n \left( 1 + \frac{x}{n} \right)
\leq a_n e^{\frac{x}{n}} $$
where we utilized the inequality $1 + t \leq e^t$ in the last step. From this, we get
$$ a_n \leq x e^{x H_{n-1}}, $$
where $H_n = \sum_{k=1}^{n} \frac{1}{k}$ is the harmonic number. Then using $H_n = \log n + \mathcal{O}(1)$, the desired claim follows. (In fact, using the inequality $H_{n-1} \leq 1+ \log n$, we may choose $C = x e^{x}$.)

Claim 3. $(a_n)$ converges.

Let $C$ be the constant as in the previous claim. Then
$$ a_{n+1}
= a_n \left( 1 + \frac{a_n}{n^2} \right)
\leq a_n \left( 1 + \frac{C}{n^{2-x}} \right)
\leq a_n \exp\left(\frac{C}{n^{2-x}}\right), $$
and so,
$$ a_n \leq x \exp\left( \sum_{k=1}^{n-1} \frac{C}{k^{2-x}} \right) \leq x e^{C \zeta(2-x)}.  $$
This proves that $(a_n)$ is bounded. Since $(a_n)$ is increasing, we conclude that $(a_n)$ converges.

Addendum. A numerical simulation suggests that $a_{\infty}$ as a function of $x = a_1$ satisfies
$$ a_{\infty}(x) \leq \frac{2x}{1-x} $$
for all $x \in (0, 1)$, although I could not prove this. On the other hand, we can obtain a lower bound of the same order via relatively simple argument:
Argument 1. From the recurrence relation and Claim 1,
\begin{align*}
\frac{1}{x} - \frac{1}{a_{\infty}(x)}
= \sum_{n=1}^{\infty} \frac{1}{n^2 + a_n(x)}
\geq \sum_{n=1}^{\infty} \frac{1}{n^2 + nx}
= \sum_{n=1}^{\infty} \frac{1}{x} \left( \frac{1}{n} - \frac{1}{n+x} \right)
= \frac{H_x}{x},
\end{align*}
where $H_x = \int_{0}^{1} \frac{1-t^x}{1-t} \, \mathrm{d}t$ is the harmonic number. Rearranging,
$$ a_{\infty}(x) \geq \frac{x}{1 - H_x} \sim \frac{1}{1-x} \quad \text{as} \quad x \to 1^-. $$
Argument 2. By the principle of mathematical induction, it is easy to show that
$$ a_n \geq x + x^2 + \cdots + x^n = x \cdot \frac{1-x^n}{1-x}. $$
Indeed, the claim is trivial for $n = 1$, and if it is true for $n$, then by the AM-GM inequality, $a_n \geq n x^{(n+1)/2}$, and so,
\begin{align*}
a_{n+1}
&\geq (x + x^2 + \cdots + x^n) + \left( \frac{nx^{(n+1)/2}}{n} \right)^2 \\
&= x + x^2 + \cdots + x^n + x^{n+1}.
\end{align*}
This establishes the inductive step and hence proves the desired claim.


Falha de download ao tentar atualizar plugins no Wordpress

Question: Fiz a instalação do Wordpress localmente, instalei alguns plugins e agora estou tentando atualizar as traduções. O que acontece é que ele não atualiza.
Obs: uso EasyPHP e WP 4.6.1
Ele exibe a seguinte mensagem:

Falha no download. No working transports found
Comment: EasyPHP não é servidor é apenas um gerenciador/facilitador, ele tecnicamente não faz nada além de instalar o Apache, PHP e mysql de forma mais simples na sua máquina, recomendo que leia isto para entender a diferença primeiro http://pt.stackoverflow.com/q/115689/3635.
Answer: O Wordpress usa as extensões Curl e Openssl para fazer download dos plugins, no caso as extensões estavam desativadas assim:
Se for windows:
;extension=php_curl.dll
;extension=php_openssl.dll

Se for like-unix (por exemplo linux, mac osx, bsd):
;extension=curl.so
;extension=openssl.so

A extensão Curl serve para acessar páginas via HTTP e a extensão Openssl serve para acessar que o Curl consiga acessar páginas HTTPS, os plugins do Wordpress estão em nos servidores/repositórios do Wordpress e estão sob o protocolo https://, para que o PHP consiga baixar é necessário ter ambas extensões ativadas, para isto basta remover o ponto-e-virgula (;) da frente e reiniciar o Apache em seguida.
Se for Windows deixe assim:
extension=php_curl.dll
extension=php_openssl.dll

Se for like-unix (linux, mac osx, bsd):
extension=curl.so
extension=openssl.so

Lembre-se, para que tenha efeito deve reiniciar o Apache (ou Nginx)

Como reiniciar o Apache/Nginx
Se for Windows e Mac vai depender muito de com instalou, se foi manualmente ou se foi com pacotes prontos e se ele foi instalado como serviço ou não
Para reiniciar o Apache no Linux:

Geralmente Red Hat:
sudo service apache2 restart

No Suse:
sudo systemctl restart apache2.service

Outras distros:
sudo restart apache2

ou:
sudo apache2 restart

Nota: Se o caminho do Apache não estiver Global talvez tenha que digitar assim /etc/init.d/apache2, mas depende de onde foi instalado

Reiniciar Nginx:

No Ubuntu geralmente:
sudo systemctl restart nginx

Outras distros:
sudo service nginx restart

ou:
sudo /etc/init.d/nginx restart

Comment: Excelente, funcionou perfeitamente, ficou bem claro a explicação, obrigado novamente ;D


vue3-google-map with Nuxt

Question: I've already used this vue3-google-map plugin in some Vue projects but now I'm working on a Nuxt project and I want to use this here as well. Is there any way to add it to Nuxt?
Here is the documentation:
Answer: From what I can find, this library doesn't support use as a global 'plugin' within Nuxt 3.
Most of the working examples I could find, and the approach we're using in our project, do the following:

Install the plugin within your Nuxt app using whichever package manager you use.
Skip adding the plugin in ~/plugins/
Import the map components within your components or templates using:

import { GoogleMap, Marker, etc } from 'vue3-google-map'
Note: The approach suggested by Jakub, whilst being valid for many such dependencies, did not work for us with vue3-google-map. Jabub's answer is a working method for fawmi/vue-google-maps which has been tweaked slightly from here
Answer: You should be able to use the vue3-google-map plugin in a Nuxt project.

Install the plugin with terminal:
npm install vue3-google-map

Create a new file called vue-google-maps.js in the plugins directory of your Nuxt project.

In the vue-google-maps.js file, import the vue3-google-map plugin and add it to the Nuxt plugins array:
import Vue from 'vue';
import VueGoogleMaps from 'vue3-google-maps';

Vue.use(VueGoogleMaps, {
  load: {
    key: 'YOUR_API_KEY',
    libraries: 'places',
  },
});

In your Nuxt configuration file (nuxt.config.js), add the vue-google-maps.js file to the plugins array:
export default {
  // ...
  plugins: [
    // ...
    '@/plugins/vue-google-maps',
  ],
  // ...
}

In your Vue component, you can now use the <GmapMap> component provided by the vue3-google-map plugin to display a Google Map.

vue3-google-map with Nuxt


Update order status on eBay using API?

Question: I get a list of orders using eBay getorder API, but now I want to select an order and update its status.
How can I do that?  Please, any help would be appreciated
I am using some code off the internet, and it shows "success" on changing the status.  But when I load the order list again (or if I use shipped=false in API) it's still "complete".
Code:
    //create the context
    ApiContext context = new ApiContext();

    //set the User token
    context.ApiCredential.eBayToken = "token";

    //set the server url
//    context.SoapApiServerUrl = "https://api.sandbox.ebay.com/wsapi";
    context.SoapApiServerUrl = "https://api.ebay.com/wsapi";

    //enable logging
    context.ApiLogManager = new ApiLogManager();
    context.ApiLogManager.ApiLoggerList.Add(new FileLogger("log.txt", true, true, true));
    context.ApiLogManager.EnableLogging = true;

    //set the version
    context.Version = "705";
    context.Site = SiteCodeType.UK;

    //Create the call and set the fields
    CompleteSaleCall apicall = new CompleteSaleCall(context);

    //Either ItemID-TransactionID or OrderLineItemID or OrderID is required. If item is part of an order, specify OrderID.
    apicall.OrderLineItemID = "123467585959-0";
    apicall.Shipped = true;

    //apicall.Shipment = new ShipmentType();
    //apicall.Shipment.ShipmentTrackingDetails = new ShipmentTrackingDetailsTypeCollection();

    //ShipmentTrackingDetailsType shpmnt = new ShipmentTrackingDetailsType();
    //shpmnt.ShipmentTrackingNumber = "VZ9478668";
    //shpmnt.ShippingCarrierUsed = "YourCarrier";

    //apicall.Shipment.ShipmentTrackingDetails.Add(shpmnt);

    //Specify time in GMT. This is an optional field
    //If you don't specify a value for the ShippedTime, it will be defaulted to the time at which the call was made
   // apicall.Shipment.ShippedTime = new DateTime(2011, 3, 5, 10, 0, 0).ToUniversalTime();

    //call the Execute method
    apicall.Execute();
    Console.WriteLine(apicall.ApiResponse.Ack);

Thank you
Comment: have you tried completeSale method of api?
Comment: hi yes, thank you i did it using the completessale method :).i can change order status to paid, and shipped in bulk now.But one thing why does still when i getorder usingapi the orderstatus = active? should it not change to shipped or paid etc?
Comment: it should return latest status. are you getting sccuess in response to completesale?
Answer: This should work: CompleteSale in Trading API
Comment: It's an old thread but I have a question, I want to change the status of order from `Complete` to my custom status `Confirmed`, can we do so? @zengr
Answer: For changing ebay order status from active to completed you can call "ReviseCheckoutStatus" API, it worked for me :)

Update order status on eBay using API?


Expected value using indicator variables

Question: Randomly, $k$ distinguishable balls are placed into $n$ distinguishable boxes, with
all possibilities equally likely. Find the expected number of empty boxes.
PROPOSED SOLUTION:
Let $I_j$ be the indicator random variable for the $j^{th}$ box being empty, so $I_1 + ··· + I_n$ is the number of empty boxes.
Now $E(I_j) = P(I_j = 1) $
Given both boxes AND balls are distinguishable total number of ways to place balls in boxes is $(n + k)!$
Now lets assume $j^{th}$ box is left empty, remaining $(n-1)$ boxes can be filled as $(k + n - 1)!$ ways
Therefore,  $I_j = \dfrac{(k + n -1)!}{(k + n)! }= E(I_j)$
By linearity of Expectation, $E(\sum_{k=1}^n[I_j]) = \sum_{k=1}^n(E(I_j))$
= $\sum_{k=1}^n(\dfrac{(k + n -1)!}{(k + n)!})$
= $\dfrac{n(k + n - 1)!}{(k + n)!}$
solution guide gives answer as $n(1 - 1/n)^k$ which is arrived at by saying $I_j = (1 - 1/n)^k$
Any insights in what is wrong above.
Comment: I edited some of your text, maybe you could take a look at how the changes are made and finish the editing yourself :-)
Comment: Thanks Math-fun. Made some edits and it is much more readable now :)
Answer: Imagine tossing the balls one at a time into bins. For each ball, there are $n$ equally likely places for it to land, for a total of $n^k$ equally likely cases. This is quite different from your $(n+k)!$.
For any fixed bin B, the probability any individual ball falls outside B is $\frac{n-1}{n}$. Thus the probability they all land outside B is $\left(\frac{n-1}{n}\right)^k$.
Comment: Thanks Andre. This is very helpful
Comment: You are welcome.


Make Excel Formula auto-add itself when new rows added

Question: I have added a User Form to an excel spreadsheet that asks a user a question and adds it to a new row in a spreadsheet.
Each column in the spreadsheet has its own formula that calculates based off user input.
Is there a way that I can have excel automatically "pull" the formula that is contiguous in the column into the added row?
I imagine that I can change it in the code for my User Form, so when a person hits "Submit" all the cells update. But I only know how to update the value, not add a formula in place. Here is part of the code I have:
    .Cells(iRow, 6).Value = Me.TextBox1.Value
    .Cells(iRow, 7).Value = Me.TextBox2.Value
    .Cells(iRow, 8).Value = Me.TextBox3.Value
    .Cells(iRow, 9).Value = Me.TextBox4.Value
    .Cells(iRow, 10).Value = Me.TextBox5.Value
    .Cells(iRow, 11).Value = Me.TextBox6.Value
    .Cells(iRow, 12).Value = Me.TextBox7.Value
    .Cells(iRow, 13).Value = Me.TextBox8.Value
    .Cells(iRow, 14).Value = Me.TextBox9.Value
    .Cells(iRow, 15).Value = Me.TextBox10.Value

Is it possible to add something to change the cell values 1-4? Maybe like this:
.Cells(iRow, 1).Value = *insert formula here*

Answer: You can use the range relative formula property .FormulaR1C1 to make formula references adjust relatively:
.Cells(iRow, 1).FormulaR1C1 = .Cells(iRow - 1, 1).FormulaR1C1

You can also use the regular .Formula properties instead, if you want the exact same formula, without relative references updating.
You can also do it for all 4 columns at once:
.Cells(iRow, 1).Resize(, 4).FormulaR1C1 = .Cells(iRow - 1, 1).Resize(, 4).FormulaR1C1

Comment: This is exactly what I needed! Thanks so much
Answer: If the formula is already in the cell above, you can do the below:
.Range(.Cells(iRow - 1, 1).Address,.Cells(iRow, 1).Address).Filldown

This will fill the formula from the cell above to the cell in question.


How can I send an auto-generated email every x-days with php mail(), without access to cron?

Question: I am trying to send an email, via php's mail function to user's every 15 days to remind them of a particular item (no worries, nothing spam related).  I unfortunately do not have access to cron, so I think I would need some sort of client side solution (is this correct?).
A link to get me started or a general outline of what I need to do would be great.
Thanks!
Comment: Why don't you have access to cron?
Answer: You would definitely need something that triggers this process on the interval you want, you might want to try something like http://www.webbasedcron.com/ then have a page that you can hit that sends out the emails.
Answer: Like said before you need a trigger.
That said, why not make a secret url the shoots the mail say:
http://mysite.com/secret/fireemailreport.php
And have a site like Pingdom do a scan on that every couple of days? Pingdom would fire a server response and your email would be sent. On top of that, if your email could not be sent (because your server was down), Pingdom would contact you!
Hope it helps!
EDIT: Check out the great comment by meador!
Comment: if you take this approach, be VERY careful that you write your "secret" script to check the last time it was activated and not do anything if 15 days hasn't elapsed.  You don't want someone discovering your secret URL and repeatedly requesting it to spam your clients.
Answer: U need a trigger and without cron you dont have a trigger.. unless ur site is reasonably high traffic and ur getting a hit on some page every minute or so .. if you have that kinda traffic .. you might use the page hit as a trigger and schedule mail sending according to that.
Answer: If you can't use cron, but can access the command line, you can create a deamon that runs an infinite loop checking the time and going to sleep, and when it's the right time it sends the message. You can use PHP-CLI for it, but cron seems much more appropriate.


Theme the taxonomy tags list in the node teaser

Question: In my Drupal site I have node teasers that show taxonomy terms. As it stands they are like:
Tags:
Houses

Tags:

        Houses

I cant locate where the  anchor tag is being generated. I want to be able to change it to a <button> tag instead of anchor.
Any ideas how to do this?
Comment: Have you tried hook_field_formatter_view()?
Comment: Hi mate, I have not tired `hook_field_formatter_view()` how would I implement this?
Answer: Take a look at this tutorial that shows you how to create a custom formatter for specific field types. The taxonomy term field type machine name is taxonomy_term_reference
Comment: Brilliant tutorial, is there a way without creating a custom module?
Comment: If you intend to use the hooks in the tutorial, you need to create a module . Creating a module for Drupal 7 is really simple - there are many tutorials online. Other than that, I guess you could try using jQuery to replace the tag  for , but I don't know enough jQuery to guide you. You would need to modify your theme .info file to load the .js file that contains the jQuery functions. I find this more complex than creating a module
Comment: Would it have to be a similar method if I wasn't changing the anchor to button but wanted to add extra classes to the anchor tag?
Comment: Check out field_formatter_class https://www.drupal.org/project/field_formatter_class. It allows you do ad css classes to the  wrapper around the  tag


can i join three list in python (string list and two number list)

Question: is there a way that i can concatenate a string list and 2 number list such that the concatenated list would take them one after the order while joining them.
Input:
a = [john, bob, ted, Paul]
b = [22, 34, 56, 12]
c = [13, 98, 78, 60]

Expected Ouput:

[john, 22, 13, bob, 34, 98, ted, 56, 78, Paul, 12, 60]

Comment: Possible duplicate of [Interleaving multiple lists in Python](https://stackoverflow.com/questions/7946798/interleaving-multiple-lists-in-python)
Comment: if you don't care about the order of the list you can also add the list together like `a + b + c`
Answer: You can use the zip function with list comprehension:
a = ['john', 'bob', 'ted', 'Paul']
b = [22, 34, 56, 12]
c = [13, 98, 78, 60]
outcome = [i for t in zip(a, b, c) for i in t]

outcome would become:
['john', 22, 13, 'bob', 34, 98, 'ted', 56, 78, 'Paul', 12, 60]

Note that the c list in your question has an extra 90 that is not in your expected output, so I removed it believing it's a typo on your part.
Answer: Using formatted string and enumerate with list comprehension
l = ['{}, {}, {}'.format(a[idx], b[idx], c[idx]) for idx, item in enumerate(a)]

['john, 22, 13', 'bob, 34, 98', 'ted, 56, 78', 'Paul, 12, 60']

Answer: Your lists :
Make Sure all lists have same dimensions.
a = ['john', 'bob', 'ted', 'Paul']
b = [22, 34, 56, 12]
c = [13, 98, 78, 90]

Import numpy a great module for handling arrays
import numpy as np

Make numpy array and reshape them as you want
a = np.array(a).reshape(-1,1)
b = np.array(b).reshape(-1,1)
c = np.array(c).reshape(-1,1)

Concate them along the required axis. In your case it will be 1 (Column wise as we have reshaped the arrays)
f= np.concatenate((a,b,c),axis=1)

Flatten them in 1D array
f = f.flatten()
print(f)


Does WaitForMultipleObjects() reset all auto-reset events?

Question: I've got an event loop that's waiting on several auto-reset events.
The events were all initialized into array eventHandles_ with CreateEvent(NULL, false, false, NULL).
while (true)
{
    DWORD waitResult = WaitForMultipleObjects(3, eventHandles_, false, INFINITE);
    switch (waitResult)
    {
    case WAIT_OBJECT_0 + 0:
        //handle event...

    case WAIT_OBJECT_0 + 1:
        //handle event...

    case WAIT_OBJECT_0 + 2:
        //handle event...
    }
}

My question: if event 1 and 2 occur simultaneously, the loop will process WAIT_OBJECT_0 + 1 because it's first.  But will event 2 remain signaled when the loop comes around again?  Or does it get reset automatically?
Comment: In general, it's just best to try to avoid such constructs.  I would have each signaling thread push a suitable index, delegate or whatever onto a thread-safe queue and signal a single semaphore.  This designs around the issue - the behaviour is entirely known and predictable, no events will ever get lost even if one thread signals more than once, there is no 64-handle restriction and the number of signaling theads is not fixed at compile time.
Answer: "...modification occurs only for the object or objects whose signaled state caused the function to return..."
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx
And from the mouth of one Raymond Chen:

If waiting for one event, then only that event is modified. If waiting
  for all events, then all are modified. That's what the documentation
  means by "object or objects". Singular if wait-any, plural if
  wait-all.


Sum of independent Gamma distributions is a Gamma distribution

Question: If $X\sim \Gamma(a_1,b)$ and $Y \sim \Gamma(a_2,b)$, I need to prove $X+Y\sim\Gamma(a_1+a_2,b)$ if $X$ and $Y$ are independent.
I am trying to apply formula for independence integral and just trying to multiply the gamma function but stuck ?
Comment: Hint: After multiplying $f_{X_1}(x)$ and $f_{X_2}(z-y)$ and making sure that the limits are correct, you will get an integral for $f_{X_1+Y_2}(z)$ that can be transformed into a _Beta_ function whose value is $B(a_1,a_2) = \frac{\Gamma(a_1)\Gamma(a_2)}{\Gamma(a_1+a_2)}$.
Answer: Now that the homework deadline is presumably long past,
here is a proof for the case of $b=1$, adapted
from an answer
of mine on stats.SE, which fleshes out the details of
what I said in a comment on the question.
If $X$ and $Y$ are independent continuous random variables,
then the probability density function of $Z=X+Y$ is given by the
convolution of the probability density functions $f_X(x)$ and $f_Y(y)$
of $X$ and $Y$ respectively. Thus,
$$f_{X+Y}(z) = \int_{-\infty}^{\infty} f_X(x)f_Y(z-x)\,\mathrm dx.
$$
But when $X$ and $Y$ are nonnegative random variables, $f_X(x) = 0$ when $x < 0$,
and for positive number $z$, $f_Y(z-x) = 0$ when $x > z$. Consequently,
for $z > 0$, the above integral can be simplified to
$$\begin{align}
f_{X+Y}(z) &= \int_0^z f_X(x)f_Y(z-x)\,\mathrm dx\\
&=\int_0^z \frac{x^{a_1-1}e^{-x}}{\Gamma(a_1)}\frac{(z-x)^{a_2-1}e^{-(z-x)}}{\Gamma(a_2)}\,\mathrm dx\\
&= e^{-z}\int_0^z \frac{x^{a_1-1}(z-x)^{a_2-1}}{\Gamma(a_1)\Gamma(a_2)}\,\mathrm dx
&\scriptstyle{\text{now substitute}}~ x = zt~ \text{and think}\\
&= e^{-z}z^{a_1+a_2-1}\int_0^1 \frac{t^{a_1-1}(1-t)^{a_2-1}}{\Gamma(a_1)\Gamma(a_2)}\,\mathrm dt & \scriptstyle{\text{of Beta}}(a_1,a_2)~\text{random variables}\\
&= \frac{e^{-z}z^{a_1+a_2-1}}{\Gamma(a_1+a_2)}
\end{align}$$
Comment: @A_for_Abacus I gave a _hint_ (actually a complete sketch of the answer) about the homework problem 12 minutes after the question was posted by the OP. So, there was no cruelty involved.
Comment: Dilip, Your response assumes that parameter $B=1$ is the same for both distributions. What would the function for the sum of two independent Gamma distributions be where both sets of parameters $A$ and $B$ are different? Convolute the two functions $z^{A_i-1}\mathrm{Exp}(-B_i z)/\mathrm{Gamma}(A_i)$, where $i$ is index $1$ and $2$.
Comment: You waited till his homework deadline is presumably long past to answer?! How cruel.
Comment: I wonder what the down voter found so objectionable about this answer.
Comment: Hey guys, I'm confusing why the integral started from $0$ to $z$ not  $0$to $\infty$?
Comment: @ToadetteK **Read** the two sentences immediately preceding the displayed integral for the explanation of why the lower limit got changed from $-\infty$ to $0$ and the upper limit got changed from $\infty$ to $z$.  Else, just break up $\int_{-\infty}^\infty$ into $\int_{-\infty}^\0 + \int_0^z+\int_{z}^\infty$ and _explicitly evaluate_ the first and third integrals in that sum, hopefully remembering what I said in the two sentences: that the integrand has value $0$ when $x < 0$ and also when $x > z$ as well as something from Calculus 101: the integral of $0$ over any interval has value $0$.
Comment: @DilipSarwate Thx a lot! I see.
Answer: It's easier to use Moment Generating Functions to prove that.
$$
M(t;\alpha,\beta ) = Ee^{tX} = \int_{0}^{+\infty} e^{tx} f(x;\alpha,\beta)dx
 = \int_{0}^{+\infty} e^{tx} \frac{\beta^\alpha}{\Gamma(\alpha)} x^{\alpha-1}e^{-\beta x}dx \\
 = \frac{\beta^\alpha}{\Gamma(\alpha)} \int_{0}^{+\infty} x^{\alpha-1}e^{-(\beta - t) x}dx = \frac{\beta^\alpha}{\Gamma(\alpha)} \frac{\Gamma(\alpha)}{(\beta - t)^\alpha} = \frac{1}{(1- \frac{t}{\beta})^\alpha}
$$
By using the property of independent random variables, we know
$$M_{X + Y}(t) = M_{X}(t)M_{Y}(t) $$
So
if $X \sim Gamma(\alpha_1,\beta), Y \sim Gamma(\alpha_2,\beta), $
$$M_{X + Y}(t) = \frac{1}{(1- \frac{t}{\beta})^{\alpha_1}}
\frac{1}{(1- \frac{t}{\beta})^{\alpha_2}} = \frac{1}{(1- \frac{t}{\beta})^{\alpha_1 + \alpha_2}}$$
You can see the MGF of the product is still in the format of Gamma distribution. Finally we can get $X + Y \sim Gamma(\alpha_1 + \alpha_2, \beta)$
Answer: You may use a easier method. Consider the moment generating function or probability generating function. $E(e^{(X+Y)t} )=E(e^{Xt}e^{Yt})=E(e^{Xt})E(e^{Yt})$ as they are independent then we can get a moment generating function of a gamma distribution. Then you can find the mean and variance from the Moment generating function


Partition of measure-preserving dynamical system.

Question: We have given a measure-preserving dynamical system $(X,\mathcal{B},\mu,T)$, where $T:X\to X$ is measurable transformation which preserves the measure $\mu$, i.e. $\forall_{A\in\mathcal{B}} \ \mu(T^{-1}(A))=\mu(A)$. Then in such space we take a partition, i.e. finite or countable set $\xi$ of nonempty measurable pair-wise disjoint subsets of X, for which $\bigcup_{A\in\xi}A=X$.
My question sounds: if that subsets in $\xi$ must have a positive measure? Can we take also a subsets which the measure $\mu$ is equal to zero (e.i. can $\xi$ consists some $B$, for which $\mu(B)=0$)? In other words whether the partition $\xi$ is understood $\mu$-almost?
Answer: Yes, you can also have sets of measure zero, provided that when you use the partition for something specific you "deal with them". For example, with the convention that $0\log0=0$ you can compute the entropy of the partition.
So, really it doesn't matter: you can either say that sets of measure zero are allowed or forbid them.
Another approach is to consider equivalence classes of partitions$\bmod0$ in the sense that two partitions are equivalent if for each set $A$ of one of them you can find a set $B$ in the other such that the symmetric difference $A\Delta B$ has measure zero.
For example, you can then define the entropy of the equivalence class as the entropy of any element of the class. Similar observations apply to many other concepts.
Comment: I just using this concepts to define a measure entropy of transformation $T:X\to X$ :) So ok, I will be understand the partition with sets of measure zero.


What is the difference between a density and a distribution in formal mathematical terms?

Question: A similar question has been already asked but its not in mathematical framework and therefore seems to be different. According to definitions from the book that I am reading, a random variable and a distribution are defined as follows:

Definition. Let $(\Omega', \mathcal{A}')$ be a measurable space and let $X:\Omega\to\Omega'$ be measurable. Then $X$ is called a random variable.
Definition. Let $X$ be a random variable. The probability measure $P_X:=P\circ X^{-1}$ is called the distribution.

Now according to what I see in physical textbooks there is some other thing called density and that differs from distribution. How that one is formally defined?
Comment: Short answer: a probability density, when it exists, is the [derivative](http://en.wikipedia.org/wiki/Radon%E2%80%93Nikodym_theorem#Radon.E2.80.93Nikodym_derivative) of its corresponding distribution.
Comment: @GiuseppeNegro, Thank you. It would have been great if you have written this as an answer
Answer: The distribution is simply the assignment of probabilities to sets of possible values of the random variable.  If I tell you how probable it is that a certain random variable is between $3$ and $5$, and also how probably it is that it's in every other possible set, then I've told you the distribution.  Since I can't do this for every set individually, since there are infinitely many sets, perhaps a more down-to-earth way to say this is this: Suppose $X$ and $Y$ are random variables.  If it is true of every set that the probability that $X$ is in that set is the same as the probability that $Y$ is in that same set, then $X$ and $Y$ have the same distribution.
A probability density function is a way of characterizing some distributions.  For example, consider the function
$$
f(x) = \begin{cases} 0 & \text{if }x<0, \\ e^{-x} & \text{if }x\ge 0. \end{cases}
$$
To say that this is the probability density function of a random variable $X$ is to say that for every measurable set $A$ of real numbers,
$$
\Pr(X\in A) = \int_A f(x)\,dx.
$$
The probability assigned to each set $A$ is given by the integral above.  A more concrete example:
$$
\Pr(3<X<5) = \int_3^5 e^{-x}\,dx\text{ and }\Pr(X\ge 2) = \int_2^\infty e^{-x}\,dx.
$$
Not every probability distribution has a density.  Say we let $X$ be the number of aces when a die is thrown four times.  Then $X\in\{0,1,2,3,4\}$.  The probability distribution assigns a positive number to every set that intersects that last set.  For example the set $\{x : x\ge 3.2\}$ intersects $\{0,1,2,3,4\}$ and thus the probability distribution of $X$ assigns a positive number to that set.  But there is no function $f$ such that for every set $A$ we have $\int_A f(x)\,dx$ equal to the probability that $X\in A$.
PS prompted by comments below: To put it in a different kind of language: Say $m$ is a measure (not necessarily assigning finite measure to the whole space) on the set of all measurable subsets of a space $S$.  A probability density with respect to the measure $m$ is a measurable function $f:S\to[0,\infty)$ such that the function
$$
A\mapsto \int_A f\,dm
$$
is a probability measure on the set of measurable subsets of $S$.
A probability distribution on $S$ is simply a probability measure on the set of all measurable subsets of $S$.  But not quite "simply": The probability distribution of a random variable $X:\Omega\to S$ is the probability measure on measurable subsets of $S$ that assigns measure $P(\{\omega\in\Omega : X(\omega)\in A\})$ to each measurable subset $A$ of $S$.
PPS: When $f\ge0$ is a measurable function on Borel or Lebesgue-measurable subsets of $\mathbb R$, one sometimes refers to the "measure" $f(x)\,dx$, meaning the measure
$$
A\mapsto \int_A f(x)\,dx.
$$
If in addition $\displaystyle\int_{\mathbb R} f(x)\,dx=1$, so that $f$ is a probability density, then one may similarly refer to the "probability distribution" $f(x)\,dx$.
(Of course, not all probability distributions on Borel subsets of the real line are of this form.)
Comment: @Cupitor : I've now added a "formal" definition.
Comment: I appreciate the time you have spent on answering the question with such a detailed answer but I was looking for the formal definition. One more thing is what you have defined again(distributions) has been already defined as part of my question.
Comment: @O.B.D.A. : Typo fixed.
Comment: You say that $X$ and $Y$ are r.v.s (which are functions), and then you talk about r.v.s that belong to a set, which is a little bit confusing, even though you can have sets of functions. I don't think that you're referring to functions when you say that  "If it is true of every set that the probability that $X$ is in that set". Maybe you are referring to the codomain of the $X$?
Comment: @nbro : In conventional usage in probability theory, the probability that a random variable $X$ is in a set $A$ is $P(X\in A) = P\{ \omega\in\Omega : X(\omega) \in A\}.$ It does not mean the probability that the function $X$ as a whole is a member of the set $A. \qquad$


How to get a download URL for files in Google Cloud Storage?

Question: I have created a service using :
storage.Client(project='project_name', credentials=credentials)
https://googleapis.dev/python/storage/latest/client.html
And I'm able to upload, delete and list the files in a users Google Cloud bucket. I've seen an option to download the file to a server, but is there any option to get a downloadable link?
Answer: You can get the downloadable link replacing the values of the following string:
https://storage.googleapis.com/{bucket.name}/{blob.name}

If you need to limit permissions or time to make the request, you can generate a Signed URL

A signed URL is a URL that provides limited permission and time to
  make a request. Signed URLs contain authentication information in
  their query string, allowing users without credentials to perform
  specific actions on a resource. When you generate a signed URL, you
  specify a user or service account which must have sufficient
  permission to make the request that the signed URL will make. After
  you generate a signed URL, anyone who possesses it can use the signed
  URL to perform specified actions, such as reading an object, within a
  specified period of time.
Comment: What I want is to get downloadURL for files(type-not public) in a users Google Cloud bucket using the credentials got after the user authentication. I am able to create a signed url for files in my bucket using the service account file created in the same account. Is there any option similar to AWS where we can create a signed url for files in a another persons bucket using the authentication token.
Comment: As I understand you want to get object link to download it in web browser?
Comment: yes , but not for the files in my Google Cloud Storage. For the files in a users account using the token got after user authentication
Comment: Seems this feature is not available in Google Cloud https://cloud.google.com/storage/docs/access-control/index
Comment: I will recommend you create Feature Request in GCP here https://cloud.google.com/support/docs/issue-trackers
Comment: ok will do that
Comment: Any luck with this feature request?
Comment: @subin_john_ Please could you share the Feature Request about downloading the file through a link after being authenticated ?
Comment: Hi Guys! I just found the FR regarding this functionality. Please keep in mind that there is no ETA for the functionality. I suggest to star the issue in order to be notified if there is any updates:
https://issuetracker.google.com/issues/150633508
Answer: You cannot use an access token to sign a URL because access tokens are time limited (about an hour). An alternative to using the private key file to sign a url, is to use IAM's SignBlob functionality.
You can use it with "gsutil"  by the command  "gsutil signurl -u --"  as mentioned in documentation. Note that with this method, the signed url is only valid for 12 hours, as compared to the maximum of 7 days as mentioned in the documentation

The signBlob service regularly rotates the private key that it uses.
Signed URLs generated are usable for at least 12 hours, but may stop
working prior to your set expiration time if the expiration time is
greater 12 hours. Given this, signed URLs generated from signBlob are
best used for short-lived access to resources.
Comment: @subin_john_ Posted an answer, Is it helpful?


Laravel - validate url path

Question: How does one validate a url in laravel.
Example I want to allow urls like this:
https://www.test.com/test
But not:
https://www.test.com/test/test
I only want to allow one path after the base domain.
Thanks
Comment: everything up to the first single slash is the domain. Subtract it from the string.  If the string still contains a forward slash then it is invalid.  Possibly also remove the final trailing slash if there is one, eg www.test.com/test/
Comment: What do yo mean `validate`? If there is no route defined for `/test/test` it won't require validating as it will `404`.
Comment: These routes are not real routes within our application, they are routes users define for accessing their profile on an external site. I need to validate that the inputed route only contains one path
Answer: what I actually did for this problem was checking the full URL with url()->current() with the generated URL by me for my categories or my brands page or even my product pages
if()urldecode($product->getUrl()) != urldecode(url()->current()){
   dd('hello');
}

Laravel - validate url path


Modal form - cant set error message, and no message for required field

Question: In a modal form, i've got e email field that is required.

when the field is wrong, a error message is well displayed
when the field is empty, $form_state->hasAnyErrors() is true but there is no error message
when i whant to set the error message in the form validation function, it's stay empty !

in BuildForm :
<code>  $form['email'] = array(
            '#type' => 'email',
            '#required' => true,
            '#attributes' => [
                'placeholder' => t('Your email'),
                "data-nluid" => $nluid
            ],
        );
$form['actions']['submit'] = [
                '#type' => 'submit',
                '#value' => t('Suscribe'),
                '#ajax' => [
                    'callback' => '::submitModalFormAjax',
                    'wrapper' => 'newsletter_add_modal',
                    'event' => 'click'
                ]
            ];
</code>
in validateForm
<code> public function validateForm(array &$form, FormStateInterface $form_state) {
        $emailValue = $form_state->getValue("email");
        if (!\Drupal::service('email.validator')->isValid($emailValue) || trim($emailValue) == "") {

         $form_state->setErrorByName('email', "Email is required and must be valid");
         //binding form_state->getError($form['email']) show empty string
        }
    }
</code>
in submitModalFormAjax
<code> // If there are any form errors, re-display the form.
        if ($form_state->hasAnyErrors()) {
            $response->addCommand(new ReplaceCommand('#newsletter_add_modal', $form));
        } else {
 // else, exec success behavior
</code>
What am I doing wrong?
Answer: I know i'm a bit late but the problem is that the email field is required.
Required fields may not be empty, otherwise it will throw an error.
If you wish to show an error message you need a form element to catch these messages.
<code> $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];
</code>


Codeigniter , classe Session é segura?

Question: O Codeigniter possui uma classe própria para Session, isto é, não utiliza as Sessions nativas do PHP.
Note: The Session class does not utilize native PHP sessions. It generates its own session data, offering more flexibility for developers.
Voce pode setar uma session da seguinte forma:
$data_session = array(
                              'id_login'                    => $id_user,
                              'nome'                         => $nome,
                              'userPermission'                   => 1
                              );
$this->session->set_userdata($data_session);

Minhá dúvida é:
É realmente seguro utilizar esta classe para gravar ID's que deveriam ser secretos?
Existe alguma contra-indicação na qual não deveríamos utilizar esta classe?
Comment: @RafaelWithoeft Se não me engano agora com a versão 3 que o Codeigniter passou a integrar com a superglobal `$_SESSION` do php sendo que nas versões anteriores as sessions do CI eram independentes. Com relação a segurança das sessions, nessa nova versão do CI elas foram reescritas, mas com as versões anteriores você também pode definir algumas configurações de segurança, como expiração da sessão, chave de encriptação entre outras configurações no arquivo `config.php`. Já ouvi várias críticas com relação as sessions do CI, mas é sempre legal configura-la antes.
Comment: @JhonatanOliveira, não sabia que nas versões anteriores eram independentes (Não utilizo CodeIgniter). Fui pesquisar e na documentação encontrei essa informação por isso perguntei o motivo dele falar "não utilizar sessions nativas"... mas obrigado pela informação, sempre é bom saber dessas diferenças. Até seria bom ele adicionar essa informação na pergunta, acho que é bem relevante...
Comment: O que você quis dizer com não utilizar sessions nativas? O CodeIgniter o chama de Session Library, como você mesmo pode ver são um conjunto de funções pré-escritas. Podemos acompanhar nesse link (http://www.codeigniter.com/userguide3/libraries/sessions.html#retrieving-session-data) que `$_SESSION['item']` e `$this->session->item` são a mesma coisa...
Answer: Sem o devido cuidado não!
Você pode setar algumas opções de segurança para a sua Session, como uma chave de encriptação (hash) e modificar o tempo de duração da sessão (por padrão 1 hora).
Uma situação (obviamente) não recomendável é deixar a Sessão ativa após fechar o navegador, que vinha por padrão ativada no arquivo config.php ou dados de recuperação;
Answer: Acredito que se você usar uma encriptografia (hash) e também , no arquivo config.php tornar false a opção de deixar a sessão ativa após o encerramento do navegador

Codeigniter , classe Session é segura?


Why linear regression is widely adopted given its (sometimes) poor prediction

Question: Linear regressions are in nearly every paper I've read. The authors always model the response variable as a linear combination of independent variables without regards to how the data is actually generated. It seems like they only use linear regression because it can produce a table with CI of "influence" of each variable ($\beta$ in $y = \alpha + \beta x + \epsilon_i $).
I want to know reasons social scientists use linear regression this much.
Also, should I use a more opinionated model (with a better fit) if possible?
Comment: Often linear regression is used but the axis of the graph are scaled to turn non linear data into linear data. So you can get a non-linear function if you rescale the axis back to their original but it's nice because it's easy to calculate correlation coefficient and R-squared.
Answer: As someone with background in social science I would say two main reasons:
Ignorance; usually social science get a crash course in statistics with simpler tests such as, chi-square, t-test, linear/logistic regression and ANOVA. This limits the way of looking at at problem. If all the tools you have are hammers, every problem will look like a nail.
Good enough; In social science its seldom that you want to predict a response variable rather you want to explain it. in that case a linear regression will do good enough. since there is no need for "a perfect fit". Sure if you want to maximize R-squared/RMSE there are other solutions, but if you "only" want to get an understanding what drives a behaviour, a general idea from a linear regression is often good enough.
I hope this was an answer to your question.


Why does this jQuery not work in IE but in every other browser?

Question: My question is why this code is working in all browsers except of IE function. In the other browsers it works.
if (phrases.indexOf(currentPhrase)) phrases.splice(phrases.indexOf(currentPhrase), 1);
Comment: Does IE give you any kind of JavaScript Error Messages?
Answer: My guess is that IE is caching the request (since it's through GET).  You can fix this in a bunch of ways including cache-control on the server side or using POST instead.  jQuery's .load() is a bit annoying in that you have to use an object as data to indicate you want a POST request and use a string for GET instead of allowing you to set an explicit request.
Comment: I found a trick to GET another variable like date(), is something like this you are referring to ?
Comment: Also, how do I make a POST request instead of this one ?
Comment: @kotsirokolos, yes, sending the datetime should work too.  You can make it POST by changing the data (second argument if there are three) to an object instead of a string or using `.post()`


How can I find the biggest magnitude present in a numpy array?

Question: Say I have:
<code>A = np.array( [1,2,3,-8] )
</code>
I need a function that would return 8
I know it's a simple one, but instant Google-Fu failed, hence some merit in populating SO maybe.
Comment: That's it! Could you put it as an answer?
Comment: Gimme a moment :) (SO does not allow you to accept an answer until several minutes after you've asked the question)
Comment: Sorry to rush you, thanks!
Answer: You can try running :
<code> np.abs(A).max()
</code>
Comment: Also see `argmax` if you need its index.


How to make quiz questions appear one at a time after clicking next in Javascript?

Question: So i've been trying to build a quiz app with a feature that when a user clicks a button called "next" the next question appears in place of the current one.
I'm fetching questions from another Js file which has the questions stored as an array of objects.
Initially i had a variable "i" which was initialized to 0 and i was planning to just increment it till i reach the total number of questions.
But how do i re-render that div when i increment "i". I'm trying to do this with vanilla Js.
Here's the code for the div.
div.innerHTML = `

${questions[i].name}

    <form id="myForm">
        <input type="radio" id="0" name="option" value="0">
        ${questions[i].options[0].title}

        <input type="radio" id="1" name="option" value="1">
        ${questions[i].options[1].title}

        <input type="radio" id="2" name="option" value="2">
        ${questions[i].options[2].title}

        <input type="radio" id="3" name="option" value="3">
        ${questions[i].options[3].title}

        <button id="submit">Submit</button>
        <button id="nextQuestion">Next</button>
</form>
`

document.body.appendChild(div);

document.getElementById("nextQuestion").addEventListener("click", (e)=> {

    e.preventDefault()

    if(i<questions.length){
        i++;
        // NEED TO DO SOMETHING HERE
    }
    else {
        alert("You've reached the last question.")
    }
})

EDIT >>>>>>>>>>>>
Thanks for the response.
So i was trying to think of something and ended up doing exactly what you told but now im stuck with another issue.
Now my next button works properly but when i submit on the first question it works properly and tells me if the answer is correct or not and then when i click next i get the next question but then if i try to submit it reloads the page. Even though i've used e.preventDefault() it reloads it. How do i deal with this?
document.getElementById("submit").addEventListener("click", (e)=>{

    e.preventDefault()

        let msg = document.getElementById("message");
        var correctAns = questions[i].answer;

        if(document.querySelector('input[name="option"]:checked') === null){
            msg.innerHTML = "Select an option to proceed."
        } else {
            let userAns = document.querySelector('input[name="option"]:checked').value;

            if(correctAns === userAns){
                msg.innerHTML = "Correct"
            } else {
                msg.innerHTML = "Incorrect"
            }

            document.getElementById("0").disabled = true;
            document.getElementById("1").disabled = true;
            document.getElementById("2").disabled = true;
            document.getElementById("3").disabled = true;
        }
})

Answer: You will need to render the HTML content of the question each time the index is updated, so you should throw the rendering logic into a function and call it each time you increment the question.
Also, if you know you are on the last question, you can change the text of the next button to "Finish" or render a different button in its place.
Lastly, you will want to clean-up any event listeners you associated to the DOM before replacing the content or you will have memory leaks.

const quizEl = document.querySelector('.quiz');
const questions = [{
  name: 'How many inches in a foot?', answer: '2',
  options: [{ title: '3' }, { title: '6' }, { title: '12' }, { title: '36' } ]
}, {
  name: 'How tall is the Eiffel Tower?', answer: '1',
  options: [{ title: '308m' }, { title: '324m' }, { title: '352m' }, { title: '463m' } ]
}];
let currentQuestion = 0;
let submitted = false;

const renderQuestion = () => {
  submitted = false;

  // Clean-up since we are removing the DOM
  removeClickListener(quizEl.querySelector('#nextQuestion'), handleNext);
  removeClickListener(quizEl.querySelector('#submit'), handleSubmit);

  const question = questions[currentQuestion];
  const isLast = currentQuestion === questions.length - 1;

  quizEl.innerHTML = `

${question.name}

    <form id="myForm">
        <input type="radio" id="0" name="option" value="0">
        ${question.options[0].title}

        <input type="radio" id="1" name="option" value="1">
        ${question.options[1].title}

        <input type="radio" id="2" name="option" value="2">
        ${question.options[2].title}

        <input type="radio" id="3" name="option" value="3">
        ${question.options[3].title}

        <button id="submit">Submit</button>
        <button id="nextQuestion">${!isLast ? 'Next' : 'Finish'}</button>
    </form>
  `;

  // Re-associate the listener
  addClickListener(quizEl.querySelector('#nextQuestion'), handleNext);
  addClickListener(quizEl.querySelector('#submit'), handleSubmit);
}

const addClickListener = (btn, listener) => {
  if (btn) btn.addEventListener('click', listener);
};

const removeClickListener = (btn, listener) => {
  if (btn) btn.removeEventListener('click', listener);
};

const handleNext = e => {
  e.preventDefault();

  const msg = document.getElementById('message');

  if (document.querySelector('input[name="option"]:checked') === null) {
    msg.innerHTML = "Select an answer to proceed."
    return; // Exit from function.
  }

  if (!submitted) {
    msg.innerHTML = "Please submit your answer before proceeding."
    return; // Exit from function.
  }

  if (currentQuestion < questions.length - 1) {
    currentQuestion++;
    renderQuestion();
  } else {
    alert("You've reached the last question.");
  }
};

const handleSubmit = e => {
  e.preventDefault()

  const msg = document.getElementById('message');
  const ans = document.querySelector('input[name="option"]:checked');

  if (!ans) {
    msg.innerHTML = "Please select an answer."
    return; // Exit from function.
  }

  const question = questions[currentQuestion];
  const correctAns = question.answer;
  const userAns = ans.value;

  if (correctAns === userAns) {
    msg.innerHTML = "Correct"
  } else {
    msg.innerHTML = "Incorrect"
  }

  document.getElementById("0").disabled = true;
  document.getElementById("1").disabled = true;
  document.getElementById("2").disabled = true;
  document.getElementById("3").disabled = true;

  submitted = true;
};

renderQuestion();
#message { color: red; }

Comment: Thanks for the reply. Can you please look at the edit?
Comment: It's all done thanks. Fixed the edit part too.
Comment: @Parth I updated my code to include submission handling. I added various messages to describe what is required as well.


Microsoft DNS behaving strangely

Question: I'm having this peculiar issue with Microsoft DNS.
Basically, we have domain.com that's a split horizon setup (external public DNS and internal DNS are both authoritative for separate zones), don't ask me why, it was like this when I got here.
In this AD we have 3 domain controllers, serving as DNS servers for the internal zones. On top of this, we have 2 DNS servers that forwards queries to these AD servers, and cache the results.
Additionally, we have another domain, example.com that's only in our external public DNS servers.
Now to the problem; AD servers have taken an issue with the name subdomain.example.com. The return queries with "domain name can't be found", as an authoritative server does when it doesn't have a record. However, the DNS forwarders for clients do resolve the query.
Externally everything works fine, subdomain.example.com resolves as it should to a CNAME for www3.domain.com
However, the problem is not with the whole zone, it's only with that specific subdomain. www.example.com resolves both internally and externally as a CNAME for www3.domain.com.
So, how can a DNS server that's not authoritative for a zone reply that a record can't be found?
As a workaround, I created a new zone for subdomain.example.com and added an A record that's identical with the one for www3.domain.com. And an hour later this record was gone?
I'm close to giving up and becoming a goat farmer. :)
Comment: Can you please share with us the configurations?
Comment: Configurations of what exactly? The DNS zones?
Comment: DNS zones and configurations of how the DNS servers are configured on the different domain controllers.
Comment: I'm having trouble picturing your DNS server flow from the description. Any way you could include a diagram?
Answer: I'm having trouble understanding your flow from the description but...
I would encourage you to have separate recursive and authoritative servers for your domain on the external side and have the internal DCs point to the external recursive servers with server forwarding.

This setup is commonly referred to as split DNS. One advantage is that you can force internal clients to respond to certain addresses differently than external clients. The other advantage is you can more easily troubleshoot the flow of DNS.
To answer your question, a server that's not authoritative for a zone can say the record is not found if it couldn't find an authoritative answer for the zone. You may have a problem with your DC DNS being unable to perform recursive look ups. Ensure that the server forwarding on the DCs is enabled and goes to the recursive DNS servers. Then make sure the Recursive servers utilize the Global Hints correctly.
You can play around with NSlookup, setting the server with server = IP command and testing each server in turn for what it can see.

Microsoft DNS behaving strangely


Android studio can't show icon after changing icon

Question: I have tried to change the default icon into another icon. But, the icon showed in the android is different with the icon at mipmap folder.
This is my emulator along with the wrong icon.

In the android phone, the icon doesn't even appear at all.
This is the manifest file.
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

The icon name is right as the code above. How can this happen?
Comment: if there is any folder  similar name to mipmap-anydpi-v26  then delete that folder
Comment: you mean like mipmap-hdpi or something?
Comment: no , mipmap-hdpi is fine . When you create a new project there will be a folder with name `mipmap-anydpi-v26` . If its there then remove the icons from it
Comment: by any chance are you testing on android  7.1 and  +?
Comment: i test on emulator. custom phone 8 api 26
Comment: @Redman thanks, it works now.
Comment: ok let me post an answer for future readers
Answer: Go to File > New > Image Asset and It will show you below dialog.

In Icon type select Launcher Icons (Adaptive and Legacy) option.
In Asset Type select Image and from below path choose your image, Similarly you can select background layer.
Now Select Next and Finish, and your Icon will be changed.
Answer: When you create a new project there will be a folder with name mipmap-anydpi-v26 . If its there then the icons will be picked from it for devices with Api 26+ . Just delete this folder and app icons will will be picked from mipmap folder .
mipmap-anydpi-v26 folder is for implementation of adaptive icons introduced in Api 26 . If you want to use adaptive icon then create an adaptive icon . If your phone is above version 8.0 , adaptive icon will be picked  else normal icon will be picked .
additional if you have ic_launcher_round then only phones with version 7.1 will pick from it .
Answer: Make sure you've updated the ic_launcher image in every mipmap folder such as

mipmap-hdpi
mipmap-mdpi
mipmap-xhdpi
Comment: Have you tried uninstalling and reinstalling the app from the emulator? Sometimes I have to do this for it to update.
Answer: try to rename your image file in mipmap as "appicon" and then set it to manifest as
   android:icon="@mipmap/appicon"


Uploading from within fieldset using drupal 6 forms API not working

Question: I've got a drupal form with a fieldset (actually, two). Inside the fieldset, there are a number of dynamically generated file fields. Unfortunately, I can't seem to access these fields' contents from file_save_upload. Currently, I'm attempting to use the approach described here to set the #name property of my file fields so that the files array gets built correctly. However, file_save_upload always returns 0. What am I doing wrong?
Form (this is an example, since the actual form is dynamically generated by a bunch of code that isn't relevant here):
$form['release_data_graphics'] = array(              //This has a few other random things in it
    '#type' => 'fieldset',
    '#title' => 'Brand Release Graphics',
    '#collapsed' => FALSE,
    '#collapsible' => TRUE,
    '#weight' => 11,
);
$form['release_data_graphics']['graphics'] = array(  //This has a few other random things in it
    'folders' => array(                              //This is here because I iterate through it
        'folder1' => array(
            '#type' => 'fieldset',
            '#name' => 'Folder 1',
            '#description' => 'some description',
            'graphics' => array(                     //This is here because I iterate through it
                'graphic1' => array(
                    '#type' => 'file',
                    '#title' => 'Upload graphic 1',
                    '#name' => 'files[1]',
                ),
                'graphic2' => array(
                    '#type' => 'file',
                    '#title' => 'Upload graphic 2',
                    '#name' => 'files[2]',
                ),
            ),
        ),
    ),
);

Then, in my submit handler, I iterate through the folders and child graphics arrays (which I won't show here) with file_save_upload. My code ends up running file_save_upload like this:
graphic1 = file_save_upload('1', file_directory_path(), FILE_EXISTS_REPLACE);
graphic2 = file_save_upload('2', file_directory_path(), FILE_EXISTS_REPLACE);

When I select a few items for upload and then print the files table in the submit callback, the files table looks good:
[files] => Array(
    [1] => test1.png
    [2] => test2.png
);

So I'm really having trouble figuring out what's going on...
Comment: How are you dynamically generating file fields. Are you doing it via AHAH? If not so then it can be the reason of problem. Drupal would not allow to accept dynamically created form fields and it would generate a validation error."An illegal choice has been detected"
Comment: Nope, it's all being done with the standard core Forms API. Basically, I loop through the results of a db query for images that the user can upload and add nodes to the form that are similar to 'graphics1' and 'graphics2'. Nothing fancy.
Comment: Upon further debugging, it looks like the ['#post']['files'] array is being generated properly, but that $_FILES['files'] isn't, and so file_save_upload can't find the file. It looks like I'll have to ditch the fieldset if no one has a workaround.
Comment: I think it is not recommended to use $_FILES array. Are you getting some kind of `fid` in ['#psot']['files']? If so then your files record are being dumped in 'upload' database table.
Comment: I'm not getting any fid entries in `[#post][files]`, just the `[name] => filename.png` output being shown above.
Answer: Add this to beginning of your form
You need this:
$form['#attributes'] = array('enctype' => 'multipart/form-data');

Also:
file_save_upload($source, $validators = array(), $dest = FALSE, $replace = FILE_EXISTS_RENAME)

you have
graphic1 = file_save_upload('graphic1', file_directory_path(), FILE_EXISTS_REPLACE);

you should have
$graphic1 = file_save_upload('graphic1',,file_directory_path(), FILE_EXISTS_REPLACE);

One thing I've noticed in D6 with file uploads is that using only file_save_upload() will result in your file being purged on a subsequent drupal cron run. This happens because all files are uploaded in Drupal with a status of 0.
Therefore, you should be calling your hook_submit more like this...
// Save new file uploads.
if ($file = file_save_upload('file_upload', $validators, file_directory_path())) {

// Do something with $file here.

//Make file permanent
file_set_status($file, FILE_STATUS_PERMANENT);
}

Comment: Thanks for the answer - I ended up solving the problem by removing the top level fieldset and rearranging my UI so that there was only one upload per fieldset. It actually ended up making things a lot easier to deal with in the form submission.
Answer: There is a known bug when file upload inputs are used inside fieldset in the Drupal 6 API. See these for more info:

bug: http://drupal.org/node/83698
possible alternative: http://drupal.org/node/83506

structure of $_FILES when more than one file input is used:

http://www.php.net/manual/en/reserved.variables.files.php#104395
http://www.php.net/manual/en/reserved.variables.files.php#89674


Adding Data to a Variable in a Contributed Module

Question: I'd like to add some data to a variable in a contributed module but I'm not sure how to do that with a custom module.
The Question:
The module I need to 'hack' is the Drupal Commerce PayPal WPP Module. I talked with PayPal and they said specifically I'd need to hack this file: 'commerce_paypal_wpp.module'. They said on line 365 if I added more data to the 'CUSTOM' variable (see below) it would pass that on to PayPal. Sweet! But how can I do that?
My Proposed Solution
I'm thinking I will create my variables to add to CUSTOM, like so (this is how I'd normally do it in PHP of course:
$fname = 'examplename';
$lname = 'examplelastname';
$arr = array($fname, $lname);
$allthedata = implode('+', $arr);
CUSTOM = $allthedata

It's that last line I don't know how to add properly! This, because 'CUSTOM' is already defined in the contributed module (see below).
The Function I Need to Edit:
The function in question in the contributed module is:
function commerce_paypal_wpp_submit_form_submit($payment_method,
$pane_form, $pane_values, $order, $charge) {

And the relevant code with 'CUSTOM' > the variable I want to change:
// Add additional transaction invormation to the request array.
  $nvp += array(
    // Order Information; we append the timestamp to the order number to
allow
    // for multiple transactions against the same order.
    'INVNUM' => substr($order->order_number, 0, 127) . '-' . REQUEST_TIME,
    'CUSTOM' => substr(t('Order @number', array('@number' => $order-
>order_number)), 0, 256),
    'DESC' => substr(implode(', ', $description), 0, 127),

    // Customer Information
    'EMAIL' => substr($order->mail, 0, 127),
    'IPADDRESS' => substr($ip_address, 0, 15),
    'FIRSTNAME' => substr($billing_address['first_name'], 0, 25),
    'LASTNAME' => substr($billing_address['last_name'], 0, 25),
    'STREET' => substr($billing_address['thoroughfare'], 0, 100),
    'STREET2' => substr($billing_address['premise'], 0, 100),
    'CITY' => substr($billing_address['locality'], 0, 40),
    'STATE' => substr($billing_address['administrative_area'], 0, 40),
    'COUNTRYCODE' => $billing_address['country'],
    'ZIP' => substr($billing_address['postal_code'], 0, 20),
  );
}

Comment: Hey @Sage, is this question still on? Did you try the hook_commerce_paypal_api_request_alter I mentioned below? Cheers
Answer: You will not need to 'hack' this module, you can use a legitimate hook to modify the $nvp array, hook_commerce_paypal_api_request_alter
At line 382 of the commerce_paypal_wpp.module, right after the part you mention, the whole array is passed to the commerce_paypal_api_request where the mentioned hook is called early on, to allow modifications from other modules.
Following your example code, your hook implementation would look like this:
function yourmodule_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method) {
  ...
  $fname = 'examplename';
  $lname = 'examplelastname';
  $arr = array($fname, $lname);
  $allthedata = implode('+', $arr);
  $nvp['CUSTOM'] = $allthedata;
  ...
}

Hope this helps!
Comment: Yes, thank you for the solution, it works very elegantly!
Comment: Very welcome, glad to hear!


Calculate missing side of quadrilateral

Question:
This is a problem from a Geometry Facebook group. Segment $AB$ is split as shown in the picture, in sub-segments of length 2, 5 and 4. Also $BT=2$ and $AS=5$. A, B, T and S are on the same circle. Also by extending TQ and SP, they intersect on point C, which supposedly is also on the same circle. We are looking for length of ST.
I have tried it in Geogebra and there is no way to have C on the same circle. I suspect something is wrong.
Since $ABTS$ is cyclic, I have tried to use several of its properties, for example, to draw its diagonals $d_1$ and $d_2$ (not shown in the image) and then use the property $d_1*d_2 = 11x+5$ but I am not getting anywhere.
Any ideas?
Thank you!
Comment: Here it is: https://i.stack.imgur.com/yzxmC.png
Comment: The figure can be constructed (just checked with GeoGebra) and $X\approx6.25$.
Comment: Construct the circle through $A$ and $B$, having its center on a generic point $O$ on the perpendicular bisector of $AB$. Construct then $S$ and $T$ on that circle and move $O$ until the intersection $C$ lies on the same circle.
Comment: @Intelligentipauca how? I have tried moving S and T on their circles but C is always outside the big circle.
Comment: I tried it but there is no way the circle passes through all 3 points (S, T and C). Remember that lines CS and CT must pass through P and Q, where $BQ=4$ and $AP=2$.
Comment: I see. I now tried again and got a similar measurement from Geogebra, but I still don't know how to compute it by using geometry, or even trigonometry. Thank you.
Comment: There several similar triangles and you can create more. For example you could find AC to be 7/2... and on
Comment: @Moti AC is not $7/2$. What similar triangles are you referring to?
Comment: @Juan It is. BTQ is similar ACQ
Answer: With
$$
\cases{
r_1=2\\
r_2 = 5\\
d_{BQ} = 4\\
d_{QP} = 5\\
d_{PA} = 2\\
\vec h = (0,1)\\
O=(0,0)\\
T=(t_x,t_y)\\
S=(s_x,s_y)\\
p = (x,y)\\
B=r(-\cos\theta,\sin\theta)\\
A=r(\cos\theta,\sin\theta)\\
Q=B+d_{BQ}\vec h\\
P=A-d_{PA}\vec h\\
L_1\to p = T+\lambda(Q-T)\\
L_2\to p = S+\mu(P-S)\\
C = L_1\cap L_2\\
(A-B)\cdot(A-B) = (d_{BQ}+d_{QP}+d_{PA})^2\\
(B-T)\cdot(B-T) = r_1^2\\
(A-S)\cdot(A-S) = r_2^2\\
(T-O)\cdot(T-O) = r^2\\
(S-O)\cdot(S-O) = r^2\\
(C-O)\cdot(C-O) = r^2
}
$$
and solving the last six equations for $r,s_x,s_y,t_x,t_y,\theta$ we obtain
$$
\cases{
r=6.09126\\
s_x =1.6875\\
s_y =5.85284\\
t_x =-4.35563\\
t_y = 4.25815\\
\theta = 0.444249
}
$$
and also $X = [TS] = \frac{25}{4}$

NOTE
Latter I saw the beautiful answer from here

Calculate missing side of quadrilateral


UTC within Site

Question: I am working on a website that will only be available via the intranet but is a website that is Australia wide ONLY.
The thing is, I have been asked to look into making the site UTC and was wondering how I could go about displaying a clock or determing which timezone the site in running in and so perhaps display a clock on the home page indicating the time in the state of Australia a user is using the site.
Would like some universal type jQuery, Javascript routine that will work out the correct clock time of where the user is located within Australia.
I was looking at http://randomibis.com/coolclock/ but from the looks of it, I need to specify the correct GMTOffset.
Could this value be determined somehow or is this something the user will need to specify?
Thanks.
Answer: The GMT offset of a given client is available within the browser via the Date class:
<code>var today = new Date();
var offset = -(today.getTimezoneOffset()/60);
</code>
Via http://www.24hourapps.com/2009/03/javascript-gmtutc-timezone-offset.html
Comment: Thanks for that - ould I then use this and pass into coolClocks.js?
Comment: Unsure why there is a - against the offset because if I am in Australia, that is placing me -10 instead of +10?
Comment: Depends on what you're trying to accomplish, you can remove the minus sign if you like.

UTC within Site


Abrir página numa determinada secção

Question: Eu gostaria que ao clicar em um link (ex: carros esportivos) a nova página, assim que carregada, executasse uma animação até a localização do "tópico" carros esportivos.
Segue o meu projeto:
http://andrellfreire.esy.es/Treinamentos.html
Na parte de cursos tem a opção dsg 7 e ao clicar nela a página de detalhes > http://andrellfreire.esy.es/Treinamentoslista.html é carregada, no entanto eu queria que ela desliza-se até a parte do dsg 7 (ou que já fosse carregada nela o que seria melhor). O mesmo iria acontecer nas outras opções.
Agradeço desde já pela ajuda
Answer: "...ou que já fosse carregada nela o que seria melhor...". Para isso não precisa de usar jQuery, visto que o browser (navegador) faz isso por nós, truque é inserir o id da secção da página onde quer ir parar também no URL. Veja se é isto que pretende:
http://andrellfreire.esy.es/Treinamentos.html#cursos
http://andrellfreire.esy.es/Treinamentoslista.html#dsg7
Ou seja, pode inserir logo no link direto:
...

...

O mesmo pode fazer para os outros

Abrir página numa determinada secção


What are the minimum permissions for a Windows share to be anonymous-read only?

Question: I am in the long and arduous process of resolving my confusion over Windows permissions, and would love to get some clarity over the following.
I would like to provision a Windows share such that any anonymous Windows computer on the network (we do not use a domain controller) can type \\servername\sharename and have read-only access to the files therein.
What I know:

The "Everyone" group does not include the "anonymous" SID. (Though strangely, that article doesn't "apply" to 2008 R2...)
There are two "levels" (probably not the best word) of permissions on the files themselves: the Share Permissions and the NTFS Permissions. (i.e. Share and Storage Management -> Properties -> Permissions)
There are some gotchas about operating in an environment without a domain controller but with identically-named user accounts on multiple machines.

What I think I know:

"Making Network Services Discoverable" should have no impact on the accessibility of properly-permissioned shares.
NTFS permissions must ALSO be configured for this share to be accessible -- not just share permissions!(?) (Despite Share and Storage Management claiming they only apply to local access.)
The "Everyone" group should not be left out of access permissions even though it explicitly refers to local user accounts, BECAUSE a client computer logged on as the same username as one local to the server will try to authenticate as that user, and be denied if there is a difference in password. (*groan*)

What I don't know:

Are there any gotchas having to do with cached credentials or server response? Should I reboot my test client workstation after every attempt to connect to the share?
Should the "Guest" account have anything to do with this, on either the share or NTFS permissions?
Am I correct in observing the need to configure "ANONYMOUS LOGON" with read permissions on BOTH the share and NTFS permissions? Same for "Everyone" group?
Comment: Share permissions only apply to the visibility of the share name. The content permissions are held in the file system independently. The share can also be partially hidden from compliant client by adding a '$' suffix. Cached credentials are not relevant for work group access. The client is not caching as it owns the credentials it presents. There are additional down-level protocols that also ignore case with registry keys that suppress them from use.
Comment: "Share permissions only apply to the visibility of the share name"' This is not true at all. Share and NTFS perms are indeed two levels of permission, and they are additive. If you are denied access at the share level (nothing to do with visibility of the share), then there aren't any NTFS permissions you can have that will grant you what you were denied.
Answer: First, setting up anonymous access to a share isn't that bad, you just have to include Anonymous in Everyone (you actually linked to it yourself):

Open the Local Group Policy Manager (gpedit)
Computer Configuration
Windows Settings
Security Settings
Local Policies
Security Options -- Network access: Let Everyone permissions to apply to anonymous users from Disabled to Enabled
Change Network access: Restrict anonymous access to Named Pipes and Shares to disabled
Network access: Shares that can be accessed anonymously - set the share name there you are sharing.

As far as the Share itself goes then.  Set the Share Permissions as "Everyone - Modify" and "Administrators - Full Control".  Then set the NTFS permissions as Administrators - Full Control and Everyone - <whatever rights needed>
That should handle your need.
Comment: So, it's preferable to change those settings rather than add the "ANONYMOUS LOGIN" security object to the share permissions? Why do "Everyone" users need 'modify' ('change'? No 'modify' on share permissions.) on the share? I created a test share that seems to be accessible with just 'read' set on "Everyone" and anon.
Comment: Sorry, it's habit for me.  I always set SHARE perms that way and then lock them down to read-only at the NTFS level.  That way if I do require that someone suddenly needs write access I don't have to modify the share perms.
Comment: Is there a reason Administrators should have full control on the share permissions? (Presuming I never want to modify the share when connecting to it remotely)
Comment: They would need it for Full Control NTFS permissions to work on the files/folders within the share.
Comment: Even if Administrators only need Full Control when accessing the files locally???
Comment: No...at that point it wouldn't be necessary.
Answer: Three things need to be done to set up access for anonymous users under the "Everyone" group, which is cleaner than using 'ANONYMOUS LOGON' explicitly:
1. Create the File Share

NTFS permissions: set 'Read & Execute', 'List Folder Contents', and 'Read' for the 'Everyone' group
Share permissions: set 'Read' for the "Everyone" group

2. Adjust Local Security Policy
Open "Local Security Policy", navigate to Security Settings -> Local Policies -> Security Options, and set:

Network access: Let Everyone permissions apply to anonymous users - Enabled
Network access: Restrict anonymous access to Named Pipes and Shares - Disabled
Edit Network access: Shares that can be accessed anonymously to be the name of the share you created. (Formatting is ambiguous, but don't include the server name, and presumedly this is a comma-delimited list if you need more than one.)

3. Allow Access Without a Password

Open "Advanced sharing settings", either from "Network and Sharing Center" in control panels, or by clicking the link in Properties on the directory (under Password Protection).
Change the "Password protected sharing" setting to off.

Other notes:

Permissions need to be granted for users BOTH on the NTFS and Share levels
Consider any testing you do on a machine logged in as a user whose name matches one on your server to be useless (but rebooting a true test machine will not be necessary)
Answer: I found this to give me something similar i was looking for. The link below will give anonymous users read only access. No credentials will be required. If you want to add RW access in the step where you add the guest account, just grant full access instead of read only.
http://nikolar.com/2015/03/10/creating-network-share-with-anonymous-access/


Can I perform cross correlation on non-stationary data?

Question: I have level data which need different level of integration to be stationary. I would like to know how to perform a correlation analysis. Can I perform this on raw data or must the data be stationary?
Comment: You can still calculate the sample correlation for time series $X(t)$ and $Y(t)$ if they are non-stationary. However, the two time series must be _cointegrated_. If yes, the sample correlation will be a consistent estimator of the true correlation.
Comment: @stans-ReinstateMonica, I wonder if true correlation for cointegrated processes might be dependent on time and approaching 1 or -1 as the length of the time series grows. If so, what is the sample correlation estimating consistently? The correlation for that particular sample size? Would you have a reference?
Comment: These questions are part of very standard time series knowledge, which has been available to humankind for decades. Please see Green or Hamilton... What I have stated to you is correct.
Comment: @stans, here is a simulation in R illustrating the distribution of sample cross correlation of two cointegrated processes when the true correlation between their innovations is approximately zero:
`Ts=c(30,100,300,1000,3000);
m=1000;
XCor=matrix(NA,ncol=length(Ts),nrow=m);

for(j in 1:length(Ts)){
 for(i in 1:m){
  set.seed(i    ); x=cumsum(rnorm(Ts[j]));
  set.seed(i+1e6); y=x+rnorm(Ts[j]);
  XCor[i,j]=cor(x,y);
 };
};

for(j in 1:length(Ts)){
 plot(density(XCor[,j]));
 readline();
}` If you run it, you will see that it contradicts your statement but does not contradict mine.
Comment: @stans-ReinstateMonica, given the simulation evidence, I am curious about a precise reference in those classical textbooks contradicting it.
Comment: And did you let the sample size converge to infinity? Consistency means n----> inf. With all respect, and with warmest wishes, what I have stated is quite standard. Again: Greene or Hamilton... I would love to engage in a debate with you regarding some other, more sophisticated and unresolved matters, like gradient boosting versus deep learning. Warmest regards.
Comment: @CagdasOzgenc, in presence of nonstationarity, cointegration is one of two situations that are possible, so it is relevant enough, I guess. stans mentioned it, and I chipped in to point out some false statements.
Comment: @RichardHardy I'm afraid, your simulation describes a different problem. By design, you are making the true correlation between $X(t)$ and $Y(t)$ change over time in the regression equation $Y(t) = X(t) + \varepsilon(t)$. Naturally, if there is "no true correlation" (loosely speaking), if the correlation is constantly changing then there is nothing to estimate consistently. However, if the true correlation is constant, the estimate will be consistent... You may ask, which two non-stationary process could possibly have constant correlation? Are they not supposed to explode over time? (cont.)...
Comment: ... Well, not necessarily. Imagine four independent stationary processes: $U(t)$, $V(t)$, $Q(t)$ and $W(t)$. Let's say all of them have unit standard deviations and zero means. Further, ${\rm corr}(U(t-1),U(t)) = \eta\neq\gamma = {\rm corr}(V(t-1),V(t))$. Next, let us define a somewhat strange process $Z(t)$: $Z(t) = U(t)$, $t = 1,...,10$, $21,...,30,$ $41,...,50,...$; $Z(t) = V(t), t = 11,...,20,$ $31,...,40,$ $51,...,60,...$. Process $Z(t)$ is non-stationary but non-explosive, nonetheless. Finally, as you can guess, $X(t) = a Z(t) + Q(t)$ and $Y(t) = a Z(t) + W(t)$. (cont.)...
Comment: ... $X(t)$ and $Y(t)$ are cointegrated non-stationary processes. Their correlation is constant and equals $\rho = a^2 / [a^2 + 1]$. The regression equation equals $Y(t) = \rho X(t) + \varepsilon(t)$ and $\rho$ is estimated consistently by the sample correlation... I take back some of what I've said. Thank you for your comments. They made me think more deeply about the problem.
Comment: @stans, so what do you take back? *I'm afraid, your simulation describes a different problem*. No, this is incorrect. What you subsequently describe is characteristic to cointegrated processes - see my first comment. Also, your $X(t)$ and $Y(t)$ are not cointegrated because they are not integrated to begin with, hence your argument breaks down.
Comment: @RichardHardy I was using term "cointegration" in the wide sense: two processes are non-stationary but their linear combination is stationary (something which is done in finance, somewhat loosely, I guess). You want "cointegration" to be used in the narrow sense (two processes are $I(1)$ but their linear combination is $I(0))$? Fine. Let's make $Z(t) = t + U(t)$. Now $X(t)$ and $Y(t)$ are $I(1)$... In this case the sample correlation is calculated on the detrended data but consistent estimation of the true correlation is still possible, for these  two so non-stationary processes. (cont.)...
Comment: ... Also please note that OP's question implies that there exists a constant correlation, which is possible. Hence your simulation, which has violated the assumption, corresponds to a different problem... More importantly, I hope you've read my argument fully and see what I am trying to say. I do see what you have been saying... I take a couple of my sentences back in the sense that this discussion turned out to be more interesting and informative than what I had originally expected. And for this I am thankful to your comments. Also thanks for checking the mathematics of my argument.
Comment: @stans-ReinstateMonica, *You want "cointegration" to be used in the narrow sense*: whether I want it or not, I am using the well established notions of integration and cointegration; see Hamilton or Greene, or any time series textbook for that matter. Meanwhile, your use of terminology is clashing with the established one. Hence, you may wish to create your own terms to avoid ambiguity. Regarding your new example, adding a deterministic time trend to a stationary variable does not make it integrated. Also, in my eyes the OP does not even remotely imply that there exists a constant correlation.
Comment: @RichardHardy Adding a determinstic trend to a stationary process _does_ make it integrated. For example, this Wikipedia page (http://en.wikipedia.org/wiki/Order_of_integration) says: "In statistics, the order of integration, denoted $I(d)$, of a time series is a summary statistic, which reports the minimum number of differences required to obtain a _covariance-stationary series_"... Of course, OP's problem implied constant correlation. The whole premise of frequentist point estimation is that the parameter is constant but unknown. Of course, one cannot estimate something which does no exist.
Comment: @RichardHardy Cointegration is usually considering nonstationarity in terms of acumulating shocks, however some authors also use "common trend" idea without specifying what kind of trend we are talking about. At the end of the day if Y(t) = aX(t) + e(t) can be satisfied if common trend can be cancelled out. In that case I believe "a" can be estimated.
Comment: @CagdasOzgenc, thanks for you input. I am too busy to deal with this rigorously (by posting an answer myself), but I have spent some effort on not leaving misleading statements unchallenged out here on CV.
Answer: You can calculate correlation for non-stationary variables, but you have to think carefully about why you are doing so and what you hope to learn.  As @stans-ReinstateMonica suggested, reading up on co-integration would be a good start.
As @RichardHardy points out, one problem is that your estimates will depend on your estimation window.  Imagine we have two integrated processes that are just straight lines through the origin with opposite slopes. Their correlation is -1.  Now add some shared stationary noise to each of them, and the correlation will increase towards 1 as the variance of the noise becomes large relative to the variance of the lines.  Unfortunately, that variance is proportional to the square of the width of the observation window, so changing the window changes the correlation.
Because of problems like this, I find it hard to think of examples where calculating the correlation of nonstationary variables would be useful.  If in doubt I suggest you difference for stationarity but, as always in statistics, in the answer to what you should calculate should be determined by the inference you wish to draw from the result.
Comment: *the correlation will increase towards 1 as the variance of the noise becomes large relative to the variance of the lines*: perhaps *small* rather than *large*? Also, a straight line is not a representative example of an integrated process.
Comment: No, I do mean large -- the noise is shared so when it is large correlation approaches 1.  Straight lines are just a simple example to illustrate.
Comment: Missed the word "shared" initially, my bad.


In Jython, can I make an inline anonymous class that implements a Java interface?

Question: In Java, I can say
Thread t = new Thread(){
    public void run(){ // do stuff }
}

(or something much like that) to declare an anonymous class inline.  This is most useful for making event handlers or other callback sorts of things, that in any sensible language wouldn't require an object to own them in the first place.
I face the same problem in Jython -- I want to define an event handler, but I don't want to build a whole standalone class to do so.
Ideally, I'd just be able to pass a lambda and be done with it, but if this is possible, I can't find it anywhere in the docs.
Comment: http://stackoverflow.com/questions/357997/does-python-have-something-like-anonymous-inner-classes-of-java

http://stackoverflow.com/questions/1123000/does-python-have-anonymous-classes

http://stackoverflow.com/questions/652276/is-it-possible-to-create-anonymous-objects-in-python
Comment: David: This is exactly what I was asking, if you make your comment an answer I'll accept it.  Thanks!
Answer: Here are the background-reading links from my original answer:
Read this: Does Python have something like anonymous inner classes of Java?
Then, read this: Does Python have anonymous classes?
Finally, read this: Is it possible to create anonymous objects in Python?
[IMPROVEMENT TO ORIGINAL ANSER]
Jython implicitly converts a function to an event handler when appropriate.  So, you can write this inside of one of your methods:
def _(self, event):
    print 'Cancel button was clicked!'
    if self.task is not None:
        self.task.cancel()
cancelButton.setOnAction(lambda event: _(self, event))

This approach provides three of desirable characteristics of an anonymous inner class.
(1) It is highly localized.  The handler code is next to the code that assigns the handler.
(2) It is self aware, meaning you have self and can access to all of the members of the containing object.
(3) It is (almost) anonymous.  Python forces me to choose a name for multi-line function, but it also allows me to reuse that name.  So, I can define as many local functions called _ as long as I use them right away.  (Defining a second function by the same name makes the first function inaccessible by that name.)  So, I am not forced to invent unique names ad-infinitum.
You can also package this pattern in a decorator, which I think clarifies the intent a bit:
@LocalEventHandler(self, cancelButton.setOnAction)
def _(self, event):
    print 'Cancel button was clicked!'
    if self.task is not None:
        self.task.cancel()

The decorator implementation looks like this:
class LocalEventHandler(object):
    '''This decorator turns a local function into a *self aware* event handler.'''

    def __init__(self, context, assignHandlerFunc):
        self.context = context
        self.assignHandlerFunc = assignHandlerFunc

    def __call__(self, handler):
        self.assignHandlerFunc(lambda event: handler(self.context, event))
        return handler

Comment: Potential problem: I tried this approach to adding a `ChangeListener` to through `ReadOnlyObjectProperty.addListener()`.  But, `addListener()` is overloaded and Jython picks the 'wrong' overloaded function.  What I end up with is an `InvalidationListener` instead of a `ChangeListener`.


Como nomear automaticamente uma CONSTRAINT criada manualmente no SQLServer 2016

Question: Olá, estou criando uma base de dados e preciso criar alguns indexes compostos para otimizar o processamento do banco. O problema é que não quero ter que nomear esses indexes um-a-um. Normalmente, eu crio uma tabela da seguinte forma:
CREATE TABLE Usuario (
    id INT NOT NULL IDENTITY PRIMARY KEY,
    email NVARCHAR(100) NOT NULL UNIQUE,
    senha NVARCHAR(100) NOT NULL DEFAULT '123',
)

Ao criar essa tabela, automaticamente o SQLServer já gera para mim as CONSTRAINT para os campos email (UNIQUE) e senha (DEFAULT). O problema é quando eu tenho que criar um index composto, como no exemplo abaixo:
CREATE TABLE Foo (
    id INT NOT NULL IDENTITY PRIMARY KEY
);
CREATE TABLE Bar (
    id INT NOT NULL IDENTITY PRIMARY KEY
);
CREATE TABLE Bin (
    id INT NOT NULL IDENTITY PRIMARY KEY,
    FooId INT NOT NULL FOREIGN KEY REFERENCES Foo(id),
    BarId INT NOT NULL FOREIGN KEY REFERENCES Bar(id)
);
CREATE UNIQUE INDEX [UX_Bin_FooIdBarId] ON Bin(FooId, BarId);

Existe alguma forma ou declaração ou caractere coringa que eu possa utilizar na declaração desse index para que ele seja nomeado automaticamente? ou então alguma outra forma de criar esse index composto para que tenha o mesmo resultado?
Answer: Não se você quiser usar o comando create index, o nome é obrigatório: docs.microsoft.com
O que acontece como você já sabe é que quando você usa create table ou alter table e criar constraints ou índices (chave primária por exemplo) implicitamente (usando default, unique, etc), o sql-server se encarrega de nomear, mas se criar explicitamente usando o comando create precisa dar um nome.
Answer: Como o Ricardo Pontual comentou, é obrigatório informar o nome de constraints criadas fora do comando CREATE TABLE.
Porém, é possível criar constraints mais complexas já na criação da tabela, não precisando assim nomeá-las manualmente. Considerando o seu exemplo:
CREATE TABLE Bin (
  id INT NOT NULL IDENTITY PRIMARY KEY,
  FooId INT NOT NULL FOREIGN KEY REFERENCES Foo(id),
  BarId INT NOT NULL FOREIGN KEY REFERENCES Bar(id),
  UNIQUE(FooId, BarId)
);

Lembrando que você pode também usar essa declaração para definir outras constraints ou índices sobre a tabela, como por exemplo, uma CHECK constraint que verifica duas colunas da tabela ou até mesmo uma chave estrangeira composta.
Comment: Excelente. Muito obrigado mesmo! É um saco ter que ficar nomeando essas referências... rs


JQGrid sortableRows change sorting column values to match new order

Question: So I'm using JQGrid to produce a table. The data is read from a database and the table is populated via JSON. Once the table is rendered all the sorting and editing is done locally until the data is saved backed into the database. I am using the sortableRows function so that i can drag and drop and reorder the rows; it is working as expected except I also want the values of a specific columns to change based on the new order. I have been following this example here as is does exactly what I'm trying to do, but looking at the source code as not done me much good. I believe it has to do with the update() function.
I want the values of the Display Order column to be renumbered starting from 0 going by multiples of 10 depending on the new order the the rows. like is in my example
Can anyone give me some insight in the right direction?
Here is my JQGrid code:
$(function() {
    $("#grid").jqGrid({
        url:'/WEB_META_CONFIG/meta/record?meta_type=${meta_type}&plan_id=${plan_id}',
        datatype: 'json',
        mtype: 'GET',
        colNames:[
                    'Display Order',
                    'Field Name',
                    'Field Label',
                    'Meta Type',
                    'Display Control',
                    'plan id',
                    'lov',
                    'rounding formula',
                    'units',
                    'hrms data type',
                    'conversion data type',
                    'modified by',
                    'capability',
                    'field width',
                    'field validation message',
                    'field null string',
                    'field ineligibility tag',
                    'hard validation logic',
                    'hard validation message',
                    'soft validation logic',
                    'soft validation message',
                    'attribute1',
                    'attribute2',
                    'attribute3',
                    'attribute4',
                    'attribute5',
                    'field required',
                    'field length',
                    'field format',
                    //'calculation',
                ],
        colModel:[
            {name:'display_order',index:'display_order', align:'center', width:'100',sorttype:'int'},
            {name:'field_name',index:'field_name', align:'left', editable:true},
            {name:'field_label',index:'field_label', align:'left', editable:true},
            {name:'meta_type',index:'meta_type', align:'center', width:'60'},
            {name:'display_control',index:'display_control', align:'left',editable:true},
            {name:'plan_id',index:'plan_id', align:'left',hidden:true},
            {name:'lov', index:'lov', align:'left',hidden:true},
            {name:'rounding_formula', index:'rounding_formula', align:'left',hidden:true},
            {name:'units', index:'units', align:'left',hidden:true},
            {name:'hrms_data_type', index:'hrms_data_type', align:'left',hidden:true},
            {name:'conversion_data_type', index:'conversion_data_type', align:'left',hidden:true},
            {name:'modified_by', index:'modified_by', align:'left',hidden:true},
            {name:'capability', index:'capability', align:'left',hidden:true},
            {name:'field_width', index:'field_width', align:'left',hidden:true},
            {name:'field_validation_message', index:'field_validation_message', align:'left',hidden:true},
            {name:'field_null_string', index:'field_null_string', align:'left',hidden:true},
            {name:'field_ineligibility_tag', index:'field_ineligibility_tag', align:'left',hidden:true},
            {name:'hard_validation_logic', index:'hard_validation_logic', align:'left',hidden:true},
            {name:'hard_validation_message', index:'hard_validation_message', align:'left',hidden:true},
            {name:'soft_validation_logic', index:'soft_validation_logic', align:'left',hidden:true},
            {name:'soft_validation_message', index:'soft_validation_message', align:'left',hidden:true},
            {name:'attribute1', index:'attribute1', align:'left',hidden:true},
            {name:'attribute2', index:'attribute2', align:'left',hidden:true},
            {name:'attribute3', index:'attribute3', align:'left',hidden:true},
            {name:'attribute4', index:'attribute4', align:'left',hidden:true},
            {name:'attribute5', index:'attribute5', align:'left',hidden:true},
            {name:'field_required', index:'field_required', align:'left',hidden:true},
            {name:'field_length', index:'field_length', align:'left',hidden:true},
            {name:'field_format', index:'field_format', align:'left',hidden:true},
            //{name:'calculation', index:'calculation', align:'left',hidden:true},
            ],
        rowNum:10,
        rowList:[10,20,40],
        shrinkToFit : true,
        loadonce: true,
        gridview: true,
        //editurl:'/WEB_META_CONFIG/meta/record',
        cellEdit: true,
        cellsubmit:'clientArray',
        height: 'auto',
        autowidth: true,
        rownumbers: false,
        pager: '#pager',
        sortname: 'display_order',
        viewrecords: true,
        sortorder: "asc",
        caption:"${plan_id} - ${meta_type}",
        emptyrecords: "Empty records",
        sortable:true,
        jsonReader : {
            repeatitems: false,

        },
        beforeSelectRow : function(rowid) {return false;},
        ondblClickRow: function(rowid, iRow,iCol){
            $('#grid').editCell(iRow, iCol, true);
        },
    });

    $("#grid").jqGrid('navGrid','#pager',{edit:false,add:false,del:false,search:false});
    $('#grid').jqGrid('sortableRows', {
        update:function(ev, ui){
            var item = ui.item[0], ri = item.rowIndex, itemId = item.id;
        }
    });

    $("#grid").navButtonAdd('#pager',
            {   caption:"Save",
                buttonicon:"ui-icon-disk",
                onClickButton: save,
                position: "last",
                title:"",
                cursor: "pointer"
            }
    );

    function save(){

        //var data = $('#grid').jqGrid('getRowData');
        var data = $('#grid').jqGrid('getGridParam', 'data');

        for(var i = 0; i < data.length; i++){
            delete data[i]["_id_"];
        }

        $.ajax({
            type :"POST",
            url : "/WEB_META_CONFIG/meta/record/save",
            contentType: "application/json; charset=utf-8",
            dataType:"json",
            data: JSON.stringify(data, function(key, value){
                                    return (value == null) ? "" : value;
                                    }
            ),
            success: function(){
                alert('Save Successfully');
            }
        });

    }

});

Answer: I think you will need to call the remapColumns function to do this as part of your update call.  The tricky part is finding what the new order should be based on the user changes you have described.  This new order is passed into the array as the first part of the call.  See jqgrid documentation
$("#grid").remapColumns([1,3,2],true,false);