How to simulate connection to HTTPS and record the handshake?

Question: I have a farm of IIS 6 web servers hosting a website over HTTP and HTTPS. With Safari 4 on a Mac, connecting over HTTPS, some nodes in the farm trigger the browser to raise a certificate error to the user, the other nodes work fine. Always the same nodes cause the problem but the problem does not appear to occur in IE or Chrome.
I presume these nodes in the farm are misconfigured but I cannot easily identify the problem from looking at the individual server setups. I'd like to point a client-side tool at a known good node and capture the SSL client and server hello, the certificate message, the key exchange, etc from the client's perspective, unencrypted and then repeat on a known problem node and then compare.
Can you please suggest any Windows tools for this, or perhaps a better way to diagnose the fault?
Answer: I've often used OpenSSL's s_client. I don't see why the Win32 version shouldn't work the same.
You can use the following command to be very verbose about the SSL handshake:
openssl s_client -debug -msg -state -status -showcerts -connect <host>:443

You can then drop some of the arguments off if you wish to be less chatty.
You may also wish to specify -CAfile with your sole signing CA.
Answer: The article The First Few Milliseconds of an HTTPS Connection explains what are you looking for.
Answer: Have a look at fiddler2 - http://www.fiddler2.com
"Fiddler is a Web Debugging Proxy which logs all HTTP(S) traffic between your computer and the Internet. Fiddler allows you to inspect all HTTP(S) traffic, set breakpoints, and "fiddle" with incoming or outgoing data. Fiddler includes a powerful event-based scripting subsystem, and can be extended using any .NET language."
Fiddler is a great general purpose web debugging tool.  Now, for your purposes you might want to combine the advice from David in terms of connecting to each of the servers individually with the ability to trace from Fiddler what is going on.  It's obviously key to know which server you are connecting to so that you can identify exactly where the problem lies
Comment: I am familiar with Fiddler2... great tool. Unfortunately it seems to use its own certs when proxying HTTPS traffic and doesn't reveal sufficient information about the SSL handshake with the server.
Comment: It does for me.  I had it intercept https traffic, and it shows the server certificate detail under the inspector view of the CONNECT line...
Answer: How is the farm configured? If you can see each node of the farm (i.e. you are on the same network directly or via VPN, or they have public facing IP addresses), could you not connect to each and see which is having certificate problems?
For each node:

completely close your browser (in case it has cached the IP address associated with the name, as we are about to change that association locally in the next step)
associate its direct address with the (sub)domain name that you expect to be on the certificate by adding an entry in your hosts file (c:\windows\system32\drivers\etc\hosts on most Windows configurations)
open your browser and go to the site
Comment: I have already done this. I know which nodes in the farm are wrong. Unfortunately the details in the error presented by the browser are insufficient to determine what is misconfigured on those servers.


How to Find Total People By Their Total Weight?

Question: imagine you are on a room where 4people lived. let's consider there weight are below:

P1 = 82kg
P2 = 62kg
P3 = 49kg
P4 = 73kg

after sum we can see their total weight are 266kg (P1+P2+P3+P4 = 266kg)
now the question: is there any way to find how many people are there just by knowning their total weight? in this case its 266kg
Note: i know its a basic question but currenly i am learning math, thats why i put simple question here too so that i can get a clear overview
Comment: If you have a maximum and minimum weight for humans, you could get a range estimate for the number of people.  But you can't generally say exactly how many people given a total weight. For example, a total weight of $400$ kilograms could come from $4$ people at $100$ kg each; or from $5$ people at $80$ kg each.
Comment: What do you think? You can try guessing a weight to see if it works. Then guess a different weight. Does it work too?
Comment: what about you have 2people weight individually and total 4 people weight. (you have P1,P2 weight individually)
Comment: @paw88789, your answer is good. I guess to complement it maybe you want to add that the weights should all be an integer value. Not sure what other constraints are required to get a finite solution.
Answer: HINT:
Suppose that instead of these $4$ people, you had $4$ different people, whose weights are $31$, $38$, $62$, and $69$
Now suppose I weighed some people, and I got a total of $100$.  Notice that this could have been from the $31$ and the $69$ persons, but also from the $38$ and $62$.
Or what if the total was $69$?  That could have been just the $69$ person by themselves, but it could also be the $31$ together with the $38$ person.
So, in this example, it is not always the case that given some total weight, you can tell which person(s) were being weighed.
Now, you have different numbers to work with, but maybe something like this could happen in your case as well?  I think that this is what your question is asking. So see if with your numbers you can get some different combinations of people that add up to the same total weight. And, if you think that in your case this is not possible, try and come up with an explanation (a proof!) that this is not possible ... in which case you can always tell which people were being weighed given the total weight.
Good luck!


How to call view block on click?

Question: I have a page/node that contains 15 view blocks, each view block has many fields and all of this causes the page to load really slow.
How do I load the view block only when I need it? for example I would click a button/div (venue) then the view block venue will load instead of invoking all of the view blocks on the template and letting it load all at once.
UPDATE:
I tried using ajax but it's not working even though I turned the ajax on the view block.
This the code I used:
JS:
$(document).ready(function(){
$("#getvenue").click(function(){
    $.ajax(
    Drupal.settings.basePath + 'views/ajax',
    {

    view_name: 'custom_package_form',view_display_id: 'block_56'
    },

    function(response)
    {
        if (response[1] !== undefined)
        {
            var viewHtml = response[1].data;
            $("#output-venue").html(viewHtml);

            Drupal.attachBehaviors();
        }
        else {
            $("#output-venue").html("NONE");
        }

    });
    });
 });

Node Venue TPL:
<button id="getvenue"> GET VENUE </button>

Nothing happens, I tried alerting the var viewHtml to see if it has something, the alert only shows null.
What's wrong with the JS? Can someone point me to the right direction?
Thank you in advance!
Answer: Try this code
$.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'POST',
    dataType: 'json',
    data: 'view_name=custom_package_form&view_display_id=block_56',
    success: function(response) {
      var output = response[1].data;
      $("#output-venue").html(output);
    },
    error: function(data) {
        alert('An error occured!');
    }
});

Comment: Hi, Thank you for your response. I tried this code, it's giving a null on the #output-venue div. It only appeared when I put "$("#output-venue").text(output);" to the js instead of html. I was wondering if the url is correct? I only based the coding to this link: http://blog.astaz3l.com/2013/06/24/drupal-views-ajax/
Comment: The response from the server is important. use `alert(output)` to make sure it is correct. Then you can display it in any way you want. What `url` you are talking about?
Comment: The alert shows "null" also. As for the url, I was referring this part: `url: Drupal.settings.basePath + 'views/ajax', ` I'm not sure if that is default? sorry for not being clear.
Comment: I used this code in a few websites and it works. Yes it is default
Comment: In View settings did you set  the `Use Ajax : Yes`?
Comment: Yes, I did set it. I will try to create a new view block, because the one I'm using is on modal.
Comment: It's working, if the block doesn't have contextual filter. it shows null if I use contextual filter. Thank you again
Comment: @Danz you welcome
Comment: Hi @Danz , how did you get this done? I'm trying to so the exact same thing... where did you put the code? Thanks!
Comment: Hi @Drii7, you can put the ajax code on your js file. In my case the ajax code is under click function.
Answer: You need to try this module ajaxblock, I have used it with ubercart for building e-commerce site.

Permits to load some blocks by additional AJAX request after loading the whole cached page when the page is viewed by anonymous user. It is suitable for sites which are mostly static, and the page caching for anonymous users is a great benefit, but there are some pieces of information that have to be dynamic.
Comment: Hi, I'm trying out the module you recommended. I saw this: "Time in milliseconds to wait before block loading" on the settings of the blocks. I don't like the blocks to be loaded by some given time, I would like the blocks to be loaded individually when triggering an OnClick of a button. Is that possible? Because I would like the page to be as light as it can be, the 15 blocks should not be invoked/loaded on the page/tpl as long as the button that will call the block is not clicked. thanks again

How to call view block on click?


Setting date format in unattended Windows deployment

Question: Our organization would like to use the ISO date format (known in Windows as yyyy-MM-dd).
I've configured this in our image.  When I deploy the image, it replaces the date format with the default for the locale in unattend.xml.  As far as I could see in the Unattended Windows Setup Reference for Windows 7, there are no date format settings.
It can be done with a user logon script, or a user GPO, but I really need it to be included in deployment.
Answer: I was the guy who suggested using GPO on Superuser for an almost identical question.  You can do what you are asking using the Components->Microsoft-International-Core->UserLocale settings assuming you are applying a user locale that has the settings you require.  I suspect you will already know this info.  So that might be the quickest way using the unattended setup.  There is also a SystemLocale under Microsoft-International-Core-WinPE as well that might work better.
I pulled the above info from Microsoft at :http://technet.microsoft.com/en-us/library/ff699026.aspx
Comment: What UserLocale uses the ISO date format?  Neither en-US or en-CA does.  GPO is out of the question because we need to remain having users able to change it.
Comment: There are many countries that use that format.  Here is one list available via Wikipedia.  If it isn't your local format, what is the point of changing it?
http://en.wikipedia.org/wiki/Date_format_by_country

FWIW, you could apply the GP to the new computers OU and then simply move the computers out of that OU before you deploy them to the users.  If there isn't another GP to override it the setting should stick.
Comment: You're right, I wouldn't want to change my locale to something it's not.  I thought perhaps there were hidden locales like en-CA-ISO.  You'll note that many countries, like Canada, have more than one date format.  Microsoft has even changed what the default is for Canada between versions of Windows.
Comment: are you just trying to change the clock display?  The date and times are stored as a value and just show depending on what the user has selected.

