How do I generate Psuedo-random numbers in pact. Why does now() or rand() violate PACT's core principles?

Question: When writing a bar dice game on PACT for a tutorial,  I needed to roll a series of dice in rapid succession.  After noticing no RAND() capability or NOW() capability I was stuck because my .repl and .pact files were not yet sent to test-net.   Therefore, the chain-data object was not useful in this instance as it just refers to start epoch until pushed.  (was running directly in Ubuntu bash)
Obviously, we can just make an API into a front end and pass in unique times, hash them up, and mod by 6 to roll a die. However, this led us to think about PACT and why NOW() and RAND() is not allowed.  We must admit we were stumped on this one as they are so critical in so many applications.
Is this because it opens up PACT to change of state and therefore isn't secure?  Please teach us about the theoretical issues behind opening these HASKELL functions up as a core PACT function.
Comment: You should ask precise questions that can be answered with a precise answered. Asking to "teach haskell theory" is probably too broad
Comment: who's combative attitude?
Answer: As a disclaimer - you will never have secure randomness on the blockchain.
There are work arounds for rand
One way is

Get the current hash of the time
Convert it to base 64
Convert base 64 to normal number

<code> (str-to-int
    64
    (base64-encode
        (hash (at "block-time" (chain-data) ))
    )
)
</code>
As to your problem around " I was stuck because my .repl and .pact files were not yet sent to test-net"
You can set the time variable via your repl files manually like so
<code>(env-chain-data { "block-time" : (time "2021-04-28T00:00:00Z") })</code>
Comment: the function chain-data is included in base pact. You can use it from repl as well as on-chain.
Comment: Notice that I mentioned that I had not launched to test-net or main-net and therefore the chain-object was not useful for tests.  Hence I wondered why these critical functions were not included in base pact as they are in Haskell.  https://hackage.haskell.org/package/time.  The question I think was extremely simple.  What makes NOW() and RAND() insecure?
Comment: You didn't even read the question where chain-data was clearly not a solution and not an answer to the question at all.  @georgep    At least read the question.
Comment: >  I was stuck because my .repl and .pact files were not yet sent to test-net
You can update the chain time locally if you're testing via repl
Comment: @KDAbet updated the answer to include how to do this.
As a sidenote - this probably could've been 2 or 3 questions, like
1. How to get a random number in Pact
or
2. How to get a random number in your local .repl environment
3. Why does now() and rand() violate core Pact principles.

It's a bit hard to answer multiple questions at once, even with good intent its easy for readers to miss some details
Comment: That's true,  but the fundamental question is why no RAND() or NOW() which is 3.   I got some half answer in builders telegram where the async push in fetch.send would result in random numbers being mismatched which makes sense.   but then I asked why can't I send a request to run (randlist int) on one chain,  mine it,  then propagate that message to all 20 chains?  I guess they just don't want a stateful function being opened up because it opens up function purity headaches.
Answer: All smart contract languages must be 100% deterministic.  That means that when you run something with the same inputs it gives the same output every time, no matter when or on what computer you run it.  NOW() and RAND() are not deterministic.  They give different results every time you call them.  So they can't exist in a smart contract language, full stop.
Comment: I think no-one expects a 100% purely random and secure RAND() function from a smart contract. Most languages are deterministic and have RAND() functions which aren't secure to help developers out.

This doesn't explain why there isn't a `PSEUDO_RAND()` which takes a seed number in it and uses curr time.
I'm not sure if possible - but if the GAS costs are computed as execution happens, then the gas used upto when PSEUDO_RAND is called, could be added to make things more random
Comment: There is a function like this that takes a seed value and gives you back something unpredictable that is a deterministic function of its input: [hash](https://pact-language.readthedocs.io/en/stable/pact-functions.html#hash).  It doesn't use current time, but rather does the more general thing of letting you use whatever you want as input.


Can Agresti-Coull binomial confidence intervals be negative?

Question: According to http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm
Agresti-Coull intervals cannot be negative; however using the formula from Wikipedia as well as the binom.confint function in R with x = 0 and n = 5 produces an interval of (-0.05457239, 0.4890549).
Are there conflicting definitions of Agresti-Coull?
Edit -
Using binom.confint:
binom.confint(0, 5, .95, 'agresti-coull')
         method x n mean       lower     upper
1 agresti-coull 0 5    0 -0.05457239 0.4890549

Manually calculating the lower bound (using the formula from Wikipedia):
> n <- 5
> x <- 0
> n2 <- n+qnorm(0.025)^2
> p <- 1/n2 * (0 + .5 * zn^2)
> zn <- qnorm(0.025)
1/n2 * (0 + .5 * zn^2) + zn * sqrt(1/n2 * p * (1 - p))
[1] -0.05457239

Comment: Although the Wikipedia article and the NIST page both reference the same paper, and give this confidence interval the same name, *they use different formulas.*  The NIST is correct that its formula will not produce negative values, but the Wikipedia formula can be negative. The NIST interval is attributed by Agresti & Coull to Wilson (1927); they call it the "score" interval. They proceed to develop an approximation for the score interval: the Wikipedia formula appears to be this approximation.
Comment: It seems worth remarking that Agresti & Coull ended up recommending a rather simple approximation: add two to $x$ and four to $n$ to estimate $p$ and then compute the (simple) Wald interval $\hat{p}\pm z_{1-\alpha/2}\sqrt{\hat{p}(1-\hat{p})/n}$.  This "confidence interval behaves adequately for practical application for essentially any $n$ regardless of the value of $p$" [p. 124]. Bear in mind, though, that this approximation assumes $\alpha\approx 0.05$; for extreme values of $\alpha$, the Wilson (score) interval is preferable.
Comment: +1. The Agresti-Coull interval is symmetric about the point estimate and thus will certainly yield negative lower limit when you have 0 successes. It is not guaranteed identical to the Wilson interval.
Answer: The lower limit of the formula from your link cannot be negative. But the interval from your link is not the Agresti-Coull interval, it is the Wilson interval. The formulas from your link are for the so called Wilson interval and not the Agresti-Coull interval. Agresti and Coull list the formulas from your link in their paper and call it the score confidence interval (page 120). In the superb paper from Brown et al. (2001) Interval estimation for a binomial proportion, it is called the Wilson interval. It is more commonly know as Wilson interval. They show in their article that the Wilson interval performs well even with small n. In the output of binom.confint the Wilson interval is denoted as wilson and can be calculated by setting the method methods="wilson" in binom.confint. Here is the R code for the (modified) Wilson confidence interval:
n <- 5
x <- 0

alpha <- 0.05

p.hat <- x/n

upper.lim <- (p.hat + (qnorm(1-(alpha/2))^2/(2*n)) + qnorm(1-(alpha/2)) * sqrt(((p.hat*(1-p.hat))/n) + (qnorm(1-(alpha/2))^2/(4*n^2))))/(1 + (qnorm(1-(alpha/2))^2/(n)))

lower.lim <- (p.hat + (qnorm(alpha/2)^2/(2*n)) + qnorm(alpha/2) * sqrt(((p.hat*(1-p.hat))/n) + (qnorm(alpha/2)^2/(4*n^2))))/(1 + (qnorm(alpha/2)^2/(n)))

#==============================================================================
# Modification for probabilities close to boundaries
#==============================================================================

if ((n <= 50 & x %in% c(1, 2)) | (n >= 51 & n <= 100 & x %in% c(1:3))) {
  lower.lim <- 0.5 * qchisq(alpha, 2 * x)/n
}

if ((n <= 50 & x %in% c(n - 1, n - 2)) | (n >= 51 & n <= 100 & x %in% c(n - (1:3)))) {
  upper.lim <- 1 - 0.5 * qchisq(alpha, 2 * (n - x))/n
}

upper.lim
[1] 0.4344825

lower.lim
[1] 3.139253e-17

Here, the lower limit is clearly 0 (the remaining is a numerical error). The Wilson interval in the output of binom.confint can be calculated by setting the option methods="wilson" and this is the same as the one we've calculated above:
library(binom)

binom.confint(x=0, n=5, methods="wilson")

  method x n mean        lower     upper
1 wilson 0 5    0 3.139253e-17 0.4344825

The function binom.confint implements the formulas given on the Wikipedia page for the Agresti-Coull interval:
n.hat <- n + qnorm(1-(alpha/2))^2

p.hat <- (1/n.hat) * (x + (1/2)*qnorm(1-(alpha/2))^2)

upper.lim2 <- p.hat + qnorm(1-(alpha/2))*sqrt((1/n.hat)*p.hat*(1-p.hat))

lower.lim2 <- p.hat - qnorm(1-(alpha/2))*sqrt((1/n.hat)*p.hat*(1-p.hat))

upper.lim2
[1] 0.4890549

lower.lim2
[1] -0.05457239

They are the same as the ones by binom.confint with the option methods="ac":
library(binom)

binom.confint(x=0, n=5, methods="ac")

         method x n mean       lower     upper
1 agresti-coull 0 5    0 -0.05457239 0.4890549

Comment: Not so; it's a surprisingly difficult problem and smart people have proposed different solutions from different views of what is most important. Computation is a secondary issue. No one obliges users to ask for two-sided confidence intervals here. All the methods proposed try to use defensible logic for different intervals. See Brown, L. D., T. T. Cai, and A. DasGupta. 2001. Interval estimation for a binomial proportion. Statistical Science 16: 101–133 for a superb review.
Comment: @PeterFlom `binom.confint` doesn't use the formulas that the OP linked. The function uses those the formulas given on the Wiki page an those clearly can be negative. So there's nothing wrong with the function, it just uses a different formula.
Comment: I see your point. As I recall, the Agresti-Coull method was explicitly promoted as something easy to teach and to calculate. The approximation was justified as mostly almost as good as more accurate approximations but simpler. From 1998 to 2013 a lot has changed. When every student has a laptop, it does now seem a little quaint. I tend to use the Jeffreys method, don't know the formula, but know where to look it up. Knowing how to do it by hand doesn't seem important.
Comment: When I tried binom.confint(0, 5, .95) I got a negative LL. Something is wrong.
Comment: thanks, seems silly to compute such approximations this day in age...
Comment: I'm okay with there being multiple solutions to binomial confidence intervals, but choosing between an approximation to the Agresti-Coull interval estimator and the actual Agresti-Coull interval estimator shouldn't be that controversial.

I can understand using the approximation when working with analytical expressions, but for a function that computes the interval on data, why would anyone ever bother with the approximation?


Azure Automation Graphical Runbook - Can't Execute other Runbooks in Automation Account as distinct canvas Activities?

Question: The graphical editor UI appears to allow adding Workflow Runbooks (only; Native PS do not appear), however, this breaks the GraphRunbook definition/execution.
When I try to either Test or Publish the runbook, I receive the error in the image. (Also strange, this error message has been rendering in a combination of Spanish for the first part, and English for the second half.)
Are other runbooks in the Automation Account technically not supported.. yet?

testtwo code:
<code>workflow testtwo
{
    [outputtype([string])]
    [cmdletbinding()]
    param()

    write-output "testtwo runbook output"
}
</code>
Answer: The error message you are getting is from a live site issue that we are currently actively working to resolve.
Comment: Thanks for the heads-up Chris!
Answer: I've managed to get this to work in a relatively counter-intuitive manner. (At least, counter-intuitive to how non-graph Workflow runbooks are parsed for dependency execution to copy runbooks to workers).
Rather than add the Runbook to the canvas, I simply added the call to the other runbook in the code editor configuration for MyCodeActivity.

Based on the ReadMe.docx bundled with Orchestrator.GraphRunbook.Model.dll (Azure Automation Graphical Authoring SDK), combined with the learning experience here, specifically WRT InlineScript activities (which, afaik is essentially what the Code Activity is translated to), I would not expect to be able to execute another runbook from within the context of InlineScript because (from the ReadMe)..

the execution engine will treat the provided block as a black box,
  and will make no attempts to analyze its content, except for the very
  basic syntax check.

.. which in the case of Native PS runbooks, means they don't get copied to the worker. Unfortunately I never tested executing peer workflow runbooks (that weren't referenced elsewhere so they would be copied to the worker), partly because the assumption was that code inside InlineScripts is not parsed for dependent runbooks, but maybe that's only for Native references (seems a dubious distinction to me)?
Anyway, the above appears to be a workaround.
However, I was hoping that the runbooks would be treated as first-class-citizens on the design canvas (and in the resulting serialized model) rather than being locked up inside a script activity, because I'm working on fishing dependencies out of the definition for automated CI/CD deployment in dependency order. (That said, I've already got a rough pass at the dependency checking for normal scripts, so that should suffice - just means more parsing.)