Have you tried "ENC"?  http://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx  Seems to indicate that is the ISO for en-CA.  Might be worth a shot...
Comment: No, not the clock display, the date format for the entire system.  ENC is an ISO 639 code for the name of a language.  This is unrelated to the ISO 8601 date format.
Comment: I am out of ideas,  perhaps the other answer might lead to something?  Just curious what you are trying to "fix" by changing this.
Answer: Microsoft lets you create custom locales.  They offer a tool for this called Microsoft Locale Builder.
Version 1.0 is for Windows Vista and is no longer available from Microsoft, but can be downloaded elsewhere.
Version 2.0 is for Windows 8.1.
Neither version will install on Windows 7.  Bewildering--yes.


How to predict the risk of an event?

Question: I'm working on a medical problem, where I want to analyze the effect of taking cholesterol medications on the occurrence of heart attack. Once a medication with a specific dosage is prescribed, it'll be used by a patient for $k$ consecutive periods (i.e., refills periods).
Moreover, I have a retrospective data of several patients, where each patient

is prescribed with different dosages,
has the fixed $k$ periods of refill,
may have some instances of heart attack during those $k$ periods, and
has other risk factors (as confounding factors).

Now, if a patient takes a specific dosage of that medication for $k$ consecutive periods (in a prospective sense), how can I predict the risk of heart attack at any time during those $k$ periods? I guess there might be some relevance to Cox survival analysis, but I'm not quite sure. So, any comment/help is really appreciated!
Thanks.
Answer: First thought that comes to mind is using a binary logistic regression. You can predict probability of a heart attack happening after fitting your dataset to a logistic model.
Here is the formula for generating the probability of $Y_i = 1$
$
P(Y_i = 1|\, x_{i1},\ldots,x_{ip}) = \frac{e^{\beta_0 + \beta_1 x_{i1} + \ldots + \beta_p x_{ip}}}{1+e^{\beta_0 + \beta_1 x_{i1} + \ldots + \beta_p x_{ip} }} = \pi_i
$
Comment: I'm familiar with the concept of logistic regression. The problem with this model is that it gives me the probability of a heart attack at a fixed time. However, as I explained above, I want a model that takes the data of $k$ periods and tells me the probability of this event happening once  (or at least once) during the $k$ periods.
Comment: @Alex I might be having trouble understanding your problem or the way your dataset looks but I wonder if it would be possible to take the mean of the predicted probabilities across $k$ periods.
Comment: Thanks, but that does not work for my case.

How to predict the risk of an event?


rtmfp - NetConnection.Connect.Failed - can't get what's wrong (kaspersky settings)

Question: i'm developing an actionscript p2p application. everything worked fine until today.
this is my code:
<code>            private function initConnection():void{
                nc = new NetConnection();
                nc.maxPeerConnections = maxPC;
                ExternalInterface.call("alert",maxPC);
                nc.addEventListener(NetStatusEvent.NET_STATUS, ncStatus, false, 0, true);
                nc.connect(SERVER_ADDRESS);
            }

            public function ncStatus(event:NetStatusEvent):void {
                if (event.info.code == "NetConnection.Connect.Success") initSendStream();
                else if (event.info.code == "NetStream.Connect.Closed") {
                    if (event.info.stream.farID) onPeerDisconnect(event.info.stream.farID);
                }
                else if (event.info.code == "NetConnection.Connect.Failed") ExternalInterface.call("p2pError", "conFailed")
                else ExternalInterface.call("p2pError", "conFailedUnknown");
            }
</code>
and i always got it worked. the key and rtmfp-server addres are right.
i can't understand why i allways has "NetConnection.Connect.Failed".
i search on the internet about this question. the possible sollution is to turn off firewall. but it allways turn off at my pc.
so i don't know what to do...
any suggestions?
any help appriciated!
Edit: well guys, i've just solved this problem. i got kaspersky with expired licence. so i turned it off but didn't delete. just turned off. few minutes ago i've deleted it and everything started working fine. but i'm still curious about what settings kaspersky could change. so question still open.
Answer: well, it seems coinsedence took place this time. kaspersky had nothing to deal with that. adobe cirrus server was down for few days.


Are $\mathbb{F}_2$-linear combinations of random variables in an i.i.d. Bernoulli process again an i.i.d. Bernoulli process?

Question: I'm having trouble understanding how certain combinations of random variables can correlate. The problem is as follows:
I have a binary $m \times n$ matrix $A$ of full rank (over the finite field $\mathbb{F}_2$ with two elements), where each row has exactly $w$ $1$'s (i.e., their weights are all $w$).
I randomly pick an $n$-dimensional binary vector $\boldsymbol{v} = (v_0,\dots,v_{n-1}) \in \mathbb{F}_2^n$, where each $v_i$ is $1$ with probability $p$ and $0$ with probability $1-p$. The probability $p$ is assumed to be strictly smaller than $\frac{1}{2}$. Here, $v_i$ are all independent, so that picking $\boldsymbol{v}$ is seen as an i.i.d. Bernoulli process of probability $p$.
I am going to hash this vector $\boldsymbol{v}$ into an $m$-dimensional vector $\boldsymbol{v}' = (v'_0,\dots,v'_{m-1})$ by taking $\boldsymbol{v}' = A\boldsymbol{v}^T$ over $\mathbb{F}_2$. So, if I write the $i$th row of $A$ as $\boldsymbol{r}_i$, each $v'_i$ is the product $v'_i = \boldsymbol{r}_i\cdot\boldsymbol{v}^T$ between the $i$th row of $A$ and $\boldsymbol{v}$. In other words, I'm just taking the mod $2$ sum of some bits of $\boldsymbol{v}$.
Because the weight of $\boldsymbol{r}_i$ is assumed to be $w$, the probability $P(v'_i = 1)$ that the $i$th bit $v_i'$ of the hashed vector $\boldsymbol{v}'$ is $1$ is
$$P(v'_i = 1) = \sum_{x: \text{odd}}^{w}\binom{w}{x}p^x(1-p)^{w-x},$$
which is a constant if we fix $p$ and $w$, and is also uniform across all $v_i'$.
Now, if $A$ had linearly dependent rows, the hashed bits $v_i'$ are clearly not independent. My question is:
What if all rows of $A$ are linearly independent? Is $\boldsymbol{v}'$ an i.i.d. Bernoulli process with probability $P(v'_i = 1)$? If not, can I approximate it as one if $\boldsymbol{r}_i$ and $\boldsymbol{r}_j$ have only few $1$'s at the same columns for all $i \not=j$?
I remember I read in some research paper in electrical engineering that $\boldsymbol{v}'$ is i.i.d. Bernoulli if rows of $A$ are linearly independent, although I can't seem to remember where it was. (I found one recent paper that says this is the case: V. Toto-Zarasoa, A. Roumy, C. Guillemot, Maximum likelihood BSC parameter estimation for the Slepian-Wolf problem, IEEE Comm. Lett. 15 (2011) 232–234. It's Lemma 1 on the second page.) But now I think about it, this is counterintuitive (to me) because if two rows of $A$ have $1$ at the same column, that means that I took at least one same $v_i$ when hashing $\boldsymbol{v}$ for those two rows, so the corresponding $v_i'$ look correlated.
If my reasoning and Alecos Papadopoulos's answer are correct, the last part of the above question in boldface becomes essential. For instance, are there standard methods for evaluating how close or similar a given set of random variables like $\boldsymbol{v}'$ is to i.i.d. Bernoulli?
Comment: Thanks for the feedback. Regarding the "conjecture", it only applies to square matrices -you provided a counter-example using a non-square matrix. There are general standard methods to measure distance between distributions like the Kullback-Leibler distance, Hellinger distance etc (instances of "f-divergence"). But in order to apply these, we need to have the joint distribution of the $\boldsymbol{v}′$. Do we?
Comment: @AlecosPapadopoulos Thanks. My knowledge in statistics is very poor, and I had no idea what kind of thing is known about comparing two distributions etc. But I think I figured out where I should look. For instance, I just googled the definition of the Kullback-Leibler thingy, and it's just the difference of entropies. So, it looks like information theoretic approaches are the way to go for my problem. And I agree that this way of viewing the problem looks promising.
Comment: (... cont.) I don't quite follow what you mean by "we need to have the joint distribution of the $\boldsymbol{v}'$," but I think I have enough information to find or come up with a satisfactory method on my own. Thanks.
Comment: You 're welcome. Good luck with the matter.
Answer: 1) Meta-issue:
I believe the OP should include in the title of the question a signal that something special is going on here - for example instead of "Are linear combinations of..." the title should read "Are $\mathbb{F}_2-$linear combinations of...", so that the reader gets the message that concepts may have special meanings in this specific question.
2) Bernoulli or not Bernoulli?
By $\mathbb{F}_2-$arithmetic, the sum of i.i.d Bernoulli rv's is not a Binomial, since all probabilities are condensed on the values $0$ and $1$. We first derive the binomial distribution and then add the probabilities of all even values of the support to the probability of $0$, and the probabilities of all odd values of the support to the probability of $1$ -and thus we obtain again a Bernoulli r.v. This is just to validate the probability mass function included in the OP's question. It is  by construction a Bernoulli random variable, irrespective of how $P(v'_i = 1)$ is derived. Moreover if the number of $1$'s is the same in each row of the matrix $A$, then each $v'_i$ has an identical Bernoulli marginal distribution.
3) $\mathbb{F}_2-$ linear independence.
$\mathbb{F}_2-$ linear dependence does not look much like the "usual" concept of linear independence. To be able to obtain a square matrix of full row/column rank under $\mathbb{F}_2-$arithmetic, I conjecture that $w$, the number of $1$'s in each row, should be an odd number. Consider a square matrix $n\times n$ matrix $A$, and the first element of one of its rows, say $a_{i1}$. I reason as follows:
a) Assume $w$ is an even number.
a1) Assume $a_{i1} = 0$. Then in the remaining $n-1$ elements of the row, there exists an even number of $1$'s, which by $\mathbb{F}_2-$arithmetic will give us $0$. The rest of the elements of the row all also zero, so overall the sum of the $n-1$ elements will give $0$, i.e equal to the value of the first element.
a2) Assume $a_{i1} = 1$. Then in the remaining $n-1$ elements of the row, there exists an odd number of $1$'s, which by $\mathbb{F}_2-$arithmetic will give us $1$. The rest of the elements of the row are all zero, so overall the sum of the $n-1$ elements will give $1$, i.e again equal to the value of the first element.
So if $w=even$, the  $\mathbb{F}_2-$sum of the $n-1$ columns will always equal the $n$-th column, depriving us of full rank.
b) Assume $w$ is an odd number.
b1) Assume $a_{i1} = 0$. Then in the remaining $n-1$ elements of the row, there exists an odd number of $1$'s, which by $\mathbb{F}_2-$arithmetic will give us $1$. The rest of the elements of the row all zero, so overall the sum of the $n-1$ elements will give $1$, i.e different to the value of the first element.
b2) Assume $a_{i1} = 1$. Then in the remaining $n-1$ elements of the row, there exists an even number of $1$'s, which by $\mathbb{F}_2-$arithmetic will give us $0$. The rest of the elements of the row all also zero, so overall the sum of the $n-1$ elements will give $0$, i.e again different than the value of the first element.
So it appears that $w= odd$, is at least a necessary condition to have a matrix $A$ of full column/row rank.
4) Stochastic (in)dependence in the $\mathbb{F}_2-$world.
Does the characteristics of $\mathbb{F}_2-$field affect the concept of stochastic (in)dependence? No. Two r.v.'s are independent if and only if their joint distribution is the product of their marginals. Meaning, the conditional distributions must equal the unconditional ones. Maybe the way operations work in the $\mathbb{F}_2-$field produces some unexpected results?
Let's see: Assume that we have a square $A$ matrix that has $\mathbb{F}_2-$ linearly independent rows. The column vector process $\boldsymbol{v}'$, say of dimension $5\times 1$ is written
$$\boldsymbol{v}' = A\boldsymbol{v} = \left[\begin{matrix}
v_1'(v_0,...)\\
v_2'(v_0,...)\\
v_3'(v_0,...)\\
v_4'(v_0,...)\\
v_5'(v_0,...)\\
\end{matrix}\right]$$
Now assume that $w=3$ and, say, that the $1$'s in $A$ as dispersed such that we have
$$ v_2' = v_0+v_1+v_5,\qquad v_4' = v_2+v_3+v_5$$
Consider the conditional probability (under $\mathbb{F}_2-$ arithmetic)
$$P_{\mathbb{F}_2}(v_2' =1\mid v_4'=0) = P_{\mathbb{F}_2}(v_0+v_1+v_5 =1\mid v_2+v_3+v_5=0)$$
If the conditioning statement is to affect the probabilities of $v_2'$, it will do so through $v_5$: the fact that $v_2+v_3+v_5=0$ must affect the probabilities related to $v_5$. Under the "usual" arithmetic this would be obvious: it would mean that $v_5$ should equal zero. What happens under $\mathbb{F}_2-$ arithmetic?
We can examine
$$P_{\mathbb{F}_2}(v_5 =1\mid v_2+v_3+v_5=0) = \frac{P_{\mathbb{F}_2}(\{v_5 =1\}\land \{v_2+v_3+v_5=0\})}{P_{\mathbb{F}_2}(v_2+v_3+v_5=0)}$$
The possible values of $v_2+v_3+v_5$ under $\mathbb{F}_2-$ arithmetic are

from which we get the following contingency table

Therefore
$$P_{\mathbb{F}_2}(v_5 =1\mid v_2+v_3+v_5=0) = \frac{2p^2(1-p)}{(1-p)^3+3p^2(1-p)}=\frac{2p^2}{1-2p+4p^2} \neq p$$
except when $p=1/2$ - but the set up explicitly specifies that $p<1/2$ . So we conclude that
$$P_{\mathbb{F}_2}(v_5 =1\mid v_2+v_3+v_5=0) \neq P_{\mathbb{F}_2}(v_5 =1)$$
and so
$$P_{\mathbb{F}_2}(v_2' =1\mid v_4'=0) \neq P_{\mathbb{F}_2}(v_2' =1)$$
I have shown that, in general, the elements of the vector process $\boldsymbol{v}'$ are not independent (although they have identical marginals), even under $\mathbb{F}_2$-arithmetic. I have found and read the lemma in the paper the OP mentions. There is no actual proof, just a verbal assertion that they are independent, due to the $\mathbb{F}_2$-linear independence of the rows of $A$. Hopefully, I am mistaken, but for the moment it appears the assertion is not valid.
5) Now what?
Not much. The joint distribution of the random vector will depend on how the $1$'s are allocated in matrix $A$. Without a specific form, the various measures of distance between distributions become vacuous. Intuitively, if $w$ is small relative to the length of the rows of $A$, then one can expect/hope, that the dependence will be relatively weak, and so pretending that the vector is i.i.d. won't hurt much... but without knowing the joint distribution, one cannot really tell... Copulas for discrete r.v.'s suffer from identification issues... I am still thinking about it, but I am not optimistic.
Comment: Yep. That's what I meant except that each $v_i'$ is an element of $\mathbb{F}_2$, so the sum is modulo $2$ (i.e., bits are xor'd). So we only have $P(v_i'=i)$ for $i=0,1$. If an simpler form of the probability mass function is of relevance here, I can prove $P(v_i'=1)=\frac{1-(1-2p)^w}{2}$ (and $P(v_i'=0)=1-P(v_i'=1)$) for any $w$. And that's about all I could figure out myself when I asked this. As you say, I also think $v_i'$ are correlated so $\boldsymbol{v}'$ can't be i.i.d. Bernoulli.
Comment: (...cont.) But, for instance, Lemma 1 of [this paper on data compression](http://dx.doi.org/10.1109/LCOMM.2011.122810.102182) appeared in IEEE Comm. Lett. says otherwise. They claim that $v_i'$ are independent because rows of $A$ are linearly independent, which I thought was a mistake on the authors' side, although I might be missing something obvious. In any case, if I'm correct here, I should be able to prove that $v_i'$ and $v_j$ are not independent directly by showing $P(v_i'=1)P(v_j'=1)\not=P(v_i'=1\cap v_j'=1)$, for example.
Comment: (...cont.2) So, the question is the one I asked last: **If not, can I approximate it as one if $r_i$ and $r_j$ have only few 1's at the same columns for all $i\not=j$?** For example, are there known standard methods for evaluating how close a given distribution like $\boldsymbol{v}'$ is to i.i.d. Bernoulli? Thanks for your help. I wanted to upvote your answer, but please wait until I get 10 more reps!
Comment: This is a case where different backgrounds make communication fail. The "...an element of $\mathbb{F}_2$, so the sum is modulo $2$ (ie bits are xor'd)..." was completely lost to me (and I am not even sure exactly what that means), because the information "each row has exactly $w$ $1$'s" was so clear and definite. So can you please take the matrix $A$ that appears in my answer and write it as you meant it to be written? Then maybe I can do something more about the question.
Comment: To make it as elementary as possible, what I mean is that computation should be $0+0=1+1=0$, $1+0=0+1=1$, $0\cdot1=1\cdot0=0\cdot0=0,$ and $1\cdot1=1$, that is, addition is the "mod 2 sum" in the elementary math language (or the "exclusive OR" operation in the elementary comp sci language). And multiplication is the natural, commutative one: you multiple anything by $0$, and you get $0$. And multiplying by $1$ doesn't change anything. And you don't care if it's $a\cdot b$ or $b\cdot a$; they're the same. For example, $1+1+0+1=1$.
Comment: So, in your example, if the realizations of $v_0$ and $v_3$ are both $1$, then $v_1' = v_0+v_3=1+1=0$. I'm just saying all computation should be over the finite field of order $2$, i.e., the unique algebra with two elements that have the four operations: addition, subtraction, multiplication, and division. Without the notion of the finite field of order $2$, "linearly independent" doesn't make sense, for example. As an example, the vectors $(0,0,1)$, $(1,0,1)$, $(1,0,0)$ are linearly dependent because the bitwise sum of the last two is the first" $(1,0,1) + (1,0,0) = (1+1,0+0,1+0) = (0,0,1)$.
Comment: Ah, and your matrix is not full rank either. If you sum up the last three columns, you get the first column. Since the column-rank of a matrix is equal to its row-rank, the rows must be linearly dependent, too. I didn't check if your $A$ was full-rank or not over $\mathbb{F}_2$. But obviously it's not.
Comment: To your next-to-last comment: So the way I wrote matrix $A$ is consistent with the set up. What changes is how we define and handle the next step,  $A\boldsymbol{v}^T$.
Comment: Exactly. But the linear dependence should be checked by using the computation rules I described above. Your matrix just happened to have linearly dependent columns when checked over $\mathbb{F}_2$.
Comment: If the last three columns of $A$ are added, the last element is $2$ - and its determinant is non-zero. So the concept of "linear (in)dependence" is to be understood specifically w.r.t $\mathbb{F}_2$.
Comment: Yeah, you can understand that way. It's more like there's no such thing as element $2$ in the fine field of order $2$ though. You only have $0$ and $1$, and no matter what computation you do, you can't get $2$ because it doesn't appear in the computation rules I described. If you want to use $2$ and other numbers, just think that any even number is $0$ and any odd number is $1$. So, if you add the last three columns of your $A$, the last element is $2 = 0$.
Comment: It's clarified now. I wonder how easy is to construct a matrix of full column rank under such restrictive arithmetic (coupled with the restriction that each row must have the same number 0f $1$'s)... I am thinking about it.
Comment: I conjecture that $w$ should be an odd number, at least as a necessary condition for linear independence. For $w$ an even number, I think the sum of the $n-1$ columns will always equal the $n$th column (in $\mathbb{F}_2$).
Comment: Oh, coming up with a full-rank matrix over $\mathbb{F}_2$ of constant row weight isn't difficult. For instance, you can just take the point-line incidence matrix of affine geometry over $\mathbb{F}_q$ with $q$ odd. For instance, using the affine plane on $9$ points, we have $9 \times 12$ matrix with each row having $4$ $1$'s (and $5$ $0$'s). And it's surely of full rank.
Comment: So, assuming there is a bunch of good matrices $A$, how do I evaluate the similarity/difference between $\boldsymbol{v′}$ and an i.i.d. Bernoulli process?


Change domain on series - Counting aplitudes

Question: If I have a function
$$f(t) = y$$
where $t$ & $y$ are positive Integers
for $t = \{1,2,3,4,5,6,7,8\} \to y = \{1,1,1,2,1,2,3,1\}$
How can I create a function $g(y)$ such that it counts the number of times a value of $y$ occurs. For instance if we used the above data $g(y)$ would be the following:
$g(y) = \{5, 2, 1, 0\}$ for the $y$ values $\{1,2,3,4\}$
Once I have this I need to represent this as a function $k(t) = \max R$
$$R = y * g(y) +  y * g(y+1) + y * g(y+2)...+ y * g(y+n)$$
for all values  $g(y+n) > 0$.
Please can someone help me represent $k(t)$ more mathematically. Would something like the Discrete time Fourier Transform help with $f(t) \Longrightarrow g(y)$
Thanks a mill
Comment: Do you need that for a program? If it's just a mathematical definition you need for $g$, a definition in words is perfectly fine.
Answer: One way you could do this is with the Kronecker delta function, then you can define $g$ as follows
$$g(y)=\sum_{k\in t} \delta_{y,f(k)}$$
with $t=\{1,2,3,\ldots,8\}$ or whatever your domain for $f$ is.
Taking your example, suppose you want to compute $g(1)$, then you add up all the $\delta_{1,f(k)}$ for all $k \in t$. But since $f(k)=1$ only 5 times, the $\delta_{1,f(k)}$ will be equal to $1$ only 5 times and all other times it will be $0$. Therefore the sum is $5$, which is indeed what we want.
Comment: Thanks for this, I ended up creating my own version of this Kronecker delta function :)

(((x-y)/(y-x))+1)/2

This gives me 1 when x=y and 0 for anything else


Proof that nonconstant polynomial cannot have the same value at all integer points

Question: I am reading the solution to the Project Euler problem 28 here, specifically the one under 'Deriving a non-iterative formula'. That solution first deduces the degree of the polynomial, and then constructs a polynomial for that degree. What I do not understand is why the differences method (used by the author) successfully finds the degree of the polynomial. Yes, I understand the intuition behind it. Taking the differences between two points is just short for rate of change AKA derivative, and of course if you take a derivative of a polynomial enough times you will get a constant. However how do I know that this works consistently? That is, how do I know there is not some nonconstant polynomial out there that gives the same points at f(0), f(1), f(2), f(3), f(4), and then goes to something else at f(5) and beyond? If it is impossible for a nonconstant polynomial (of degree 1 or greater) to have the same value at consecutive integer points (e.g., f(0), f(-1), etc), please prove.
Comment: Do you mean at *all* integers? Certainly it can be equal to itself for as many consecutive integers as you want, provided it's finitely many.
Comment: Yes I meant finitely many. If it were for all it would be a constant polynomial. So you're saying that a nonconstant polynomial can be constant for finitely many integers? That would mean the author's method/differences method is not guaranteed to work in finding the degree of the polynomial. Please advise.
Comment: I think I understand the problem you're having but am not up to writing an answer. Note that when you compute the $n$th difference the result is $\sum_i{(-1)^i\binom{n}{i}f(x+i)}$, so successive differences use more and more points.
Comment: (I think I recall that formula correctly, but the sign may be off.)
Comment: That was a nice formula, but I'm more interested in knowing if this method is guaranteed to work for all polynomials. So far, I'm not convinced.
Comment: Ok, well there's a proof in Enumerative Combinatorics volume 1 by Richard Stanley, which is available online.
Answer: The binomial polynomial
$$
\binom xn=\frac{x(x-1)(x-2)\cdots(x-n+1)}{n!}
$$
has the property that it takes the same value, $0$, at the $n$ consecutive integers $0,\cdots,n-1$, and beyond that, has the pleasant property that at $x=n$, it takes the value $1$. Defining $\binom x0$ to be the constant polynomial $1$ allows you to get a polynomial of degree $n$ taking any specified values whatever at $0,\cdots,n$ as a linear combination of the binomial polynomials. I think a simple inductive argument will demonstrate this.
EDIT: Let me be more complete. Let's consider the set of polynomials of degree less than $n$, and for typographic convenience, let me write $C_k(x)=\binom xk$. Now the dimension of the space of polynomials of degree less than $n$ is $n$, spanned by $1,x,\cdots,x^{n-1}$, but another spanning set consists of all the $C_k$ for $0\le k<n$. You see this most clearly by noting that the degree of the polynomial $C_k$ is exactly $k$. Thus we can say, if $\deg(f)<n$, that there are coefficients
$a_0,a_1,\cdots,a_{n-1}$, uniquely determined by $f$, such that $\,f=\sum_{k=0}^{n-1}a_kC_k$. Now use the difference operator $\Delta$: you're using $(\Delta(f))(x)=f(x+1)-f(x)$. And use also the fact that
$\Delta(C_k)=C_{k-1}$ and $\Delta(C_0)=0$. Now we can move ahead:
$$
\begin{align}
f&=a_0C_0+a_1C_1+\cdots a_{n-1}C_{n-1}\\
f(0)&=a_0\\
\Delta f&=a_1C_0+a_2C_1+\cdots a_{n-1}C_{n-2}\\
(\Delta f)(0)&=a_1\\
\Delta^2f&=a_2C_0+a_3C_1+\cdots a_{n-1}C_{n-3}\\
(\Delta^2 f)(0)&=a_2\\
\vdots\\
\Delta^{n-1}f&=a_{n-1}C_0=a_{n-1}\,.
\end{align}
$$
And that's why the method of differences always works.
Comment: I don't think that that conclusion is supported by my answer.
Comment: So the method of differences doesn't always work?
Comment: I still don't understand.
Answer: Just subtract that constant from the polynomial to get a new one which is zero at an infinite number of integer points, then use the fundamental theorem of algebra.  Alternatively, use the fact that differentiating a polynomial reduces its degree, so there is some $n$ such that its $n^{\text{th}}$ derivative is identically $0$.  In the problem being discussed, the difference method works because the answer happens to be a polynomial, and to know this in advance requires a certain intuition.  If instead the $k^{\text{th}}$ cell of the spiral had value $2^k$ then this method would not work.
Comment: My question was why the method of successive differences works on a polynomial.
Comment: I may have misunderstood the question somewhat but I mention that differentiating a polynomial reduces its degree, note that $P(x+1)-P(x)$ is also a polynomial of lesser degree.
Comment: I think I see the issue now after rereading. Given that it is a polynomial, you want a way to know what polynomial it is by sampling a finite number of points.  There is no way to do that, all we can do is get a lower bound on its degree.
Comment: The difference method simply yields a guess that we then have to prove is true with induction for example.


drawing a map of the Bronx - d3.geo.path()

Question: Trying to take GIS data of the
zip codes of the Bronx and turn it into a map using d3.js.  But I am having trouble rendering.  Could you show me proper use of d3.geo.path() ?

Here is a typical line of d[9][5].rings[0] from https://nycopendata.socrata.com/Social-Services/Bronx-Zip-Code-Boundaries/p8wz-d63u
[ [ -73.84463693999993, 40.90475939500004 ], [ -73.84443733899991, 40.90423928800004 ], [ -73.84443555299993, 40.904234630000076 ],  ...] ]