Solutions of the equation $(m! + 2)\sigma(n) = 2n \cdot m!$ where $5 \leq m$

Question: Are there any pairs of natural numbers $(m, n)$, with $5 \leq m$, other than $(5, 15128)$ and $(6, 366776)$, that satisfy the condition $(m! + 2)\sigma(n) = 2n \cdot m!$, where $\sigma(n)$ denotes the sum of divisors of $n$ and $m!$ denotes the factorial of $m$?
This question arises from the theory of immaculate groups (or, equivalently, Leinster groups). An immaculate group is a group, such that its order is equal to the sum of all orders of its proper normal subgroups.
It is easy to see, that if $A$ is a non-abelian simple group then $A\times\mathbb{Z}_n$ is immaculate iff $(|A|+1)\sigma(n) = 2|A|n$. Two well known examples of immaculate groups of that form are $A_5\times\mathbb{Z}_{15128}$ and $A_6\times\mathbb{Z}_{366776}$. In terms of immaculate groups this question thus can be reworded as:
"Does there exist any immaculate group of the type $A_n \times \mathbb{Z}_n$ other than those two?".
I checked this condition for all $n \leq 10000$ and $5 \leq m \leq  7$ but found nothing.
Any help will be appreciated.
A similar question about $M_{11}$:
Are there any natural numbers $n$ that satisfy the condition $7921\sigma(n) = 15840n$?
Answer: The equation can be written as
$$
\Bigl(\frac{m!}{2}+1\Bigr)\sigma(n)=n\,m!.
$$
Since $m!$ and $m!/2+1$ are coprime, $n$ is a multiple of $m!/2+1$. I have looked for solutions of the equation
$$
\sigma\Bigl(k\,\Bigl(\frac{m!}{2}+1\Bigr)\Bigr)=k\,m!
$$
for $5\le k\le20$, $1\le k\le10^6$. This search provided so far a new solution:
$$
m=10,\quad n=691\,816\,586\,092
$$
Answer: $$m=7 \; \; , \; \; \; n  = 5919262622 =  2 \cdot 7^2 \cdot  13 \cdot  19 \cdot  97 \cdot  2521 $$
<code>=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

m = 5

n = 15128 =  2^3 31 61  sigma 29760 =  2^6 3 5 31

  multiplier   k   248 =  2^3 31

120 =  2^3 3 5         122 =  2 61

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

m = 6

n = 366776 =  2^3 19^2 127  sigma 731520 =  2^7 3^2 5 127

  multiplier   k   1016 =  2^3 127

720 =  2^4 3^2 5         722 =  2 19^2

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

m = 7

n = 5919262622 =  2 7^2 13 19 97 2521  sigma 11833829280 =  2^5 3^2 5 7^3 13 19 97

  multiplier   k   2347982 =  2 7^2 13 19 97

5040 =  2^4 3^2 5 7         5042 =  2 2521

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
</code>
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=


Expose some administrative functions on the front-end

Question: I'm developing a web-app for managing non-profit organizations by extending the functionality of the Drupal CMS. What I want is to have only one administrator account (call it super-admin if you prefer), which should be used only by the developer, next there will be a set of roles (coordinator, director, employee).
The idea is that non of those should be able to perform administrative tasks that may broke the site functionality (like managing blocks or menus), but not just that, to provide a cleaner and more compact interface I would like to expose some functions of the admin side to the front-end (accessible only for determined roles), for example, the coordinator should be able to change the role of an employee in order to upgrade him to director.
Is that possible?
Answer: Your question is a little broad -- anything is possible given time, effort and perseverance!
I find the Role Delegation module and similar modules help to give out permissions to trusted users.
I also have been creating an Administrative Panel page using the Panels module with embedded Views and Blocks for centralized site admin options for users. I usually call this page the staff dashboard for my admin-type users.
Without specific problems you're having, these general tips are all I can provide. Happy coding!


Why do I get a Drupal\Core\DependencyInjection\ContainerNotInitializedException exception error?

Question: I am using Drupal 8.1.3, Drush 8.1.7, and PHP 5.6.2 on a Mac OS X.
I've installed a fresh Drupal 8 site demo from Zircon on a local MAMP stack. When I try to run watchdog show, and some other commands, I get the following error:

Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container. in Drupal::getContainer() (line 129 of /Applications/MAMP/htdocs/example/docroot/core/lib/Drupal.php).

I was able to run the following commands successfully:
drush cr
drush version
drush status

I've just updated to latest version of drush, but this is my first time seeing this error.
Also, drush pm-update returns:

Command pm-update needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.

Edit/Update:
Here is the output of drush status:
Drupal version         :  8.1.3
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  ******
 Database name          :  ******
 PHP configuration      :  /Applications/MAMP/bin/php/php5.6.2/conf/php.ini
 PHP OS                 :  Darwin
 Drush script           :  /usr/local/bin/drush
 Drush version          :  8.1.7
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/MAMP/htdocs/example/docroot
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default
 Sync config path       :  sites/default/files/config_pHswhbzOqqMuWn7c6kYMbap6DKcyXxItrvbtsCQeJYoQ04xTi19pOZywbF8KZ8Wrx43VrLsVMw/sync

The user interface does work.
Update: I checked some of my other projects (Drupal 7 and 8 sites), for which drush worked perfectly fine on, and they are throwing errors with the same Drush command, which tells me it's probably not a Drupal 8 problem but probably due to changes I made on my dev platform. I had installed Composer and upgraded Drush, and other related changes.
Comment: Hard to provide any useful hints without seeing a backtrace. the UI works? You could try to debug it, see e.g. https://www.lullabot.com/articles/debugging-drush-commands-with-xdebug-and-phpstorm. what is the actual output of drush status (make sure to mask any possibly secret info like passwords or so)
Comment: The backtrace is hundreds of lines long so I am linking it here: https://docs.google.com/document/d/1ovvZwKom-JXbcTn0vmp8B1_-Mlv4-WCNBUsIyyPkDoA/edit?usp=sharing
Answer: I had the same problem with Drush throwing an exception for a test site on localhost. I was able to access the site from the browser, from where I didn't get any error message, not even a message from a exception handler. This puzzled me, since the site was clearly working.
It started to work again when I changed the file permissions for the Drupal files. The user account I was using to execute the command line was missing the permission to write in some directories.
Comment: Do you execute the command line using the same user/group used to run the web server?
Comment: You need to change the file permissions too. I don't recall on which directories I changed them, but I recall it was the write permission for the user account I use to run the command line on my Mac Mini.
Comment: I checked that the user is the same. I also checked some of my other projects, which were working fine, which are now throwing the same error with this drush command. This tells me that it's something I changed on my computer or dev environment and not related to Drupal. I had updated Drush, installed composer and created a symlink to mysql for my convenience. Could it have been any of those things?
Comment: I ran `ps aux | egrep '(apache|httpd)'` and found the the user was different. I `sudo chown -R [user] [docroot]` but I still get the error.
Comment: What is curious is that my other projects, which I didn't touch today, are also throwing errors now. I think this has to go beyond file permissions within one Drupal installation. Is there a common Drush file between them all that needs permissions set?
Comment: There are the files Drush uses. Where those files are depends from how you installed Drush. Using `composer global require drush/drush`, they are in ~/.composer/vendor/drush/drush, at least on macOS.


Foco no ultimo caracter Jquery

Question: Preciso que quando o campo receba o foco, o cursor fique no ultimo caractere.
Da forma como está o cursor fica no início do campo mesmo que o campo não esteja vazio.
function gravaObs(unidadeObs) {
    var gasObs = $('#obsGas_'+unidadeObs).val();
    swal({
        title: "Inserir Observações",
        html: '<input type="text" id="obsCampo'+unidadeObs+'" class="col-xs-12 form-control" value="'+gasObs+'" />
',
        confirmButtonText: "Salvar",
        confirmButtonColor: "#5cb85c",
        cancelButtonText: "Cancelar",
        cancelButtonColor: "#d9534f",
        showCancelButton: true,
        onOpen: function () {

            $('#obsCampo'+unidadeObs).focus();

            $('#obsCampo'+unidadeObs).on('focus', function() {
                var pos = this.value.length * 2;
                this.setSelectionRange(pos, pos);
            });
        }
    }).then(function(){
        var resultado = $('#obsCampo'+unidadeObs).val();
        console.log(resultado);
        $('#obsGas_'+unidadeObs).val(resultado);
    }).catch(swal.noop);
}

Answer: Usa o .setSelectionRange e dá-lhe um numero maior que o comprimento do input.
Algo assim:

$("#obsCampo").on('focus', function() {
  var pos = this.value.length * 2;
  this.setSelectionRange(pos, pos);
});

$('button').click(function() {
  $("#obsCampo").focus()
});

// ou de 3 em 3 segundos
setInterval(() => $("#obsCampo").focus(), 3000);

<input id="obsCampo" value="algum texto" />
<button>Clica aqui para focar o input</button>
Comment: Usando botao ele funciona mas como o foco chega no campo atraves de uma função nao funcionou.
Comment: @EzequielTavares deves estar a fazer algo errado. Dá uma olhada à resposta agora com um exemplo de função após 3 segundos.
Comment: Editei a pergunta com o codigo completo já com as alterações que testei.
Comment: conforme está ele recebe o foco atraves de uma função
Comment: @EzequielTavares com mais código agora percebo o teu problema melhor. Duas coisas: `1-` Estás a chamar o `.focus()` antes do auscultador de eventos: tem de ser ao contrário. `2-` Como esse input é criado dinamicamente tens de usar delegação. **Exemplo:** http://jsfiddle.net/Sergio_fiddle/e4kv80pm/
Comment: perfeito sergio... funcionou redondinho inclusive no IE. abraço
Answer: Sempre que receber o foco, seja por click, tecla TAB ou outro, o cursor estará posicionado após o último caractere:

$("#obsCampo").on("focus click",function(){
 var pos = this.value.length+1;
 this.setSelectionRange(pos,pos);
});

<input type="text" id="obsCampo" value="texto" />

Foco no ultimo caracter Jquery


Choosing the dimension in PCA

Question: Suppose that a dataset $(x_1, \cdots x_N) =X \in \mathbb R^{d \times N}$ gives rise to the PCA (principal components analysis) result $\tilde X^\top \tilde X = U^\top DU$ where $\tilde X = (x_1 - \bar x, \cdots x_N - \bar x)$ is the centered matrix with $\bar x = \frac1N (x_1 + \cdots + x_N)$, $U$ is a symmetric matrix, and $D = \text{diag}(\lambda_1, \cdots \lambda_N)$ is a diagonal matrix of the principal values. Here, we may assume that $\lambda_1 \ge \lambda_2 \ge \cdots$.
Question. How does one choose a number $k$ representing the intrinsic dimension of $X$ so that we only use the top $k$ principal components (the column vectors from $U$)?
It seems that there are a few ways to do this, for example by taking the maximum $k$ such that $\lambda_k \ge \epsilon$, where $\epsilon \ge0$ is an error threshold. Analogously, one can bound the tail sum instead: $\lambda_{k+1} + \cdots + \lambda_N < \epsilon$, or the $L^2$ analogue: $\sqrt{\lambda_{k+1}^2 + \cdots + \lambda_N^2} < \epsilon$. There are more involved methods too, such as Minka's NeurIPS paper. However, I am curious of what is the most canonical method, either in practice or in theory.
Comment: Although a scree plot is not necessarily the best approach, virtually all related threads mention it, so it makes a good search term: https://stats.stackexchange.com/search?q=scree+plot.  Perusing them will reveal there is no "most canonical method," because applications and objectives vary.
Answer: It's customary to set $k=\#\{\lambda_j>1\}$, that is the number of eigenvalues greater than one.  Other approches can be taken, which I use a lot, but I also use the greater-than-one criteria a lot.
Mathematically, the notation can also be written in the form:
$k=\sum_{j=1}^N I(\lambda_j>1)$
where $I=1$ if $\lambda_j>1$, and zero otherwise.
Comment: The literature is clear that this is not a good general procedure.
Answer: An approach for choosing the number of dimensions to keep is to consider the amount of variance explained by each principal component.
We know that the variance of the data is equal to the diagonal sum of matrix $D$, i.e. the sum of the eigenvalues $Var(X)=\sum_{I} \lambda_{I}$. However, each eigenvalue corresponds to a principal component.
So, you can put in decreasing order the eigenvalues and start calculating their cumulative sum. Continue calculating the cumulative sum until there is no significant change into the sum.
For example, let $\lambda_{1}=15,\lambda_{2}=2,\lambda_{3}=0.2,\lambda_{4}=10$. Then $\lambda_{1}>\lambda_{4}>\lambda_{2}>\lambda_{3}$.
You start calculating the cumulative sum $\lambda_{1}+\lambda_{4}=25$, then you calculate $\lambda_{1}+\lambda_{4}+\lambda_{2}=27$. So, the variance explained by the pricipnal component that corresponds to $\lambda_{2}$ is small. So, we can keep only two principal components the ones that corresponds to $\lambda_{1}$ and $\lambda_{4}$.

Choosing the dimension in PCA


How to add existing product variations to a new product?

Question: I have products with the same variation.
From product edit form I can only add new variation.
In variations field form setting i haven't "Allow users to add existing products."

how can i have this option or How can add existing variations?
Answer: The option you're looking for is not present on purpose (and the widget itself is different despite how it worked in Drupal 7). Every product has its own variations that cannot be shared, so there's no way to reference the same variation from multiple products.
If you need to sell the same thing from multiple contexts, what you probably need is some other entity that references the same product, not a standalone variation. Products:variations have a very clear parent:child relationship ... they're "variations" of the main "product".
Answer: I'm not as familiar with D8 commerce but should be the same. If you edit the product field on your product display content type you can tick "Allow users to add existing products."
That will allow the option to add existing variants
Comment: I updated my question. I haven't that option.
Comment: Also, that would break Drupal Commerce and it's data model. Variations have a reference to their product. So overriding this feature would break unexpected things.


React Native install [Mac M1]

Question: I m installing React-native to my mac book m1
But i think, i installed all(npm, jdk, node, rosseta, cocoapad, vscode, android studio, xcode and so on...). But if i run command(npm start), there is no dir (ios, android and so on...)
'node_modules    package.json    yarn.lock'
how can I build react native example?
if run command (npm react-native run-ios)
error iOS project folder not found. Are you sure this is a React Native project?.

info Run CLI with --verbose flag for more details.
I tried delete and reinstall npm, node, react-native...
But it's not working. there is no directory like ios/ , android/
I don't know what should i do?
Comment: What command have you used to create your react native project?
Comment: I tried ''react-native start"
Answer: Use this command to create react native project :
npx react-native init project-name

Comment: use the exact command as I have mentioned above
Comment: I already that command. But Error is occur like below.
```
Using yarn v1.22.19
...
yarn add v1.22.19
...
warning "react-native > @react-native-community/cli > @react-native-community/cli-
...
warning " > email@example.com" has unmet peer dependency "email@example.com".
[4/4]   Building fresh packages...
success Saved 1 new dependency.
...
node:internal/readline/emitKeypressEvents:71
            throw err;
            ^
TypeError: cli.init is not a function
    at run (/usr/local/lib/node_modules/react-native-cli/index.js:302:7)
 ...
```

React Native install [Mac M1]


Bounded sequence with ratio of consecutive terms going to 1 is convergent?

Question: Let $(x_n)$ be a sequence satisfying

$1 \leq x_n \leq 2$ for all $n \geq 1$,
$\lim_{n\to\infty} x_{n+1}/x_n = 1$.

Is this enough to show that $(x_n)$ converges?
This is motivated by the case where $x_n$ is the ratio of successive Fibonacci numbers , as well as this similar example. In both cases, we can show convergence but making use of the actual definition of the sequence, not simply the two properties listed above.
I have attempted to show that this sequence is Cauchy but the details elude me.
Answer: Let $(x_n)_{n\geq 1}$ by
$$ x_n = \frac{3+\sin(\log n)}{2}. $$
It is obvious that $1 \leq x_n \leq 2$. Moreover,
$$ \left|\frac{x_{n+1}}{x_{n}} - 1\right| \leq \frac{1}{2}\left| \sin(\log(n+1)) - \sin(\log n)\right| \leq \frac{1}{2}\log\left(\frac{n+1}{n}\right) $$
by the mean-value theorem and this bound converges to $0$ as $n\to\infty$. So $x_{n+1}/x_n \to 1$ as $n\to\infty$. Of course, it is clear that $x_n$ does not converge as $n\to\infty$.
Answer: No. For example, we can take $x_n=x_{n-1}\pm\frac 1n$, and choose the signs to ensure that $1\leq x_n\leq 2$. This will also ensure the ratios tend to $1$, since $\frac{x_{n+1}}{x_n}=1\pm\frac1{nx_n}$, and $nx_n\to\infty$. We can also choose signs such that the sequence gets arbitrarily close to $1$ and to $2$ each infinitely often, since $\sum\frac1n=\infty$.


Group by quarter (datepart) returns multiple rows with same quarter

Question: I'm trying to return a count for the total number of records in the table HISTORY grouped by their quarter and year. Currently I have:
SELECT DISTINCT (CAST(DATEPART(year, CREATE_DATE) AS char) + ' Qtr' +
                CAST(DATEPART(quarter, CREATE_DATE) AS char)) AS Period,
       COUNT(ID)
FROM HISTORY
GROUP BY CREATE_DATE
ORDER BY Period;

But I'm getting duplicate rows with the same quarter and year. I'm also getting a total of records counted that's lower than the total records in the table. Here's a sample sql fiddle in case that helps identify the problem.
I wouldn't have thought I'd need to specify DISTINCT in the period column either, but when I don't I get even more dupes... which I'm guessing is part of the same root problem.
Comment: Look closely. The code does what you wrote, not what you want. You group by create_date so you get a row for each unique value of create_date. The fact that you only display a value composed of year and quarter does not affect your grouping. You need to group by year and quarter.
Answer: The problem ist that you are grouping by CREATE_DATE but want to group by year and quarter:
SELECT
  DATENAME(year, CREATE_DATE) + ' Qtr' + DATENAME(quarter, CREATE_DATE) AS Period,
  COUNT(*) AS NumberOfRecords
FROM HISTORY
GROUP BY DATENAME(year, CREATE_DATE), DATENAME(quarter, CREATE_DATE)
ORDER BY Period;

Comment: I tried grouping by the column that I had named (like you can do `ORDER BY`) but that just wouldn't compute. I didn't think to specify multiple values to group by, which was dumb of me!