Answer: You need to pass your array into path() to get it to return screen xy:
.attr("d",function(d) { return path(d[9][5].rings[0]); })


Inheritance in Null Safety - Flutter

Question: I'm working on Flutter Clean Architecture. Initially I developed my project without sound null-safety. I recently migrated it to null-safety.
Migrating to null-safety was pretty smooth but unfortunately there is an issue with inheriting classes that I'm unable to resolve.
Here is a sample of my code I'm working with:
ENTITIES:
UserEntity:
class UserEntity extends Equatable {
    final int userID;
    final String email;

    const UserEntity({required this.userID, required this.email});

    @override
    List<Object> get props => [userID, email];
}

CourseEntity:
class CourseEntity extends Equatable {
    final int courseID;
    final String courseName;

    const CourseEntity({required this.courseID, required this.courseName});

    @override
    List<Object> get props => [courseID, courseName];
}

DataEntity:
class DataEntity extends Equatable {
    final UserEntity? user;
    final CourseEntity? course;

    const DataEntity({required this.user, required this.course});

    @override
    List<Object> get props => [user, course];
}

MODELS:
UserModel:
class UserModel extends UserEntity {
    const UserModel({
        required int userID,
        required String email,
    }) : super(userID: userID, email: email);

    factory UserModel.fromJson(Map<dynamic, dynamic> json) {
        return UserModel(
            userID: json["userID"],
            email: json["email"],
        );
    }