Also thanks for pointing out the `DATENAME` function! That'll save some space!
Comment: @IsaacReefman The only reason for the sorting by the column name works is that it takes place in the very end after calculating the result. The grouping takes place long before, so you would have to repeat the formula in the GROUP BY clause (which wasn't too bad, because SQL Server is clever enough to evaluate the expression only once). As you see, grouping by multiple values isn't "dumb", instead sometimes it's useful. You wanted to see the number of records by quarter, but of course the quarter belongs to a year. Grouping by the date was too granular. Thank you, happy that you liked it!


Positive-Definite Matrix Question

Question: I want to prove that the matrix is positive definite using the fact that:

If $A$ is symmetric and $\langle x, Ax \rangle$ > $0$ for a nonzero vector $x$ then $A$ is positive.
So I have the matrix : $A$ =$\begin{bmatrix} 10&-3&0\\-3&10&0\\0&0&9\end{bmatrix}$.
  And I already checked that $A$ is symmetric, as $A=A^T$
and then I also compute that
$\langle x, Ax \rangle = 10a^2+10b^2+9c^2 -6ab$,  so is it that true that eventhough I have one negative number (-6ab), $\langle x,Ax \rangle$ is still positive ?
Comment: have you had multivariable calculus ?
Comment: No. I am not sure what is that?
Comment: Derivatives of functions with multiple variables are a part of that course. It gives a general tool to show positive definiteness of such things. However, @ComFreek gave you a more elementary answer, which requires to be able to fiddle with numbers. (But it's more elegant)
Answer: Having negative terms in the resulting polynomial does not necessarily mean that the overall polynomial function attains values $\leq 0$. Indeed, we can prove it to be strictly positive for every nonzero vector $x = (a,b,c)^T$.
So in your last step you reached
$$\langle x, Ax \rangle = 10a^2 + 10b^2 + 9c^2 - 6ab$$
Do you notice this suspicious mixed term $-6ab$? That should ring a bell! It commonly occurs in the identity $(u-v)^2 = u^2 - 2uv + v^2$.
Let's see if we can manipulate it to reach the LHS of the identity:
$$
\begin{align*}
 &10a^2 + 10b^2 + 9c^2 - 6ab\\
 =& ??? + ??? + 9c^2 + 3(a^2-2ab+b^2)\\
 =& 7a^2 + 7b^2 + 9c^2 + 3(a^2-2ab+b^2)\\
 =& 7a^2 + 7b^2 + 9c^2 + 3(a-b)^2
\end{align*}
$$
Usually, I would do the step with $???$, but I explicitly listed it for you here. In this step you just attempt to write $-6ab$ in the form of the identity I mentioned and then try to adjust the other summands, so that we indeed have a valid equality from the previous line.
Can you now prove how the expression on the last line is always $> 0$ for every $x = (a, b, c)^T \neq 0$?
By the way, I think in general going the eigenvalue way, i.e. a symmetric matrix is positive definite iff. all eigenvalues are $> 0$, is more systematic and easier.
Comment: Not anymore, you have the sum of three squares. the square of a number is always positive ^^
Comment: but in you still have a negative term, namely 3(a-b)^2
Comment: Take a look at 3*(3-10)^2. Compute it, and you'll find 3*49 > 0 I mean, go ahead, plug in some numbers, and convince yourselt. Alternatively, Take a look at the graph of x^2 and you'll see that no matter the x, it's positive. Replace that x with a-b and you see that it is always positive.
Comment: Thank you very much!
Comment: @Kai Note though, that if we had reached the expression $a^2 + b^2$, then the matrix would *not* be positive definite since for $x = (0, 0, 10)^T$ we have that $\langle x, Ax \rangle = 0$. But here, if $\langle x, Ax \rangle = 0$, we can conclude that every summand of our expression is $0$, which implies $a = b = c = 0$.

Positive-Definite Matrix Question


How to Get Index of a Selected Item From List Object

Question: I need to get index of a selected object from list, in my code:
let index = this.List.map(function (x) { return x.ID }).indexOf(this.Item);

Every time I'm mapping, is there any other solution for this without mapping.
Comment: And how your `List` looks like?
Answer: You can do that with findIndex.
let index = this.List.findIndex(function (x) { return x.ID == this.Item });

With arrow function.
let index = this.List.findIndex(x => x.ID == this.Item);

Answer: You could use lodash findIndex method like this :
let index = _.findIndex(this.List, item => item.ID === this.Item.ID)

See documentation for more info.


Adding the if condition quits the android app in telephony manager

Question: I am trying to make a simple android app in which there is a toast message containing the number of the incoming call. I have stored the number in a string variable. When I display just the toast, it works fine but before the toast, if I add a simple if condition comparing the number to another string, the app quits. The required permissions are given. Can someone help me?
This Works:
public void onReceive(Context context, Intent intent) {

        String incomingNumber = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
        Toast.makeText(context, incomingNumber, Toast.LENGTH_LONG).show();
    }

This Does not Work (App quits)
public void onReceive(Context context, Intent intent) {

        String incomingNumber = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
          if(incomingNumber.equals("+919999999999"))
           {
              Toast.makeText(context, "Call from Mom", Toast.LENGTH_LONG).show();
           }
           else
           {
              Toast.makeText(context, incomingNumber, Toast.LENGTH_LONG).show();
           }

    }

Comment: "the app quits". Do you get an error? have you debugged your code? what is that value, a default? I don't see anything in that condition or that code that would just "quit"
Comment: Does this answer your question? [Unfortunately MyApp has stopped. How can I solve this?](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this)
Comment: Maybe if you change .equals() to == it will work
Comment: @Lenin not if it's java code. for javascript, that would be fine, but it isn't javascript
Comment: it won't @Lenin that's just going to cause more bugs.
Answer: It sounds a little silly but I just wrapped my "if" condition in a try-catch block and it solved the problem. I am not used to programming in JAVA so it took me a lot to figure out this simple thing. Thank You All for providing me with suggestions :)


lighttpd redirect certain links to certain urls

Question: Could someone tell me how / why is this redirect not working?
$HTTP["host"] =~ ".*\\.mydomain\\.com" {
    url.redirect = (
        "/index\.php\?pg=mysql" => "http://mydomain.com/lean-webhosting/mysql-clustering/",
        "/index\.php\?pg=cloud_uitleg" => "http://mydomain.com/lean-webhosting/cloud-uitleg/"
    )
}

Someone any idea?  THanks!
Answer: You probably need to replace ".*\\.mydomain\\.com" with ".*\.mydomain\.com" and restart lighttpd. If that doesn't help: please explain how the redirect isn't working for you.
Comment: Thaks for the regexp Asgar. That was indeed one of the problems. I've excluded the index.php part and it worked.
Answer: $HTTP["host"] =~ ".*\.muntinternet\.nl" {
    url.redirect = (
        "/\?pg=mysql" => "http://muntinternet.nl/lean-webhosting/mysql-clustering/",
        "/\?pg=cloud_uitleg" => "http://muntinternet.nl/lean-webhosting/cloud-uitleg/"
    )
}

I needed to exclude /index\.php
Thanks!
Comment: Do not forget to accept your answer then. Btw, in the future, add more information in your question instead of just the configuration lines that doesn't work. It would have been interesting here to see which **real** url you want to redirect to where.
Comment: hi j0k. I just added real links to illustrate the situation. Thanks for letting me know to accept the answer as solved. It won't let me untill tomorrow.
Comment: Well, I do not want to see real path to your website :) You still can use `example.com`. But, here we need a real example of url you want to redirect. For example, `http://example.com/?pg=mysql` So it will be easy to see that your redirect won't work if the rule start with `index.php`, you see?
Comment: There is no http://muntinternet.nl/?pg=mysql. There is http://muntinternet.nl/index.php?pg=mysql  however non of these should be used if redirecting these two specific urls. THe same example as you can see above is used within lighttpd.conf.
Comment: I think you should remove the first `/` from `"/\?pg=mysql"` (and the other line too) then, both http://muntinternet.nl/index.php?pg=mysql & http://muntinternet.nl/?pg=mysql will be redirected


Probabilities of test result scores

Question: A Big 5 personality test has five orthogonal normally distributed scales.
What I would like to know is the likelihood of exactly zero, one, two, three, four or five scores outside of the median. E.g how likely is it that a test taker has one score higher than one standard deviation above the mean, and one score less than one standard deviation above the mean?
This requires a firmer grasp of probability calculus than I have, so I simulated using R:
<code>mydata <- matrix(rnorm(50000,0,1),ncol=5)

res <- apply(abs(mydata) > 1,1,which)

res <- sapply(0:5,function(X){length(which(sapply(res,length)==X))})/100

names(res) <- c(0:5)

pie(res)
</code>

I don't feel that this makes any sense. The likelihood of exactly one and exactly two scores outside the mean is the same?
Any and all suggestions or comments appreciated. Thank you.
Comment: Conceptually, they are; in practice test scales will correlate. But for now I'd like to leave that out of the equation.
Comment: Is it reasonable to assume that the values on the five scales are independent of one another?
Answer: If the scores are approximately normally distributed, that implies a probability of 0.68 that a given score falls within one standard deviation of the median and, so, a probability of 0.32 that a given score lies more than one standard deviation away from the median (above or below).
Assuming the scores are independent of one another, we can use those values to derive the quantities you're after. The probability that all five scores are within 1 s.d. is the product of the probabilities of the five independent events, so 0.68^5, or 0.145.
The probability of exactly one score lying more than 1 s.d. away from the median is the product of the probability that four lie within 1 s.d. (0.68^4) and the probability of a single score landing more than 1 s.d. away (0.32), which is 0.68^4 * 0.32 = 0.068. But there are five ways that can happen (once for each question), so the total probability of any single answer being more than 1 s.d. away from the median is 0.34.
Now you start to see the pattern.

The probability that any pair of scores falls more than 1 s.d. away while the others land within that range is 0.68^3 * 0.32^2, or 0.032, times the 10 ways that can happen (AB vs. CDE, AC vs. BDE, etc.), which equals 0.322.
The probability that any trio of scores fall more than 1 s.d. away is 0.68^2 * 0.32^3, or 0.015, times the 10 ways that can happen, which is 0.152.
The probability for a quartet of scores is 0.68 * 0.32^4, and there are five ways that can happen, which produces 0.036.
The probability that all five scores are at least 1 s.d. away is 0.32^5, which is 0.003.

So I can't tell exactly what values lay behind your pie chart, but there are two slices that are approximately equal: exactly one and exactly two. That may seem counterintuitive, but then remember that there are twice as many ways to get pairs of outlier answers as there are ways to get single outliers, and then I think it makes a little more sense.
Comment: Thank you for your comprehensive answer! This is very helpful.

Probabilities of test result scores


How to catch twig errors and display custom 500 error page?

Question: I have a patch to add some custom handling of 500 errors that run through the code in errors.inc, so that it returns a themed page in those cases.
This works well in certain conditions, but I have an error that occurred with a misnamed twig template, so I got
Twig_Error_Loader: Template "@mytheme/search-result/search-result--event.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "@mytheme/search-result/search-result--event.twig" in the Drupal theme registry.) in "themes/custom/mytheme/templates/node/node--admissions-event--search-result.html.twig" at line 1. in Twig_Loader_Chain->getCacheKey() (line 129 of /var/www/mytheme-qa/site/vendor/twig/twig/lib/Twig/Loader/Chain.php).

After some digging I see that this error is generated here:
/core/lib/Drupal/Core/Template/Loader/ThemeRegistryLoader.php
if ($throw) {
  throw new \Twig_Error_Loader(sprintf('Unable to find template "%s" in the Drupal theme registry.', $name));
}

The problem is this type of error isn't handled by Drupal.  It's a Twig engine error.  So an exception subscriber doesn't catch this.
Any suggestions on how to return a themed 500 page in fatal error cases like this at the theme layer?
Answer: Just checked, there is no special handling of Twig exceptions in core, so they end up in FinalExceptionSubscriber. You can add a custom exception subscriber catching Twig_Error_Loader or Twig_Error_Syntax and return a themed response (though you might need to theme this yourself when the theme layer is broken because of the Twig error).
error.inc has nothing to do with this as long as there is no fatal error not catchable by Symfony (but this would be a failure of the Twig layer, which normally protects you from low level errors)
Comment: Great this works! I still need my patch to errors.inc though, as uncaught fatal errors end up there, but this is working much better than what I previously had, because it's catching additional errors, such as twig errors.


How to get urls in javascript file under playframework 1.2?

Question: I'm using play-1.2.4, but i found the javascript file can't generate urls with the tag:
@{Users.login()}

Indeed i can use
/Users/login

instead , but it will cause problems when i export to war files and run it in tomcat.
Answer: Take a look at the JSAction tag. http://www.playframework.org/documentation/1.2/ajax
The purpose of the jsAction tag is to be able to generate the URLs that you need to call from the routes file. However, these need to be defined inside of your views, as they need to be generated serverside by Play, and not inside a js file.
If you really want to be able to keep most of your code inside of your JS file, then you can generate the method names in your main.html file, and reference from within your javascript file.
example

then you can access this using
loginAction;


MongoDB Mongoose Exclude Results from Query by Boolean Value

Question: Edit
I now realise I have two problems with my query.
1 (My original question):
In Node / Express I'm trying to filter results from a Mongo query by a boolean value. Should be simple enough right? Basically if the profile is not complete, I want to ignore the user.
This is particular part of the query which isn't playing ball:
{profileComplete: {$ne: false}}

I've tried swapping $ne for $nin, but this does't work either.
Am I getting something wrong in that query?
Here's the entire query, in case that's useful:
req.session.query = {$and:
  [
    {learningLanguages: {$in: req.user.spokenLanguages}}, // matches other users' learning languages with the current users spoken language(s)
    {_id: {$nin: [req.user.blockedUsers.split(","), req.user._id]}}, // disregard users who have been blocked by the current user AND the current user him/herself
    {profileComplete: {$ne: false}} // disregard users who haven't completed their profiles yet.
  ]
}

2:
I've also just found out that blocking the own logged-in user from the results isn't working either. That's the last bit of this line of the query: {_id: {$nin: [req.user.blockedUsers.split(","), req.user._id]}}
Just when I though I was getting to grips with MongoDB.
Answer: OK I figured it out. It was working all along, but I had an if statement elsewhere (not very far away!) which was creating a different query. Doh!


CoreGraphics touch custom shape

Question: I have a UIView subclass that draws a circle inside its drawRect:rect method. Now I want to react when the user touches the circle (not the view).
My idea was to get the CGPoint of the touch and ask CGContext if there is something.
Is there a way to check whether there is a fill or stroke? Or can I access the color at this point to see if it is opaque?
I think this must be possible because graphics get drawn to the screen so the system can do it somehow in a low level mechanism..
Any ideas?
Answer: You need to use CGBitmapContextCreate() to create a bitmap context and draw your image in it.
In bitmap context you can access individual pixels and check what color they are in the form of RGBA.

CoreGraphics touch custom shape


jQuery Easing Plugin not working