    Map<String, dynamic> toJson() {
        return {
            "userID": userID,
            "email": email,
        };
    }
}

CourseModel:
class CourseModel extends CourseEntity {
    const CourseModel({
        required int courseID,
        required String courseName,
    }) : super(courseID: courseID, courseName: courseName);

    factory CourseModel.fromJson(Map<dynamic, dynamic> json) {
        return CourseModel(
            courseID: json["courseID"],
            courseName: json["courseName"],
        );
    }

    Map<String, dynamic> toJson() {
        return {
            "courseID": courseID,
            "courseName": courseName,
        };
    }
}

DataModel:
class DataModel extends DataEntity {
    const DataModel({
        required UserModel? user,
        required CourseModel? course,
    }) : super(user: user, course: course);

    factory DataModel.fromJson(Map<dynamic, dynamic> json) {
        return DataModel(
            user: UserModel.fromJson(json["user"]),
            course: CourseModel.fromJson(json["course"]),
        );
    }
}

LOCAL DATASOURCE:
Saving Data Locally:
abstract class LocalDataSource {
    Future<void> saveData(DataModel model);
    Future<void> saveUser(UserModel user);
    Future<void> saveCourse(CourseModel course);
}

class LocalDataSourceImpl implements LocalDataSource {
    @override
    Future<void> saveData(DataModel model) async {
        await saveUser(model.user);
        await saveCourse(model.course);
    }

    @override
    Future<void> saveUser(UserModel model) async {
        final box = await Hive.openBox("USER");

        return box.put("user", model.toJson());
    }

    @override
    Future<void> saveCourse(CourseModel model) async {
        final box = await Hive.openBox("COURSE");

        return box.put("course", model.toJson());
    }
}

Explanation:
I hope all the sample classes are easy to understand.
There are 2 entities User and Course. The Data entity is a combination of these 2 entities. The models are extending these entities which means that the entities are the parent classes for their respective models.
The class LocalDataSource is used to store data locally on the device. I'm using Hive to cache the data. There are 2 main futures namely saveUser and saveCourse. The saveData future is the combination of these 2 futures just like the entities.
Problem:
The problem exists in the future saveData of class LocalDataSourceImpl. The future requires 1 argument i.e. DataModel. The other futures also require 1 argument i.e. UserModel and CourseModel.
In saveData(model) future, when I provide the values for respective arguments to saveUser and saveCourse as saveUser(model.user) and saveCourse(model.course), this is the error that I receive on arguments passed:

The argument type 'UserEntity' can't be assigned to the parameter type 'UserModel'.dart(argument_type_not_assignable)

Workarounds:
First workaround could be using getters:
class DataModel extends DataEntity {
    final UserModel? _user;
    final CourseModel? _course;

    const DataModel({
        required UserModel user,
        required CourseModel course,
    }) : _user = user,
         _course = course, super(
             user: user,
             course: course,
         );

    UserModel? get user => _user;
    CourseModel? get course => _course;
    ...
}

Second workaround could be overriding fields:
class DataModel extends DataEntity {
    final UserModel? user;
    final CourseModel? course;

    const DataModel({
        required this.user,
        required this.course,
    }) : super(
             user: user,
             course: course,
         );

    ...
}

I'm confused if any of these 2 is a good practice, because there must be no assignment error as Models are actually the subclasses of Entities.
Thanks in advance!
Comment: I used it once when I had one class with method taking the other class (something like classA.function(ClassB argument)) - and then I extended both (classA1extendsClassA(ClassB1extendsB argument) - and I had to use covariant for this to work). I think your case is simpler; so your answer makes sense.
Comment: Try using covariant keyword: ````Future saveData(covariant DataModel model) async {````.
Comment: @Andrija unfortunately, covariant doesn't work in this case. Covariant is used when 2 classes are extending same parent class. I hope I'm not wrong.
Answer: Simplest and Easiest way is to add type cast, and it works great!
class LocalDataSourceImpl implements LocalDataSource {
    @override
    Future<void> saveData(DataModel model) async {
        await saveUser(model.user as UserModel);
        await saveCourse(model.course as CourseModel);
    }
    ...

Inheritance in Null Safety - Flutter


Correspondence between inductively definable and countable

Question: Working within ZFC:
Is the collection of all countable sets (call it $C$) a well-defined set, or is it a proper class? If $C$ is a set, I would suspect it's at least uncountable. For example the elements of $P(\mathbb{N})$, the power set of $\mathbb{N}$, are countable and hence are elements of $C$ (i.e. $P(\mathbb{N})\subseteq C$). The presence of an uncountable subset in $C$ would imply that $C$ itself is uncountable, no?
Similarly, is the collection of all inductively-definable sets (call it $I$) a well-defined set or is it a proper class? Here, one can take "inductively-definable" to be same concept laid out in A Mathematical Introduction to Logic by Enderton (see section 1.4). If $I$ is a set, is it countable or uncountable?
I suspect that there is a bijective correspondence between the collections $C$ and $I$. Hence, I would anticipate $I$ must be uncountable as well. For if $I$ were countable, the aforementioned bijection would be between a set which is uncountable and a set which is countable; this would be nonsensical. But does such a bijection exist to begin with, and if so how can we formalize this correspondence? In particular, is it the case that a set is inductively-definable iff it is countable?
Comment: $C$ is a proper class, since $\{x\}$ is finite (hence countable) for every set $x$. However, the set of *hereditarily* countable sets is a well-defined set, and is denoted as $H_{\omega_1}$.
Answer: Both of the collections you mention are proper classes. If the collection of countable sets were a set, then the collection of finite sets would be set. But the latter collection is a proper class. If the collection of inductive sets (in the sense of Enderton) were a set, then the collection of limit ordinals would be a set (since limit ordinals contain the empty set and are closed under ordinal successors). However, the latter collection is a proper class as well.


Javascript Chamada de função com parâmetro

Question: Preciso chamar uma função em Javascript onde um de seus parâmetros é uma função.
Neste caso, como faço para passar parâmetros dentro da chamada da função?
Ex: (Função que será chamada primeiro:
function getWS(data, success) {
    $.ajax({
        type: 'GET',
        url: 'MinhaUrl',
        data: data,
        async: false,
        crossDomain: true,
        dataType: 'json',
        success: success,
        error: error,
    });
}

Função em caso de sucesso na chamada acima:
function preencheLista(data, lista)
{
    $.each(data, function (i, item) {
        lista.push({ "id": item.id, "nome": item.nome })
    });
}

Chamada:
//Aqui que está minha dúvida. Como passar data e marcas para esta função)
var marcas = [];
getWS(data, preencheLista(data, marcas));

Comment: O problema maior é você querer usar ajax síncrono. Você devia manipular a lista de marcas apenas de dentro do callback de sucesso do ajax.
Answer: Para o devido efeito podes usar a função $.proxy() do jquery!
Esta função recebe uma função e retorna uma nova que sempre tera um contexto particular.
Para ser mais concreto veja o exemplo do seu codigo funcionando no jsfiddle

var url = 'https://jsonplaceholder.typicode.com/posts';

var getWS = function(data, success) {
  $.ajax({
    type: 'GET',
    url: url,
    data: data,
    //async: false, //deprecado
    crossDomain: true,
    dataType: 'json',
    success: success,
    //error: error,
  });
}

var preencheLista = function(data, lista) {
  $.each(data, function(i, item) {
    lista.push({
      "id": item.id,
      "nome": item.title
    }) // alterado item.nome para item.title pois o objecto de retorno nao possui o atributo nome
  });
}

var marcas = [];

getWS({}, $.proxy(function(data) {
  preencheLista(data, marcas);

  //adiciona o resultdado a lista no html para visualização
  $(marcas).each(function(i, item) {
    $("ul").append(`<li>${item.id} - ${item.nome}</li>`)
  });

}));


Prove that a simple graph with $2$ vertices without triangles inside has at most $n^2$ lines.

Question: A triangle in a graph is a subset of the node set $\{a, b, c\} \subseteq V (G)$ such that $\{a, b\}, \{a, c\}, \{b, c\} \in E (G).$ Prove with induction for all $n \in \mathbb{N}$ that a graph without a triangle with $2n$ nodes has at most $n^2$ edges.
Comment: Welcome to MSE.  You'll get a lot more help, and fewer votes to close, if you show that you have made a real effort to solve the problem yourself.  What are your thoughts?  What have you tried?  How far did you get?  Where are you stuck?  This question is likely to be closed if you don't add more context.  Please respond by **editing the question body.**  Many people browsing questions will vote to close without reading the comments.   Also, please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to typeset math on this site.
Answer: The crucial part of the proof is to choose two vertices $u,v$ say, which are connected.
Then there are at most $2n-2$ edges from these points to other points (they cannot both be joined to the same point).
Then by induction the number of edges is at most $1+(2n-2)+(n-1)^2=n^2$.
Comment: Thanks for the response, i do not understand your induction step. Where did the 1 and the (n-1)^2 come from ?
Comment: The "1" is the edge between u and v. Then there are at most  $(n-1)^2$ edges between the $2(n-1)$ edges ( by the inductive hypothesis).


Load resources from another JAR in Warework PC-MAC Distribution

Question: I'm writing a program with Warework Connected Distribution for PC-MAC that consists of three JARs: one with the Java code of my application, another with the resources of the application and the last one is the Warework JAR.
The JAR with the Java code contains a default configuration while the resources JAR contains the main configuration of the application (used in most cases).
As many resources in both JARs have the same name, how do I tell Warework to load the configuration files from a specific JAR?
Answer: You can create a dummy class (an empty class, without nothing) in your resources JAR and configure Warework to use this class to load the configuration of your application from the resources JAR. Just provide the dummy class when you create the Scope, for example:
ScopeFacade system = ScopeFactory.createFacade(Dummy.class, "config", "app-name");

or:
ScopeFacade system = ScopeFactory.createTemplate(Dummy.class, "full", "app-name");

And that's it. Now you should be able to read resources from your resources JAR.


Set single raster to NA where values of raster stack are NA

Question: I have two 30m x 30m raster files which I would like to sample points from.  Prior to sampling, I would like to remove the clouded areas from the images.  I turned to R and Hijman's Raster package for the task.
Using the drawPoly(sp=TRUE) command, I drew in 18 different polygons.  The function did not seem to allow 18 polygons as one sp object, so I drew them all separately.  I then gave the polygons a proj4string matching the rasters', and set them into a list.  I ran the list through a lapply function to convert them to rasters (rasterize function in Hijman's package) with the polygon areas set to NA, and the rest of the image set to 1.
My end goal is one raster layer with the 18 areas set to NA.  I have tried stacking the list of rasterized polygons, and subsetting it to put set a new raster to NA in the same areas.  My reproducible code is below.
library(raster)
r1 <- raster(nrow=50, ncol = 50)
r1[] <- 1
r1[4:10,] <- NA
r2 <- raster(nrow=50, ncol = 50)
r2[] <- 1
r2[9:15,] <- NA
r3 <- raster(nrow=50, ncol = 50)
r3[] <- 1
r3[24:39,] <- NA

r4 <- raster(nrow=50, ncol = 50)
r4[] <- 1

s <- stack(r1, r2, r3)

test.a.cool <- calc(s, function(x){r4[is.na(x)==1] <- NA})

For whatever reason, the darn testacool is a blank plot, where I'm aiming to have it as a raster with all values except for the NAs in the stack, s, equal to 1.
Any tips?
Thanks.
Answer: Doing sum(s) will work, as sum() returns NA for any grid cell with even one NA value in the stack.
To see that it works, compare the figures produced by the following:
plot(s)
plot(sum(s))

Answer: I posted this question on the R-Sig-Geo forum, as well, and received a response from the package author.  The two simplest solutions:
Use the sp package to rbind my polygons into one, then rasterize the polygon.
p <- rbind(p1, p2, p3...etc., makeUniqueIDs = TRUE)

r4 <- raster(nrow=50, ncol = 50)
r4[] <- 1
mask <- rasterize(p, r4)
mask[mask %in% 1:18] <- 1
#The above code produces a single raster file with
#my polygons as unique values, ready for masking.

And the second simple solution, as just pointed out by Josh O'Brien:
m <- sum(s)
test <- mask(r4, m)

The R community rocks.  Problem solved (twice) within an hour.  Thanks.
Comment: Thanks for posting this. I was right now in the process of editing my answer to note that this farther upstream solution is in fact the better way to solve your problem, but you saved me the effort!
Comment: As I look closer at the response and package PDF, don't even need to rasterize the polygon.  You can use the mask function in raster package with a spatial polygon.
Comment: No prob. By the way, if you've drawn a **bunch** of polygons and have them all in a list (as a result of doing, say `x <- lapply(1:40, drawPoly)`), the following will be an equivalent but cleaner way to combine them into a single SpatialPolygons object: `do.call(rbind, c(x, makeUniqueIDs=TRUE))`. i.e. that'll be easier and less error-prone than typing `rbind(x[[1]], x[[2]], x[[3]], ..., x[[40]], makeUniqueIDs=TRUE)` .
Answer: I'm not familiar with the package you are using, however looking at the final line in your code, I think the issue might be here:
 function(x){r4[is.na(x)==1] <- NA})

It doesn't look like calc will do much with that. It is setting the values of r4 indexed by the NAs of x and setting those to NA.
What then?   If anything, maybe:
 function(x){r4[is.na(x)==1] <- NA; return(r4) })

Although, it's not clear if that is even what you are after.
Comment: Sure, makes sense.  That was my first code, which produces this error "Error in setValues(out, x) :
  values must be numeric, integer, logical or factor", which is an error derived from the raster package, if I'm not mistaken.
Comment: if `r4` is a `raster` object, can it be assigned logical `NA` values?  That aside, there is no point in having a function that does nothing simply because it was giving you an error ;)
Comment: For whatever reason, this works:  r4[is.na(r2)==1] <- NA, but this doesnt r4[is.na(s)==1] <- NA
Comment: Well, start by determining the differences between `r2` and `s` and I'm certain that will lead you to your answer.   Useful tools are `str(.)`, `dput()` `is()`.
Answer: You were on the right track. The [ operator is defined for rasters and raster stacks, so you could just use the single line:
r4[ any(is.na(s) ) ] <- NA
plot(r4)

If you wanted to use calc you could have used it like this:
r4 <- calc( s, function(x){ ( ! any( is.na(x) ) ) } )
r4[is.na(r4)] <- NA
plot(r4)

Comment: Thanks, Simon.  Calc would have been the right move since I have a 12,000,000 cells in each raster layer, right?  I think I read that arithmetic operators can freeze up on large datasets.
Comment: Yes `calc` is the way to go because it will operate on large datasets in chunks. I am curious, does `sum` work on raster layers that big?
Comment: It's summing a stack with nlayers=12, ncell = 12,072,775 in less than a minute.  Impressive.
Comment: Using sum inside `calc` or just using `sum(s)`? It's good to know because I often work with large rasters and I'd normally plump for `calc` but I can't see in this case why it would perform better than a simple call to `sum` as Josh recommends.
Comment: That was just using the sum() function, as per Josh's rec.


docusign update parent field on complete

Question: I am new to docusign integration with salesforce. I am following a simple flow of

User logs into sfdc

User goes to an object A and clicks the custom button (exactly same one as in documentation) selects a template and sends to user X.
The receiver X will sign and send it back.
My question is - after step 3, is there any way to update a picklist field in the object A indicating that the document is  signed and received.

I do not want to do a trigger on document status and when I tried process builder, cannot see the parent picklist field.
So, I want to know if docusign has any feature to solve my problem.
Thanks
KR
Answer: The DocuSign for Salesforce (DfS) app on the App Exchange is an end product (ie. end-user product).  If it's current feature set does not solve all of your business needs then you can always do an API integration and use the DocuSign Connect module.
Using DocuSign Connect you can setup an external http listener where real time status/event updates are sent and can be parsed.  At that point you can write whatever logic you need to do inside or out of Salesforce.  For more info on DocuSign Connect see this here.
Otherwise if you want to use in conjunction with DfS, this can be done only by trigger because

Workflows won't help because workflow can't update related (via Lookup field) object.
Process builder also won't help because of the same issue (can't update related object).
Formula fields won't help because DocuSign Status to Salesforce object is 1 to Many relationship.