Question: Can't seem to get this jQuery easing plugin to work!  I saw it on http://easings.net/ and I have a fiddle on http://jsfiddle.net/XqqtN/ with my code
I'm new to this please help!
$("#coolDiv").animate({'top':'-300px'},600,'easeOutBack',function(){
                            $(this).css({'top':'310px'});
Comment: See if this works for you http://jsfiddle.net/Pzzhx/
Comment: i tested the example from @Fabi and it work fine...
Answer: Using the jQuery easing plugin should work:
#coolDiv {
    width: 50px;
    height: 50px;
    position: absolute;
    top: 0;
    right: 0;
    background: yellow;
}

cool

var left = $('#coolDiv').offset().left;

$("#coolDiv").css({left:left}).animate({"left":"0px"}, { duration: 1500, easing: "easeOutBack" });

Note that the main difference is adding { duration: 1500, easing: "easeOutBack" } to the animate function.
Fiddle
Comment: Thanks a lot, that worked great! Just wondering what the left:left means  - For my purposes I changed the code to slide in from the top and also I will have 3 animations so I was changing the variables and the first reference to 'left' in the section of code left:left seems useless.  In the fiddle you will see I replaced this with 'duck' and it worked - just wondering.... http://jsfiddle.net/Pzzhx/1/
Comment: you're getting the offset left of the #coolDiv.. and animate it to the left from that position.. try alert(left) right after var left and youll see the starting value.. so it reads move block from N px to  left:0px, duration 1500 and easing effect "easeOutBack"... glad it worked, if you could please accept it so I can increase my reputation...thanks
Comment: Accpeted - but I still don't understand what the variable where I currently use 'duck' means / does. Thoughts?
Comment: you know, youre right. In this case makes no sense to have it there since youre not adding anything to it (and you already set TOP in your css). But in the previous code, you have not set the LEFT offset, so you need to get it and set it on the css. Try removing the css function and see it goes nowhere..

jQuery Easing Plugin not working


Unable to read whitespaces when reading from a dat file in java

Question: I am trying to read a dat file and store column names.
The first line in the file is separated by spaces.
The following code is unable to split the column names from the line
FileInputStream fis=new FileInputStream("file.dat");
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
String line=br.readLine();``
String k[]=line.split(" ");

if i print k[0] it prints the entire line and the same does not happen if its a text file. What should i do to read the white space
Comment: Would you provide us the content of your `file.dat`? Your code should work well and store words separated with a whitespace (`" "`) to the array.
Answer: It's possible that the fields are separated by whitespace other than the simple " " space. You can try splitting by any kind of whitespace with:
String k[]=line.split("\\s");

If this doesn't work either, the data is not separated by whitespace. Try using a hex editor/viewer to see what the separator character is.
Comment: Perhaps `\\s+` would be a better regex since OP says "The first line in the file is separated by spaces.", `\\s` would include empty strings in the resulting split array. Good point though.


Override _user_mail_notify() to NOT send email on user_save() if user status is changed

Question: I have an external service registering and altering the status of Drupal users, performing user_save() on several occasions depending on the service response.
So i am blocking and unblockiing users and other operations.
My problem is i cant find a descent way to override this code inside user_save()
// Send emails after we have the new user object.
if ($account->status != $account->original->status) {
 // The user's status is changing; conditionally send notification email.
 $op = $account->status == 1 ? 'status_activated' : 'status_blocked';
 _user_mail_notify($op, $account);
}

ideally i would like to have full control on what is going to be sent depending on user role, the account status etc. say for example
// pseudo code
if (user_is_external and statusChanged){
  dont send email
} else {
  send_email
}

Is this possible?
thanks
Answer: Maybe you should take a look at drupal_mail function
// Invoke hook_mail_alter() to allow all modules to alter the resulting e-mail.
drupal_alter('mail', $message);

// The original caller requested sending. Sending was canceled by one or
// more hook_mail_alter() implementations. We set 'result' to NULL, because
// FALSE indicates an error in sending.
if (empty($message['send'])) {
  $message['result'] = NULL;
}

Then hook_mail_alter
From description

$message: An array containing the message data. Keys in this array include:
'send': Set to FALSE to abort sending this email message.
'params': An array of optional parameters supplied by the caller of drupal_mail() that is used to build the message before
  hook_mail_alter() is invoked.

Parameters usually contain $message['params']['account'], so you can abort e-mail sending by role or other way.
Example (not tested) aborting any e-mail to account with specific role:
function MY_MODULE_mail_alter(&$message) {
  $role = 'CUSTOM_ROLE';
  if (!isset($message['params']['account'])) return;
  $account = $message['params']['account'];
  if (is_array($account->roles) && in_array($role, array_values($account->roles))) {
    $message['send'] = NULL;
  }
}

There is an issue then sending custom e-mails, $account contain sender account object, not receiver. But for default notifications this should work. So don't forget to check $message['key'] for default notification types from _user_mail_notify, it always provide $account object mail is sending to:
'register_admin_created': Welcome message for user created by the admin.
'register_no_approval_required': Welcome message when user self-registers.
'register_pending_approval': Welcome message, user pending admin approval.
'password_reset': Password recovery request.
'status_activated': Account activated.
'status_blocked': Account blocked.
'cancel_confirm': Account cancellation request.
'status_canceled': Account canceled.

Answer: The decision not to send email is Not made in the user_save function but rather in _user_mail_notify(). That function checks the variables table.
The only way I see for you to acquire this control (without hacking core) is for you to disable all related user email for the core email functions, and to write your own module using hook_user_insert and hook_user_update.
Comment: And how to control all related user email?
Comment: Several can be disabled at /config/people/accounts. The rest can be disabled with entries in the variables table. The entries will have the form 'user_mail_' . $op . '_notify' and should be set to FALSE. Look at the API entry for _user_mail_notify for a list of the op's.


Private accessible vs Public

Question: I have problems with the encapsulation, and I don't where the problem is. Why can the line be altered after it has been created? This tells me something is wrong in my "line-class" and needs to be encapsulated. Advise would be much appreciated.
When calling "pa.X = 4" and "startpos.Y = 7" this should not change the line for me, but it does. I expect that all the lines are unchanged when the program has finished.
Dotclass:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dot
{
    class Dot
    {
        private int x;
        private int y;

        public Dot()
        {
            this.X = 0;
            this.Y = 0;

        }
        public Dot(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }

        public int X
        {
            get
            { return x; }
            set { x = value; }
        }

        public int Y
        {
            get { return y; }
            set { y = value; }
        }
    }
}

Lineclass:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dot
{
    class Line
    {
        private Dot startdot;
        private Dot enddot;
        private double length;

        public Line(Dot pa, Dot pb)
        {
            this.startdot = pa;
            this.enddot = pb;
        }

        public double Size()
        {
            double a = (double)(enddot.X - startdot.X);
            double b = (double)(enddot.Y - startdot.Y);

            return length = Math.Sqrt(a * a + b * b);
        }

        public Dot Position()
        {
            return startdot;
        }

    }
}

Main:
    using System;
    namespace Dot
    {
        class Program
        {
            public static void Main()
            {
                Dot pa = new Dot();
                Dot pb = new Dot(-10, -10);
                Console.WriteLine("Dot pa, position = (" + pa.X + ", " + pa.Y + ")");
                Console.WriteLine("Dot pb, position = (" + pb.X + ", " + pb.Y + ")");
                Line line = new Line(pa, pb);
                Print("Run 1 off line", line);
                pa.X = 4;
                Print("Run 2 off line", line);
                Dot startpos = line.Position();
                startpos.Y = 7;
                Print("Run 3 off line", line);
            }
            private static void print(string text, Line line)
            {
                double length = line.Size();
                Dot startPos = line.Position();
                Console.WriteLine("\n" + text);
                Console.WriteLine("Längd = {0 :f4} length", length);
                Console.WriteLine("Position = ({0},{1})", startPos.X, startPos.Y);
                Console.ReadLine();
            }
        }
    }

Comment: The problem is that the `Dot` class is mutable. Does it *have* to be? If not, simply make the `set` of `X` and `Y` private. If for whatever reason `Dot` *must* be mutable, you could let `Line` work with a "clone". For example: `public Line(Dot pa, Dot pb) { startdot = new Dot(pa.X, pa.Y); enddot = new Dot(pb.X, pb.Y); }`
Comment: I tried replacing my Line constructor with this one, but value changes
Comment: It is because your `set` of X is public. Even your data menber is private, but you provide a public way for other to change the private x.
Comment: I think your problem is deep copying vs shadow copying.
Comment: Change `public Dot Position()` to `return new Dot(startdot.X, startdot.Y);` -- but maybe your concept of what a dot is is wrong. Why does it have to be mutable? A dot is a dot. It doesn't "move". You don't take the origin (0,0) and move it to become (4,0) for example. (4,0) is another different dot. The *variable* `pa` might at one point be a reference to (0,0) and at some other point be a reference to (4,0). But that doesn't mean that the *value* (0,0) was changed. Like in `int x = 0; x = 4;` you don't change the *value* `0` to suddenly be the *value* `4`.
Comment: You could have a method like `public Dot SetX(double x) { return new Dot(x, this.Y); }` in `Dot` and use it like `pa = pa.SetX(4);`. It's a little bit more cumbersome than just `pa.X = 4;`, but now you can make `Dot` completely immutable (you probably want a `SetX` and maybe even a `SetXY`, too). And immutability is *a good thing*. See Eric Lipperts [articles](https://blogs.msdn.microsoft.com/ericlippert/tag/immutability/) about it for more info.
Answer:
Why can the line be altered after it has been created?

The reason is that class Dot is a reference type, and you want a value type, struct:
  // please, notice "struct"
  public struct Dot {
    // you don't need separate fields, but properties
    public int X {get; set;}
    public int Y {get; set;}

    public Dot(int x, int y) {
      X = x;
      Y = y;
    }
  }

  ....

EDIT: I suggest turning public Dot Position() into property as well:
 class Line {
   ...
   public Dot Position {
     get {
       return startdot;
     }
     set {
       startdot = value;
     }
   }
 }

and so you can "control the angles":
line.Position = new Dot(line.Position.X, 5);

Comment: Thank you for your answer, however Dot needs to be mutable
Comment: @iscilcra: `Dot` is mutable,  `Dot d = new Dot(1, 2); d.X = 123; d.Y = 456;`
Comment: Thanks. Sorry for seeming demanding, but it supposed to be a class and the changes are meant to be made on the Lineclass. I want to control all angles.
Comment: @iscilcra: it seems, that you have to change `public Dot Position()` into *property* for that (see my edit)

Private accessible vs Public


Advantages and disadvantages of EM algorithm vs trust region methods for nonlinear optimization

Question: I have a set of observations X that I believe were generated by a mixture of several probability distributions (specifically, two von mises and one uniform). I'd like to find the maximum likelihood estimate of the parameters of these distributions and their mixing coefficients.
What are the advantages and disadvantages of using the EM algorithm to identify these parameters, versus plugging the likelihood function into a nonlinear programming solver using trust region based methods?
Answer: The EM algorithm is very popular for fitting mixture distributions.
In general, both approaches will converge to a local optimum. A common heuristic for both approaches is to repeat several times from different initialization points.
The nonlinear programming approach would need constraints to be specified. In higher dimensions, this could get complicated (e.g. positive semidefiniteness constraints for covariance matrices). But, it sounds like your distributions are 1d, which simplifies things somewhat. You'd still need to constrain mixture weights to be nonnegative and sum to one, and the widths of component distributions to be nonnegative. The EM algorithm will naturally produce valid parameters for the mixture distribution.
Optimization with trust region methods requires the gradient of the objective function and possibly the Hessian, depending on the method. Gradients of the constraints are required as well. Things will be much faster if you can provide a function to compute these. That would require deriving an expression for the gradient/Hessian, or using automatic differentiation. Otherwise, finite differencing is typically used, which scales poorly with the number of parameters. The EM algorithm doesn't require the gradient.
From an implementation standpoint, the EM algorithm is often described as being very simple, but plugging things into a standard optimization solver sounds even simpler. If gradients/Hessians have to be derived, it may put the two approaches on more even footing in this regard.
Because of the uniform distribution, it seems like your objective function might have some nasty behavior. For example, imagine sliding the uniform distribution to the side. The likelihood won't change at all (the derivative will be zero w.r.t. the location parameter), until a data point falls into or out of the support of the distribution. The likelihood will then abruptly jump to a new value, and the function will be nondifferentiable at this point. This kind of behavior doesn't play nicely with gradient-based optimization algorithms. I don't know how it would affect the EM algorithm.
The EM algorithm can be used in cases where some data values are missing, although this is less relevant in the 1d case.
Possibly of interest:
Why should one use EM vs. say, Gradient Descent with MLE?
What is the difference between EM and Gradient Ascent?
Comment: Why do you say that the EM algorithm doesn't require the gradient? In each maximisation step one needs to find the optimal parameters that maximise the expected log-likelihood. Wouldn't the gradient be helpful in this case?


How to use getch() (from curses library)?

Question: Consider this code:
if(initscr() == NULL) ERROR("Cannot start ncurses mode.\n");

    keypad(stdscr, TRUE);

    cbreak();

    int reply = getch();

    if(reply == 'y')
        printw("yes!\n");
    else if(reply == 'n')
        printw("no!\n");
    else
        printw("invalid answer!\n");

    refresh();

    endwin();

Independent of key that I type, the program closes without print any message.
Can someone explain the behavior of this program? Thanks in advance.
Answer: You call printw() to print one of three messages, then refresh() to cause the message to be displayed. So far, so good.
You then immediately call endwin(), which (depending on your termcap/terminfo settings) will likely clear the screen.
Chances are the message is actually displayed; it just doesn't stay on the screen long enough for you to read it.
Try adding a delay or another getch() call after the refresh() call.
Answer: If you insert a sleep(5) in between your refresh() and your endwin(), you should see better results.  At least, I do.


To SSL or to not SSL

Question: Currently I have a website that serves a lot of mixed content I have the whole website under ssl.
example.com All static content such as css js and a small amount of my own images such as logos ect
However my platform is pulling in a lot of images from an outside domain cdn.example.net that will only ssl a small amount of their images that I dont have any access to resulting in my site throwing off a mixed content warning.
What would be the dangers of ssl sitewide am I at risk of some users not seeing all of the content because there browser thinks its not secure? I am also using spdy with nginx and I would like to keep the speed boost is there any workaround I could do for this?
Comment: Can you change CDNs? A CDN that won't do HTTPS is a problem. CloudFlare solves this problem by proxing and protecting the entire website.
Comment: Currently I cannot:( That would be the ideal route.
Comment: I think your setup will compromise your security and user experience. Suggest you find a way to change.
Answer: When you use https you are ensuring the users that the connection between your website and the client device is encrypted, this ensures the user that anyone sniffing packets on the internet will only see encrypted gobbledygook when connected to your site, (they won't see you or the client) now when you mix in http content from css fonts, images etc. you are breaking that agreement - this results in (depending on security settings) a big warning to the user letting them know - this guy is claiming to use https but he's not really and he might be trying to take advantage of you, a big red cross through over the 'https' in the address bar if the client decides to fecth he http content but usually the http content is ignored to try and make you compliant with the protocol and them you loose images and styling for your website - an altogether terrible experience for the user and for your website. force the outside domain to use SSL or if you can, save the images locally so you own server can encrypt them, if the CSS is using font elements from google, just change the url to https and it will work.
Answer: No ssl means, in between other things, that you are so vulnerable to mitm attacks because all the data will be sent without encryption. You will also not have a certificate and I wouldn't recommend anyone not to have a https version of their website already running as the end of http:// shouldn't be far away.
Comment: Even if its only the `img` not under ssl?
Comment: I understood from your answer that you are considering on stop using `ssl` but no, images wont be a big deal as long as there's no login needed or anything similar.
Answer: Firstly I suggest you to check your website in Why No Padlock tool. This tool will help you to identify all non-secure content on your website. There is a chance of higher bounce rate if your website will encounter warning message in the web browser.
There is no other way to get rid from such warning message instead of solving it. Instead of using third party platform to store your file (if you are), you should host all files on your domain (which is SSL secured). And if you still want to share third party file on your site, than upload on your own network and give them a citation.

To SSL or to not SSL


Why is this JavaScript code entering a for loop after the boolean expression is no longer true?

Question: Edit: This turned out to be a case of Firebug incorrectly stepping through the code, while my bug was elsewhere. A coworker who has seen similar behavior suggested that clearing the browser cache regularly can help.
I have this simple function that splits a comma-delimited string and uses the tokens to populate a Dojo data store:
UpdateFileNames: function(names) {
    var fileNames = names.split(",");
    var fileNameData = [];
    for (var i = 0; i < fileNames.length; i++) {
        fileNameData.push({ name: fileNames[i], id: fileNames[i] });
    }
    this.fileListStore = new dojo.store.Memory({ data: fileNameData });
}

I'm stepping through this code in Firebug and can't believe what I'm seeing. Everything is happy until i == fileNames.length, at which point the loop is entered again and fileNames[i] is invalid.
What's going on here?
Comment: Please created a http://jsfiddle.net/ demo for your problem. But obviously if the body of the `for` loop is executed, the condition is fulfilled. So the data might not be what you think it is.
Comment: @TravisChristian: Forget the debugger. Are you saying that if you run your code without debugging, but you do `console.log(i === fileNames.length)` inside the loop, the last iteration will show `true` in the console?
Comment: Is this your actual code, or have you attempted to simplify it?
Comment: What's the data coming in? I'm pretty sure `split()` works--does the list have a trailing comma?
Comment: @blo0p3r Splitting on commas will split on commas, spaces aren't relevant.
Comment: Have you lost interest in your own question? No response/clarification == Not A Real Question.
Comment: This is the actual code. split() works correctly, if I give it `"foo,bar"` then `fileNameData` is `[ "foo", "bar" ]`.
Comment: If that's the data, your loop works as expected.
Comment: @FelixKling The code is stepping into the body of the loop when `i == 2` and `fileNames.length == 2`, according to the debugger.
Comment: ...and you wrote *"if I give it `"foo,bar"` then `fileNameData` is `[ "foo", "bar" ]`"*. But `fileNameData` is the new Array into which the data is pushed, so are you saying that it's actually working correctly?
Comment: @amnotiam Oops, I meant `fileNames` was `[ "foo", "bar" ]`.When I added `console.log(i)` before the push, it appears to have actually changed the behavior of the code. The loop is not entered an extra time, and the debugger is now hitting the final line where it was not hit before.
Comment: @TravisChristian: Seems like it may be a bug in Firebug rather than in the JavaScript environment. Try upgrading to the latest version if you haven't. If you can reproduce the bug using a simple example, it may be worth filing a bug report.
Comment: @amnotiam At this point it seems pretty clear that Firebug has been lying to me. Going back to the original code, I looked at the state of the object later on and `this.fileListStore` was created, and looks correct, after all. I guess this is a non-question.
Comment: @TravisChristian: Yeah, I tend to have a healthy distrust for debuggers. ;)
Comment: ...deleting my jsFiddle example because overriding `Array.prototype.push` just made a mess in the Chrome debugger.
Answer: Have you tryed to to loop one less?
for (var i = 0; i < fileNames.length-1; i++) {
    fileNameData.push({ name: fileNames[i], id: fileNames[i] });
}

If that works you need to look at how you generate your list (names). So that you dont get blank elements at the end.
Comment: Why would you want to skip the last filename?
Comment: I just meant as test case to see if the code worked then. Maybe the was a blank element at the end. This would be easier with an example of the list: names
Answer: Does names end with a comma? If so, fileNames[fileNames.length - 1] == ''.

proof of concept
Comment: No, there is no trailing comma and fileNames is composed as expected.


questions related to joint distribution and continuous and discrete random variables

Question:
(a) If $U$ and $V$ are jointly continuous, show that $P(U =V) = 0$.
(b) Let $X$ be uniformly distributed on $(0,1)$, and let $Y= X$. Then, $X$ and $Y$ are continuous, and $P(X=Y) = 1$. Is there a contradiction?

(a)$P(U =V) = \int_{(u, v) = (u, u)} f(u, v) du dv$, and this integral is equal to zero since it is integrated at one point. Is this correct?
(b) $X$ is uniformly distributed on $(0, 1)$, so we have the distribution function $F(x) = x$ for $x \in (0,1)$. Then, we have an integrable function $f(x) = 1$ such that $\int_0^x 1 dx = x = F(x)$. Thus, $X$ is a continuous random variable. It seems intuitive that $P(X = Y) =1 $ since $X=Y$, but how can we actually compute this? Also, according to the solution, it does not contradict to (a) because $X, Y$ are not jointly continuous (i.e., there exists no integrable function $f$ such that $P(X \le x, Y\le y) = \int_0^x\int_0^y f(u,v) dudv$). How do we know the non-existence of such function?
Comment: Your answer to (a) makes no sense.  The event $U=V$ is not just a single point: it's an entire line.  For (b), you can use the technique employed at the end of https://stats.stackexchange.com/a/310493/919.  Also see https://stats.stackexchange.com/questions/124663
Answer: Hint:
I assume ,  $Y=X$,  you  mean distribution of
$Y|X=t$ is degenerate in point $t$.
For part a) use the fact that integral over set of measure zero is zero. integral over set of measure zero
For the question "How do we know the non-existence of such function?"
Now for  $(x,y)$ a.e
$F_{(X,Y)}(x,y)=P(Y\leq y,X\leq x)=\int_0^1  P(Y\leq y,X\leq x|X=t)  f_X(t) dt
=\int_0^1  P(t\leq y,t\leq x|X=t)  f_X(t) dt
=\int_0^{\min(x,y)} dt=\min(x,y)$.
Now
$f(x,y)=\frac{d^2}{dx \, dy} F(x,y)=0$ . So for
$(x,y)$ a.e
 $$f(x,y)=0$$. But in this case it's not a distribution function (because it doesn't integrate to unity). Such distribution that the density is not defined called singular distribution.
Comment: Your argument is good but it's not quite complete, because it's not the case that $f(x,y)=0$ everywhere.  However, it is undefined on a set of measure zero, so without changing anything essential you can *redefine* $f$ to be zero everywhere.  But in that case it's not a distribution function (because it doesn't integrate to unity).
Comment: @whuber, Thanks for attention ,I will edit it according your point.


Cronômetro com tempo errado

Question: Tenho um cronometro feito com QtSDK, porém quando ele é iniciado o tempo corre absurdamente mais rápido do que o normal. Segue o código abaixo:
QTime time;
QTimer timer;

void PlanejamentoWidget::timeUpdate(){
    QTime t = ui.timeEdit->time();
    ui.timeEdit->setTime(t.addMSecs(time.elapsed()));
}

void PlanejamentoWidget::startTimer(){
    if (timer.isActive()){
       ui.btStart->setText("Iniciar");
       timer.stop();
    }
    else{
        ui.btStart->setText("Parar");
        time.start();
        timer.start(60);
    }
}

void PlanejamentoWidget::restartTimer(){
    time.restart();
    QTime t;
    t.setHMS(0, 0, 0, 0);
    ui.timeEdit->setTime(t);
}

Alguém tem alguma ideia do que possa ser? Obrigado.
Comment: O que é absurdamente mais rápido? Como você chegou a esta conclusão? Dê mais detalhes, fica difícil entender o problema só com estas informações.
Comment: O método `timeUpdate` é o chamado a cada tick to seu timer? Outra coisa, é mesmo o que você deseja iniciar o timer com o valor `60`? Só lembrando que o valor esperado é em milisegundos...
Comment: Se diferença vai aumentando é por que o timer está sendo executado mais de uma vez.
Comment: No contador do cronometro 10 segundos são equivalentes a cerca 5 segundos do tempo real.
Comment: E essa diferença vai aumentando com o passar do tempo do cronometro.
Comment: Outra coisa: provavelmente você deseja alterar `ui.timeEdit` diretamente com o valor de `time.elapsed()` e não somar o tempo decorrido ao que já estava lá no campo da Interface. Provavelmente esse é o erro.
Comment: Note que QtCreator é apenas uma IDE e não "faz nada" além de organizar o seu projeto, quem compila ele no Windows é o VisualStudio ou o MingW. O termo QT pode ser usado para se referir ao qtSDK (que é uma biblioteca com funções prontas para facilitar o desenvolvimento, principalmente no caso de cross-platform).
Answer: O seu problema é que time.elapsed() é a quantidade tempo desde que você chamou time.start() em milisegundos. Por isso, que a diferença vai aumentando - o valor nunca é zerado.
Para arrumar, ao invés de chamar #elapsed() use #restart():
    void PlanejamentoWidget::timeUpdate(){
        QTime t = ui.timeEdit->time();
        ui.timeEdit->setTime(t.addMSecs(time.restart()));
    }

O método #restart() retorna a quantidade de tempo passada (em milisegundos) desde a última chamada à #start() ou #restart().
Veja mais em: QTime.

Cronômetro com tempo errado


Is there a canonical isomorphism between these two vector spaces?

Question: Suppose V is a vector space, W is a subspace of V. Suppose a linear map T from V to V is injective. Suppose the image of W under T, T(W), is contained in W. My question is: is there an isomorphism between V/T(V) and W/T(W)?
If V/T(W) is of finite dimension, by a calculation for the dimensions of these two spaces, I can conclude that they are isomorphic. I would like to know if there is more elegant argument to show these two spaces are isomorphic, perhaps there is a canonical one between them in general?
Thanks!
Comment: Suppose $V = \ell^1 \oplus \ell^2$, $W = \ell^2$, and $T$ shifts the $\ell^1$ component but fixes $W$. Then $V/T(V) \cong \mathbb{C}$, but $W/T(W) \cong \{0\}$.
Comment: You need to suppose $T$ bijective to make your finite dimensional case work out with this context.
Comment: @PatrickDaSilva: For linear maps I think injective implies bijective; if f is 1-1 ,kerT is trivial, and then by Rank-nullity, Dim(RankT)=n=DimV.
Comment: @user99680 : My point was that in the finite dimensional case, injective and bijective are the same. So if he wants to work with a general vector space of non-necessarily finite dimension, then the correct assumption (as the counter examples have shown) is not injective, but rather bijective. In this case both spaces are zero though, so the isomorphism is quite canonical. I admit my first comment didn't realize the only example gave zero... -_-
Comment: @Patrick Da Silva: Ah, I see, I isunderstood/misunderestimated your point, sorry.
Comment: @PatrickDaSilva We don't need $V$ is finite, we only need $V/W$ is finite. See the answer below.
Answer: No.  For a counterexample, let $V = \bigoplus_{i \in \mathbb{Z}}\mathbb{R}$ be the direct sum of countably infinite copies of $\mathbb{R}$,   Denote by $e_i$ the element with a $1$ in the $i^{\textrm{th}}$ place and zeros elsewhere, and let $W$ be the subspace generated by $e_0$.  Let $T$ be defined by $T(e_i) = e_{2i}$.  Then $T$ is injective on $V$ and is the identity on $W$, so $W/T(W)=0$, but $V/T(V)$ is isomorphic to $V$, since the image does not contain $e_i$ for any odd $i$.
Answer: Since
$$V/T(V) = V/(W+T(V))\oplus (W+T(V))/T(V) = V/(W+T(V))\oplus
{\color{blue} {W/(T(V)\cap
W)}}$$
and $$W/T(W)={\color{blue}{W/(T(V)\cap W)}} \oplus (T(V)\cap W)/T(W).$$
Thus
$$V/T(V)\cong W/T(W)$$ if (${\color{red}{\text{ BUT NOT ONLY IF }}}$) $$V/(W+T(V))\cong (T(V)\cap W)/T(W).$$
However, $T(V)/T(W)\cong V/W=V/(W+T(V))\oplus
(W+T(V))/W= V/(W+T(V))\oplus
T(V)/(W\cap T(V))$
and $(T(V)\cap W)/T(W)\oplus T(V)/(T(V)\cap
W)=T(V)/T(W)$.
So if $V/W=T(V)/T(W)$ is of finite dimension, we do
have $V/T(V)\cong W/T(W)$.
Comment: Oh man you should really format this better. This is painful to read.


Django modelform field how to make disabled and prevent tampering?

Question: There is this disabled attribute. But i am not able to apply it to the modelform fields. I am not sure how to. I can add it to forms.Form easily. But since I am using widgets I just dont know where to insert it.
https://docs.djangoproject.com/en/2.0/ref/forms/fields/#disabled
class TestForm(forms.ModelForm):
    class Meta:
        model = Test
        fields = ['date']
        widgets = {'date': forms.TextInput(attrs={'readonly': 'readonly'})}