The only correct solution is a trigger (it's very simple, 10 lines of code, just replace my TODOs with your info):
trigger UpdateOpportunityOnEnvelopeCompleted on dsfs__DocuSign_Status__c (after update)
{

    // get a set of all completed docusign statuses with opportunities
    Set<Id> opportunityId = new Set<Id>();
    for(dsfs__DocuSign_Status__c  status : Trigger.new) {
       if (status.dsfs__Opportunity__c != null && status.dsfs__Envelope_Status__c== 'Completed') {  // TODO: Replace dsfs__Opportunity__c with the object you want to update, say dsfs__Contact__c or dsfs__Lead__c
           opportunityId.add(status.dsfs__Opportunity__c);                                                                                // TODO: Replace dsfs__Opportunity__c with the object you want to update
       }
    }

    // retrieve these opportunities
    // TODO: Replace DeliveryInstallationStatus__c with the field you want to update, replace Opportunity to your object name, ex: Contact or Lead
    List<Opportunity> opportunities = [SELECT Id, DeliveryInstallationStatus__c FROM Opportunity WHERE Id IN :opportunityId];

    // update these opportunities
    for(Opportunity o : opportunities) {                  // TODO: Replace Opportunity with your object name
        o.DeliveryInstallationStatus__c = 'Completed';    // TODO: Replace DeliveryInstallationStatus__c with the field you want to update , replace 'Completed' with field value you want to set
    }
    update opportunities;
}


Methods to track player movements including distance

Question: What is the best way to measure althetic performance in a game of football. I am thinking some sort of consumer level GPS product, a bit like this product but that seems not available on a personal level.
Does what I am looking for exist?
Answer: If you're talking about measuring your own performance, there are certain shoes which have a gps tracker installed. For example the Adidas F50 adizero
If you don't want to buy an extra shoe for this there are also various sports watches with gps-trackers installed. As mentioned in comments, wearing accessories is not allowed in official games.
Comment: In an official game you would not be allowed to wear a watch though.
Comment: Yeah true. Didn't think about that, thx.


Second-Order, Linear Inhomogeneous Recurrence Relation With Constant Coefficients

Question: How does one solve the general recurrence relation
$$s_n=\alpha s_{n-1}+\beta s_{n-2}+\zeta(n)?$$
Comment: [This PDF](http://www.ee.ntu.edu.tw/~yen/courses/dm-s2012/Chap05.pdf) gives one method; the section on non-homogeneous recurrences starts halfway through, on page $15$.
Comment: Do you have an explicit formula for $\zeta$?  Do you know about solving linear difference equations with constant coefficients?  The process is quite similar to solving differential equations.
Comment: $\zeta$ is either a constant, $n$, or $n^2$.
Answer: A particular solution of the difference equation
$$s_n=\alpha s_{n-1}+\beta s_{n-2}+a+bn+cn^2\qquad(n\geq2)$$
can be found with the "Ansatz"
$$s_n=A+Bn+Cn^2,\tag{1}$$
and solving for $A$, $B$, $C$ by comparing coefficients. If $\alpha+\beta\ne1$, i.e.,if the associated homogeneous problem
$$s_n=\alpha s_{n-1}+\beta s_{n-2}\tag{2}$$ has no constant solutions, there will be exactly one admissible triple $(A,B,C)$.
Then solve the homogeneous problem $(2)$ in the usual way and add its general solution $n\mapsto C_1\lambda^n +C_2 \mu^n$ to the particular solution $(1)$ constructed before. Finally fix $C_1$ and $C_2$ using the initial conditions.
The cases $\alpha+\beta=1$ and $\lambda=\mu$ require special consideration, but lead to similar results.
Answer: Here is a foolproof approach. The difference equation is second order so we'll need two initial values, say $s_0,s_1$.
Let $S(x):=\sum_{n=0}^\infty s_nx^n$. Similarly, $Z(x):=\sum_{n=0}^\infty \zeta(n)$. Then
$$s_{n}x^n=\alpha s_{n-1}x^n+\beta s_{n-2}x^n+\zeta(n)x^n$$
summing this from $n=2$ to $\infty$ gives:
$$S(x)-s_1x+s_0=\alpha x(S(x)-s_0)+\beta x^2 S(x)+Z(x)-\zeta(1)x-\zeta(0).$$
Solving this for $S(x)$ gives:
$$S(x)=\frac{Z(x)-\zeta(1)x-\zeta(0)-(1+\alpha x)s_0+s_1x}{1-\alpha x-\beta x^2}$$
meaning that
$$s_n(x)=\left.\frac{d^n}{dx^n}S(x)\right|_{x=0},$$
or just reading off the $x^n$ coefficient. If $\zeta(n)=n$ or $n^2$, then $Z(x)=x/(1-x)^2$ or $Z(x)=-x(x-1)/(1-x)^3$.
I'll leave the pleasure of figuring out the exact coefficients to you. You can save yourself some time by using partial fractions on the expression for $S(x)$ and then use the known nice generating functions like $1/(1-x)=1+x+x^2$, or Newton's formulas for $1/(1-x)^s$, etc.
Answer: The command of Maple rsolve({s(n) = alpha*s(n-1)+beta*s(n-2)+Zeta(n)}, s) produces a long answer which can be seen in the worksheet exported as a PDF file. For example, in the concrete case $$ rsolve({s(1) = 1, s(2) = 1, s(n) = s(n-1)+s(n-2)+Zeta(n)}, s)$$  the answer is $$ -1/5\,\sqrt {5} \left( -1/2\,\sqrt {5}+1/2 \right) ^{n}+1/5\,\sqrt {5}
 \left( 1/2\,\sqrt {5}+1/2 \right) ^{n}+
$$ $$\sum_{n0=3}^n 2/5\,\sqrt {5} \left( -2\, \left( \sqrt {5}+1 \right) ^{-1} \right) ^{
n-{\it n0}} \left( \sqrt {5}+1 \right) ^{-1}\zeta(n0)-
 $$ $$\sum_{n0=3}^n 2/5\,\sqrt {5} \left( -2\, \left( -\sqrt {5}+1 \right) ^{-1} \right) ^
{n-{\it n0}} \left( -\sqrt {5}+1 \right) ^{-1}\zeta(n0)
 $$
Answer: Write your recurrence so there are no index subtractions (my $\zeta$ isn't yours, sorry):
$$
s_{n + 2} = \alpha s_{n + 1} + \beta s_n + \zeta(n)
$$
Define $S(z) = \sum_{n \ge 0} z^n$ (I'm assuming the recurrence is valid from $n = 0$ on, adjust as required). Multiply by $z^n$, sum over $n \ge 0$, recognize the resulting sums:
$$
\frac{S(z) - s_0 - s_1 z}{z^2}
  = \alpha \frac{S(z) - s_0}{z} + \beta S(z)
      + \sum_{n \ge 0} \zeta(n) z^n
$$
The last sum you'd have to get somehow. Typical seasonings are:
\begin{align}
\sum_{n \ge 0} a^n z^n
  &= \frac{1}{1 - a z} \\
\sum_{n \ge 0} k u_n z^n
  &= z \frac{\mathrm{d}}{\mathrm{d} z} U(z)
       \qquad U(z) = \sum_{n \ge 0} u_n z^n \\
\sum_{n \ge 0} \left( \sum_{0 \le k \le n} u_k \right) z^n
  &= \frac{U(z)}{1 - z}
\end{align}
Sometimes you recognize a Cauchy product:
$$
U(z) \cdot V(z)
  = \sum_{n \ge 0} \left( \sum_{0 \le k \le n} u_k v_{n - k} \right) z^n
$$
(particular cases to look out for are $u_k = a^k$, or some other simple form).
Solve the resulting equation for $S(z)$, split into partial fractions. Most of the time use of the generalized binomial theorem allows to read off the coefficients, if they aren't just geometric series:
$$
(1 + x)^{- m}
  = \sum_{k \ge 0} \binom{-m}{k} x^k
  = \sum_{k \ge 0} (-1)^k \binom{k + m - 1}{m - 1} x^k
$$
For qualitative/order of magnitude results, note that $\binom{k + m - 1}{m - 1}$ is just a polynomial of degree $m - 1$ in $k$


Show that the largest root of the following equation is $<n$.

Question: Show that the largest root of the following equation is $<n;n>2$.
$x^2-(n-2)x-2(n-2)$.
On solving I got the largest root $a=\frac{(n-2)+\sqrt {(n-2)^2+8(n-2)}}{2}$ but unable to show how is it $<n$.
I tried for various values of $n$ where the result is holding .But to prove it.
Please help
Answer: Hint: notice that
$$
\boldsymbol{(n-2)^2 + 8(n-2)} < (n-2)^2 + 8(n-2) + 16 = ((n-2) + 4)^2 = n+2.
$$
Now apply this to
$$
a = \frac{n-2 + \sqrt{\boldsymbol{(n-2)^2 + 8(n-2)}}}{2}
$$
Answer: I believe that $n$ is a natural number.
For $n=1$ our equation has no roots.
For $n=2$ it's obvious.
Let $n>2$ and $f(x)=x^2-(n-2)x-2(n-2)$.
Hence, it's obvious that $a>\frac{n-2}{2}$ and $f$ an increasing function on $\left[\frac{n-2}{2},+\infty\right)$.
Let $a\geq n$.
Thus, $$0=a^2-(n-2)a-2(n-2)\geq n^2-(n-2)n-2(n-2)$$
or $0\geq4$, which is contradiction.
Id est, $a<n$ and we are done!
Answer: Assuming $n \ge 2$ . . .

One can just simplify the inequality $a < n$ until it admits to being true:
\begin{align*}
&a < n\\[5pt]
\iff\;&\frac{(n-2)+\sqrt {(n-2)^2+8(n-2)}}{2} < n\\[6pt]
\iff\;&(n-2) + \sqrt {(n-2)^2+8(n-2)} < 2n\\[6pt]
\iff\;&\sqrt {(n-2)^2+8(n-2)} < n+2\\[6pt]
\iff\;&(n-2)^2+8(n-2) < (n+2)^2\qquad\text{[since $n \ge 2$]}\\[5pt]
\iff\;&(n^2 - 4n + 4) + (8n-16) < n^2 + 4n + 4\\[5pt]
\iff\;&n^2 + 4n -12< n^2 + 4n + 4\\[5pt]
\iff\;&-12 < 4\\[5pt]
\end{align*}
which is clearly true.
Answer: Let $f(x)=x^2-(n-2)x-2(n-2).$
Two observations:

Discriminant of the equation $f(x)=0$, $(n-2)^2+8(n-2)>0$, since $n>2$. Then the equation must have two real roots. Then $\min f(x)<0$, and minima is $\frac{n-2}{2}<n$.

$f(n)=n^2-(n-2)n-2(n-2)=4>0$.

Then due to continuity of $f(x)$ largest root must lie in $(\frac{n-2}{2},n)$.
Answer: Hint:   expressing in terms of $x-n\,$:
$$x^2-(n-2)x-2(n-2) \;=\; (x-n)^2 + (n + 2) (x-n) + 4$$
The RHS is clearly positive for $\,x \ge n\,$.


Smallest subring of $\mathbb{C}$ containing arbitrary element $\alpha$

Question: I am working on the following question:

Let $\alpha \in \mathbb{C}$ and let $\mathbb{Z}[\alpha]$ be the smallest subring of $\mathbb{C}$ containing $\alpha$. That is, $\mathbb{Z}[\alpha] := \bigcap S$ for all $S$ which are subrings of $\mathbb{C}$ that contain $\alpha$. Prove that $\mathbb{Z}[\alpha] = \{f(\alpha) | f(x) \in \mathbb{Z}[x]\}$.

My thoughts:
I'm mostly confused by the notation. I think that $\mathbb{Z}[x]$ represents all integer-coefficient polynomials of one variable. So am I to prove that $\mathbb{Z}[\alpha]$ is the set of evaluations of all those polynomials at $x=\alpha$? If so, I don't see how this is itself a subring of $\mathbb{C}$.We've also used the square bracket notation to refer to the ring of Gaussian integers, so $$\mathbb{Z}[\alpha] = \{x+\alpha y | x,y \in \mathbb{Z}\}?$$
If someone could help me understand more precisely what I'm being asked to show it would be much appreciated.
Answer: Your guesses are correct.  $\mathbb{Z}[x]$ is the ring of all polynomials in the variable $x$ with coefficients in $\mathbb{Z}$.  The proof that $\{f(\alpha):f(x)\in\mathbb{Z}[x]\}$ is a subring of $\mathbb{C}$ is very straightforward.  For instance, if you have two elements $f(\alpha)$ and $g(\alpha)$ in this set, then their sum is just $f(\alpha)+g(\alpha)=(f+g)(\alpha)$, which is another element of this set (since $f+g$ is another polynomial in $\mathbb{Z}[x]$).
Once you've shown that this set is a subring, that proves that it contains $\mathbb{Z}[\alpha]$.  For the reverse inclusion, the idea is to prove that for any $f(x)\in\mathbb{Z}[x]$ $f(\alpha)$ is forced to be an element of $S$ if $S$ is a subring containing $\alpha$.  For example, if $f(x)=x^2+3x+4$, then $$f(\alpha)=\alpha^2+3\alpha+4=\alpha\cdot\alpha+(1+1+1)\cdot\alpha+1+1+1+1$$ must in any such subring $S$ because $S$ contains $\alpha$ and $1$ and is closed under addition and multiplication.
(The case of Gaussian integers is a special case--it turns out that for $\alpha=i$, every element of $\mathbb{Z}[i]$ can be written in the form $a+ib$ for $a,b\in\mathbb{Z}$.  In other words, you only need to use linear polynomials $f(x)$ in order to get all the elements of $\mathbb{Z}[i]$.  But this is not true for general $\alpha$, and is not the definition of $\mathbb{Z}[\alpha]$ in general.)
Answer: Indeed, all you have to prove is the set of all evaluations of polynomials with integer coefficients at $\alpha$ is ring. This results from the observations that
$$f(\alpha)+g(\alpha)=(f+g)(\alpha),\quad f(\alpha)g(\alpha)=(fg)(\alpha).$$
If $\alpha$ is algebraic of degree $d$, Euclidean division shows any element of $\mathbf Z[\alpha]$ is represented uniquely as a polynomial in $\alpha$, of degree $<d$.
As to the ring of Gaussian integers, it is the smallest subring of $\mathbf C$ containing $i$, and as $i$ is a root of the polynomial $X^2+1$, its elements are uniquely represented by linear polynomials in $i$.


Simplifying Boolean Two Expressions

Question: I have these expressions
$$(A'+B'+C'+D')(A'+B'+C'+D)(A'+B+C'+D')(A'+B+C'+D)(A'+B+C+D')(A+B'+C'+D')(A+B'+C'+D)(A+B+C'+D')(A+B+C'+D)$$
$$(A'B'C D')+(A'B'C D)+(A'B C D)+(A B'C D')+(A B'C D)+(A B C D)'+(A B C D)$$
And need to simplify both. Addition means $\lor$, multiplication means $\land$ and the prime means $\neg$.
From a similar question that I asked before I know that I have to follow the laws of Boolean algebra, But I do not know how to apply them in this case that I have four variables.
I think i can do this in wolframalpha but i really want to know how to do it
Answer: The first expression reduces to the Boolean product (logical AND) of these five factors
$$(A'+B'+C'+D')(A'+B'+C'+D) = A'+B'+C'$$
$$(A'+B+C'+D')(A'+B+C'+D) = A'+ B + C'$$
$$(A+B+C'+D')(A+B+C'+D) = A + B + C' $$
$$(A+B'+C'+D')(A+B'+C'+D) = A + B' + C' $$
$$ (A'+B+C+D') $$
Looking at the first four, we see that the Boolean product (logical AND) of all four must be $C'$ since all four factors must evaluate to true, and the only way this is possible is if $C'$ is true. So the expression reduces to:
$$ C'(A'+B+C+D') = C'(A'+B+D') $$
The second expression is the logical OR of multiple terms, but looking at the last two:
$$(A B C D)' + (A B C D) = 1$$
So the whole logical OR reduces to $1$ (or logical TRUE).
Comment: i have learned a lot but i have one question. In the second expression I understood the $$ (ABCD)′+(ABCD)=1 $$. But why the whole logical OR reduces to 1
Comment: Logical OR evaluates as true (1) iff at least one of its arguments evaluates as true. So, $x + 1 = 1$, regardless of $x$.
Comment: You're absolutely right, that was an obvious question. I want to thank you for the answer, it has helped me a lot to understand

Simplifying Boolean Two Expressions


Sorting user input dynamically without using inbuilt sorting methods in Java

Question: I am trying to sort some user inputted integers separated by spaces.
Input: 4 2 1 5 9
-- Expected output: 1 2 4 5 9
I can't figure out how to stop the loop after the user presses enter in the loop where i < num. My code works when I enter the integers one by one. Any help would be appreciated
 class javasort {
    public static void main(String[] args) {
    int num, i, j, temp;
    Scanner input = new Scanner(System.in);

    // System.out.println("Enter the number of integers to sort:");
    // num = input.nextInt();

    num = 5; // <-- the user input should be dynamic

    int array[] = new int[num];

    System.out.println("Enter integers: ");

    for (i = 0; i < num; i++)

        array[i] = Integer.parseInt(input.next());
        num = i; // make array as big as input ?

    for (i = 0; i < (num - 1); i++) {
        for (j = 0; j < num - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }

    System.out.println("Sorted list of integers:");

    for (i = 0; i < num; i++)
        System.out.println(array[i]);
}}

Comment: You are missing a pair of curly braces.  The body of your first loop consists of one and only one statement.  Advice: ALWAYS use curly braces for `if` statements and loop bodies.
Comment: See my previous comment. That is not the way to change the array size. And when do you stop reading from input?
Comment: If that is the intended loop, then it is suspicious. If `num = i;`, then `i == num`, so `i < num` is false and the loop will end after one iteration. The line `num = i;` should be removed. `num` is 5 and you want to read 5 numbers from input.
Comment: If your intent is to change the size of the array each time you "find" a new number, then merely changing `num` is not going to accomplish that.
Comment: @RudyVelthuis the array size is supposed to be dynamic. I put in 5 because I couldnt get it to work otherwise
Comment: Put the question about the number of integers to sort back in and read num from input, als you commented out. But **after that**, you should not change num anymore, and also not the size of the array.
Comment: That's what Im asking. I dont know how to stop the loop so that the array can be as big as the user wants.
Comment: The answer by @ElliottFrisch looks good. It says what I said.
Comment: Yes. But if you read my question, I could already get what @ElliottFrisch did, working. I need to sort user inputted integers separated by whitespaces
Answer: Your code was very nearly correct, and then you removed the best hint you had. Use Scanner.nextInt() like
num = input.nextInt();          // <-- get the count.
int array[] = new int[num];
System.out.println("Enter integers: ");
for (i = 0; i < num; i++) {     // <-- don't rely on indentation for flow control.
    array[i] = input.nextInt(); // <-- get a number "num" times.
}

Comment: I understand. But I want the input and output to be like this Input: 4 2 1 5 9 -- Expected output: 1 2 4 5 9 instead of having to press enter after every number.
Comment: The first input has to be your count of numbers. So, 5 4 2 1 5 9 should do it.
Comment: Yes I know. But im looking for a dynamic array. Where the user shouldnt have to specify what length it needs to input. This fix is not working on 5 4 or 55 77 11
Comment: Java arrays have a fixed length, you could use a `Collection`; or you'll have to copy the array to add a new element. Further, you'll need some way to indicate that input is complete. Your requirement to not use inbuilt methods is going to make this **very** difficult. Best of luck!
Answer: So simple, yet so efficient:
Arrays.sort(array);

Comment: I cant use Arrays.sort. That is what I meant without using inbuilt libraries
Comment: guess what: Scanner, System and Integer are inbuilt libraries
Answer: You can use the Bubble sort algorithm. It runs o(n^2) on worst case. Didn't have to put the code here, you can do it. It will only take less than 20 lines.