Comment: You can add the attribute: `forms.TextInput(attrs={'disabled': 'disabled'}),`
Answer: I was facing a situation when I wanted to disable some fields when creating . And some fields disabled when editing.
My Env: Python 3, Django 2.1
My Form:
class AddInvoiceForm(forms.ModelForm):
    disabled_fields = ['inv_type', 'report', 'subsidiary']
    class Meta:
        model = models.Invoice
        fields = ('inv_type', 'report', 'subsidiary', 'rate_card', 'reviewed')

    def __init__(self, *args, **kwargs):
        super(AddInvoiceForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            for field in self.disabled_fields:
                self.fields[field].disabled = True
        else:
            self.fields['reviewed'].disabled = True

Answer: Try something like this, assuming that your date field is forms.DateField and that you want to use TextInput widget:
class TestForm(forms.ModelForm):
    date = forms.DateField(widget=forms.TextInput, disabled=True)
    class Meta:
        model = Test
        fields = ['date']

This will override the default field definition which is created from your Test model definition.

The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won't be editable by users. Even if a user tampers with the field's value submitted to the server, it will be ignored in favor of the value from the form's initial data.

Read about readonly  vs disabled HTML input attributes.
The key note to take out from the above SO post is:

A readonly element is just not editable, but gets sent when the according form submits. a disabled element isn't editable and isn't sent on submit.

From above quote, setting disabled=True is enough, so you dont need to set readonly attribute on your widget.
Comment: Can't someone just click on "inspect" on the form entry and modify the content and the resubmit the form?
Comment: @FedericoGentile see the quote I use in my answer. It says 'Even if a user tampers with the field's value submitted to the server, it will be ignored in favor of the value from the form's initial data.'. Thats what official Django docs say (https://docs.djangoproject.com/en/dev/ref/forms/fields/#disabled)
Comment: Hello, I just tested it on my own and with readonly I am still able to modify the value and submit it. As a matter of fact when I check the database where I store the data I actually see the modified value
Answer: class TestForm(forms.ModelForm):
date = forms.CharField(disabled=True)
class Meta:
    model = Test
    fields = ['date']

    widgets = {
        'date': forms.TextInput(attrs={'readonly': 'readonly'}),
    }

Comment: are you sure that will work? How will it knnow that the variable date and the field date are related to each other/
Comment: You are using model form.. So django will relate that implicitly


Updating multiple records/rows selected by two columns

Question: I've been trying to write an update query that would update several rows/records so that i could test update trigger with batch updates. I've seen somewhere it done something like that
update atbv_Sales_OrdersLines
    set Amount = case OrderID
                when 5 then 10
                when 6 then 11
    end
where OrderID in (5, 6)

but I need to select rows based on two columns and I can't manage to do it
tries something like
set Amount = case OrderID, ProductID
            when 6, 1 then 10

but as expected it's no good
Answer: What about...
update atbv_Sales_OrdersLines
   set Amount = OrderId + 5
 where (OrderId = 6 and ProductID = 1) or
       (OrderId = 5...)

or
update atbv_Sales_OrdersLines
   set Amount =
         CASE
           WHEN OrderId = 6 and ProductId = 1 THEN 11
           WHEN OrderId = 5 and ProductId = 2 THEN 10
           ...
         END
 where ...

You should probably read Microsoft's documentation on the CASE expression and pay especial attention to example "H. Using CASE in an UPDATE statement"
Comment: error `An expression of non-boolean type specified in a context where a condition is expected, near ')'.`
Comment: @NulisDefo - misplaced parenthesis.  thanks for the catch.  Corrected it.
Comment: @Agapwlesu Tried second one (as it is more clear to me) and it works. I assume `where` clause here is not necesary, right?
Comment: Yes it is, if you only want to set the Amount of those records where OrderId is 5 or 6.  Even if you manage to set Amount to the value it was before, for all other records, that would be hugely wasteful/inefficient.
Comment: it would be setting Amount to record where OrderID is for example 5 and ProductID is 1
Comment: I am not clear what you mean, but basically, you want to use the WHERE clause to limit the records that you update to only the records you need to update.  Even if the CASE expression does something to limit which `Amount` values get changed, you do not want that CASE expression to be run on any records that you do not mean to UPDATE, and you limit that with the WHERE clause.
Answer: Try this:
case
when OrderID in (6, 1) then 10
...
end

Comment: If you use the form "case OrderID when  then ..." then  can only be a single value from OrderID.

However, if you use the form "case when  then ..." you can have any conditional statement you want in that   You can say "orderID = 6 and otherThing = 'abc'" or "orderID is not null and orderID in (3,4,5,6)" or whatever logic you want that resolves down to a true/false value.
Comment: but if i name only one column `OrderID` where will it take the other number from?
Comment: oh, so pretty much what Agapwlesu showed. Good explanation, but your answer doesn't seem to reflect it. Or am I missing something?
Comment: No, I didn't see his answer, it's better and should be accepted.


Fitting Model with MCMC?

Question: In fitting a model with several variable I have found extremely useful a method involving the minimization of the Chi Square using a MCMC approach. In particular, I followed this tutorial http://sciencehouse.wordpress.com/2010/06/23/mcmc-and-fitting-models-to-data/
However, I cannot find around any other source. Since I will use this method for a scientific work, I would like to
a) be sure that the method is theoretically correct
b) cite a peer-reviewed source.
Running several simulation with complex model (6/7 parameters) showed me that the model actually works really fine, retrieving the parameter within a small error most of the time.
In particular, I am not sure about the use of $exp(-\chi^2) $ for the likelihood. Is this justified? I also tried to calculate the ratio by just dividing the oldChi2 with the newChi2, and the results were, again, satisfying. Is there any relevant difference between these two methods?
Thank you
Comment: This is nothing fancy, it's simply a Metropolis algorithm. Also, if you look closely, $\exp\left(-\chi^2 \right)$ is a Gaussian density.
Comment: I understand that, but I wonder if there is any important theoretical reason to use exp(-X^2). Could I just calculate the likelihood ratio as X^2_old/X^2new?
Comment: If you want to use the Metropolis algorithm as in the blog post, then you must use the exponential function. The Metropolis algorithm uses the ratio of densities to accept or reject proposed values. If you drop the exponential, then you are not using the ratio of densities.
Answer: Actually the Mcmc method is a good tool to find the posterior probability function. I suggest that you read the following site - - > http://dfm.io/emcee/current/ In cosmology and astrophysics this method is very useful. On the other hand, about your question of \exp(\chi^2) as likelihood, you must observe whether your error distribution is Gaussian, because there are other distribution functions for the errors.

Fitting Model with MCMC?


Xamarin forms android using user certificates

Question: If a user has installed a pfx user certificate on an Android device, chrome browser sees and asks permission to use users client certificate to access a server that accepts such certificates.
What is the Xamarin forms equivalent ?

How can we access these certificates in Xamarin form apps for Android.
Under windows (UWP) Accessing  user certificates is just
<code>              httpClientHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;
              httpClientHandler.UseDefaultCredentials = true;
</code>
Under Android we are trying to use Custom version AndroidClienthandler
<code> MyAndroidClientHandler clientHandler = new MyAndroidClientHandler();
</code>
In a Custom AndroidClientHandler There are 2 problems to solve
1) how to get a certificate from the users certificates from the keychain ?
 Something like this post perhaps?  Client Certificates on Android
2) How do you add that cert to the ClientHandler?
   Can I simply do this
            clientHandler.TrustedCerts.Add(cert);
or  more likely
Add certificate to SSL Context
Has anyone ever managed to do a HTTPS call using an already installed client certificate from Xamarin forms ?
Answer: Looks like Android didn't provide a direct way to use a default credential, but Android provide developers with some choice to use system-wide credentials or app's private credential.
KeyChain may help to launch a system dialog for user to choose a certificate/enter the password. Refering to earlier post.
And extend AndroidClientHandler as posted here is what I found to use the client certificate.
Hope it helps.
Comment: Thx Nicole Ill take a look at the links to see if I can figure something out from them. Its mainly  Android docu and JAVA blog post. I was hoping someone has managed to the equivalent in Xamarin forms.  It is of course in the right direction.
Comment: ok not really  the solution i was hoping for, but its closer than no tip at all. Thanks Nicole.


If a discrete random variable is independent to other two discrete random variable, is it independent to the sum?

Question: Suppose X,Y,Z are discrete random variables and X is independent to both Y and Z.
Is X independent to Y + Z?
I know this is not necessarily true but I am struggling to find a counterexample.
It would really be appreciated if anyone could kindly find a counterexample.
Many thanks
Answer: Consider two independent coin tosses, and the following definitions:

Let $X = 1$ if first toss is Heads
Let $Y = 1$ if second toss is Heads
Let $Z = 1$ if only one toss is Heads

You'll find that these events are pairwise independent. Yet, the following inequality remains $$0=P(X=1|Y+Z=2)\neq P(X=1)=1/2$$
which is a counter-example for independence assertion.


How to find coordinate of intersected rectangle

Question: I have two intersecting rectangles, A and B, with known dimensions and locations. In my example, Rectangle B's top-left point is on the origin. I get the intersecting rectangle, I, and its dimensions and location. With this information how can I get the intersecting rectangle's top-left coordinate relative to rectangle A's top-left? Is it possible to get a single formula for I_X and for I_Y?
Example Image
Comment: You have the coordinates of the top left point of $A,$ is that right? And the top-left coordinates of $B$ are $(0,0)$? And $(0,0)$ is also the top left of the intersecting rectangle in your figure? Then the answer is to just reverse the signs of the coordinates of $A.$ This seems so simple, I wonder if I misunderstood the question.
Comment: @DavidK The topleft point of B is known, but only falls on the origin in my example to help in understanding the problem. Perhaps I should clarify that in the question.
Comment: It's still fairly simple; instead of subtracting $A$'s coordinates from zero, you subtract them from whatever coordinates $B$ actually has.
Comment: @DavidK That wouldn't work if, for example, _A_ and _B_ were both 10 by 10. Topleft _A_ = (1,-9), Topleft _B_ = (0,0).  Intersecting rectangle would be 9 by 1 at (1,0). _I_ topleft relative to _A_ topleft is (0,9), not (-1,9) as your comment would suggest, If I understand you correctly.
Comment: If both rectangles are of general dimensions in general position with no other restrictions (except I suppose their sides are parallel to the axes), then you don't know that there _is_ an intersecting rectangle until you've examined the coordinates carefully. So the question becomes how to show whether there is an intersecting rectangle and find its upper left coordinate if it exists. Does that sound like a more complete description of what you need?
Comment: @DavidK This question assumes that the proper checks have been made prior, to assure there is an intersecting rectangle with the given rectangles. It also goes as far as assuming you already possess the size and location of the intersecting rectangle, let alone that it exists.
Comment: Then the information about $B$ is no longer relevant. I only used the coordinates of $B$ since they were the top left coordinates of the intersection in your example. Use the coordinates of the intersected rectangle instead.
Comment: Basically you seem to have the coordinates of two points, and you want to know "how far to the right and how far down to get from the top left corner of $A$ to the top left corner of $I$?" You go far enough right to get from one $x$ coordinate to the other, and far enough down to get from one $y$ coordinate to the other.
Comment: Thank you, this is the little kick I needed. I knew it was simple. What I am looking for is $I-A$ simple enough.
Comment: Sometimes you just need to hash it out like this to get unstuck ... glad to help.
Answer: Simple enough. Subtract the $A$ coordinate from the $I$ coordinate relative to $B$.
$I/A(x,y) = I/B(x,y)-A(x,y)$
$I(x,y)$ with respect to $A$ equals $I(x,y)$ with respect to $B$ minus $A(x,y)$


JApplets and JDialog

Question: I have a japplet which contains an "about" button, which when pressed creates a new JDialog. The idea is that when the user clicks on the about button in the applet they will get a popup window which displays information. This works perfectly fine when i test it from eclipse with the applet viewer, but when i test it in the html form, the button does nothing. The applet runs and works, but the button does not create a new window or respond in any way.
full disclosure: when i say JDialog i actually mean a class i created which extends JDialog and has a method public void paintComponent (Graphics g){ ~~~~ } ... and i also tried with that class extending JFrame instead and had the same problem, it worked in applet viewer but not in the browser.
now my question is, is my thinking wrong, am i going about creating a popup window for a japplet the wrong way, is there a different method i should probably try?
my code is very long, but if there's something you need to see from it to properly answer the question let me know.
Comment: "my code is very long,", but it doesn't have to be long. Create a simple applet with a button. Have that button display a JDialog. It should be about 20 lines of code. Its called a SSCCE (http://sscce.org). If it works, great then you can compare the SCCE code with your real code to see what is different. If it doesn't work, then you have something simple to post on the forum so we can also test it.
Comment: thanks i will keep that in mind, but i figured it out already. Thanks for your time
Answer: Are you making sure to set the new popup window to visible?  That could be your problem, or I've heard of problems with Google toolbar not allowing user-initiated popups to appear, but I think that problem was fixed (if you're running an old version of Google toolbar, it may still be an issue).
Answer: ok i figure out what the problem is, is an image problem, the DrawingBoard was using io and imageio to load some images.

JApplets and JDialog