Why did a moderator delete this question on how the USCIS assigns IOE numbers to N-400 applications?

Question: A moderator deleted this question on how the USCIS assigns IOE numbers to N-400 applications. Why? That's a typical question for US naturalization applicants, e.g. as they try to figure out how long it'll take the USCIS to process their applications when looking at different IOE numbers. 100% on-topic here.
Here is the question:

I wonder how the USCIS assign IOE numbers to N-400 applications. Based on the application date? USCIS field office? Rolling a die? Something else?
Answer: I'm the moderator who deleted the question in response to several flags. While I suppose it might be an interesting technical question about the inner workings of the USCIS, it doesn't appear to actually be on-topic for the site. If you feel differently, I am certainly open to discuss that here on meta. Re-reading it, I'm inclined to leave it closed for that same reason though at this point.
Comment: Estimating naturalization processing times is a black magical art, and generally questions around that topic are usually given the same or similar treatment for that reason. It's arguably even irresponsible for us to try and give the impression anyone can predict the processing time of just about any visa, residency, naturalization application, etc.... They take as long as they take. It's just setting people up for disappointment when reality hits. That's likely why such questions are flagged into oblivion. It can even be dangerous to get someone's hopes up like that.
Comment: "The answer to the question could be used .... Therefore it's on topic." In general, questions should be able to stand on their own, independent of any answers they may (or may not) ever get. Now that's not a hard rule by any stretch. In fact I've only recently come across a question on StackOverflow that I feel is a clear and obvious (and very highly voted) exception that should be made. But it's a nice guideline for many questions. This one doesn't feel like one of those exceptions.
Comment: It's asking for the internal technical workings of some *government* agency to help give the kind of advice that's generally frowned upon on this site (and pretty much on all other immigration forums I've been highly active on).
Comment: Thanks. The answer to the question could be used to determine the naturalization processing times. Therefore it's on topic.
Comment: "Estimating naturalization processing times is a black magical art" not if you know other people with similar IOE and if IOE have some consistent order/grouping. That is the point of the question.
Comment: "...not if you know other people with similar IOE and if IOE" So an applicant comes on to the site and there are indeed other people with a similar IOE. Someone posts an answer to their query that they can 99% expect their application time to be done before < insert date >. A busy case worker finishes his work on one application from that grouping in the afternoon and moves on to the applicant who got advice from Expats. The application looks pretty straightforward, visa/travel is sound, no laws or rules broken, and so on.
Comment: Ok onto the parentage. Hmmm some curiosity there due to some changes in residency, a citizenship being renounced, a couple of others being obtained. Bit adventurous, but nothing we haven't seen on the rare occassion. Ok, the grandparents... wait a minute... *< case worker starts looking more closely, searching up information on various nations >*. **This person might already be a U.S. citizen!** It's been a long day. Let's set the case aside and look into it more deeply over the coming days. Might need to get another set of eyes on this one.
Comment: And their estimated date, courtesy of Expatriates, just slips away.... Ofcourse they have already bought non-refundable tickets to visit their family in < insert country >, even leaving enough time for their passport application to be processed as well. It soon becomes obvious that they will not have their application resolved any time soon, certainly not in time to rush a passport application through on top of whenever other things finally get sorted out.
Comment: I think it's best to give the answer to the OP, then they can form estimate they wish. Estimates are typically statistical, that don't make them useless.


Evaluating a surface integral $\iint A.dS$where $A=y\hat i+2x\hat j-z\hat k$

Question: Question:Evaluate$\iint A.dS$ where $A=y\hat i+2x\hat j-z\hat k$ and S is the surface of the plane $2x+y=6$ in the first octant cut off by the plane $z=4$
My Approach:I roughly sketch and consider $5$ surfaces.
$S_1$ is the triangle in the plane $z = 0$
$S_2$ is the triangle in the plane $z = 4$
$S_3$ is the rectangle in the plane $x = 0$
$S_4$ is the rectangle in the plane $y = 0$
$S_5$ is the plane $2x+y=6$.
The normal vectors to these respective surfaces are $(0,0,-1), (0,0,1), (-1,0,0),(0,-1,0), (2,1,0) $ respectively.Then i evaluate the surfaces $S_1, S_2 ,S_3,S_4,S_5$ And Add them together.But my answer is incorrect.the solution provided by the book is correct.I think my approaching is incorrect.Please explain me how to do this in right way.Thanks in advance.
Answer: It sounds like you are trying to apply the divergence theorem defining 5 surfaces that enclose the volume, but that sounds like more work than evaluating it directly.
The vector normal to the surface is $(1,2,0)$
We will say: $y = 6 - 2x$
$\int\int (6-2x,2x,-z)\cdot(1,2,0) \ dx\ dz$
Limits  $0\le x\le 3, 0\le z\le 4$
$\int_0^4\int_0^3 6+4x \ dx\ dz\\
4(3x+2x^2)|_0^3 = 108$
Since you suggest evaluating all 5 surfaces...
By the divergence theorem we should find that:
$108 + \int_0^4\int_0^6 -y \ dy\ dz + \int_0^4\int_0^3 -2x \ dx\ dz + \int_0^3\int_0^{6-2x} -4 \ dy\ dx = \iiint -1 dV$
But that isn't really what the question has asked.
Comment: That's mean we don't need to consider the sketch..we just focus on the surface mentioned in the question?? Am I right??? @Doug M
Comment: I always recommend a sketch.  Nonetheless, you have just been asked to evaluate the one surface.
Comment: Oh! I got it.i really confused with the sketch and thinking that all surfaces should be consider.Thanks @Doug M
Comment: There are times when you will want to consider whether it is easier to directly evaluate a surface, or to evaluate the remaining surfaces that enclose a volume.  This is not one of those times.


Raid Reconfiguration

Question: We have a Hp DL 380 G6 server. we added extra hard drives and configured them using raid 5. we restarted the server and now we cannot see the drives with the os and the server will not load.
Is there a way to rebuild the raid?
Comment: can you clarify please.  How were the drives setup before this configuration and how are the drives setup now? What did you do exactly to reconfigure?
Answer: You've not taken the array over the 2TB 'limit' have you?
Answer: If you boot off of the SmartStart CD and open the ACU, can you see the original array / logical drives?  If the original disks haven't been overwritten, but the logical drives have disappeared, you should be able to re-create them, as long as you know their original size (exact to the MB).  The data will then "re-appear".
The number of logical drives also gets displayed during POST.

Raid Reconfiguration


C# export to excel

Question: Which is the best way to export data to an existing xls sheet.
I needs to support many versions of excel.
If i was using Visual basic. I would use the CreateObject("Excel.application") code which will do what i need.
What is the equivalent in c#?
I would love for it to work on any version, and if possible then also computers without ms office at all.
Please no 3rd party components that cost money. we are poor :).
TY
Answer: Writing to Excel using C# can be accomplished using the Interop.Excel  Here is a nice tutorial with screen shots to help make this happen.
http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm
Comment: That site looks to be packed with great information. It is too bad it is damn ugly.
Answer: There are built in functions for exporting an ASP.Net grid to excel.  It gives a little warning message to the end user but it works.
It is described here:  C Sharp Corner
Comment: Hi. I use winforms. Thanks for your help anyways.
Answer: If you are wanting to Open an excel doc and then add content, one of the easiest way (w/o requiring excel to be installed) is to get a 3rd party lib ( there are probably some open source solutions) that can read and save excel files.
Answer: I know you said no third-party but the reason seems to be cost.
The library I use is GemBox.  It is free as long as the spreadsheets are not too large (150 rows and 5 worksheets max).  For my use this is no problem and it works very well.
http://www.gemboxsoftware.com/GBSpreadsheet.htm
There are also some open source options.
If you are writing to the XML format then ExcelPackage is free (GPL) and may work for you:
http://excelpackage.codeplex.com/
If you want no XML but the other formats, I hear good things about ExcelLibrary (LGPL):
http://code.google.com/p/excellibrary/
There is also a port of the JExcel library (LGPL) to C#:
http://www.chrislaforetsoftware.com/products.html
Comment: FlexCel should also be included.
Comment: Thanks siride.  I had not heard of FlexCel.  Do they have an free version of some kind (OP said he was poor)?
Answer: Excel Export
I use EP Plus Excel Export for this. Add EP Plus library from Nuget to your project. Then add this class to your project.
ExcelExport.cs
Try
And use it on MVC:
public ActionResult ExportToExcel(string cid)
{
    var customerList = new List<DtoCustomer>();
    customerList = CustomerFactory.Gets();
    ExcelExport.EpplusExportToExcelFromObjectList(customerList.ToList<object>(), "Customer List", true);

    return null;
}

Also you can define which column with which name shows on Excel Document. you have to create an attribute class for this.
ExportAttribute
using System.Attribute;
public class ExportAttribute : Attribute
{
    public string DisplayName { get; set; }
    public bool IsVisible { get; set; }
}

Class & Implementation
Then, implement this attribute to your class:
public class DtoCustomer
{
    [ExportAttribute(DisplayName = "#", IsVisible = false)]
    public int ID { get; set; }
    [ExportAttribute(DisplayName = "Customer Name", IsVisible = true)]
    public string Name{ get; set; }
    [ExportAttribute(DisplayName = "Customer Surname", IsVisible = true)]
    public string Surname { get; set; }
}

C# export to excel


Porque o script não aceita somente a letra F?

Question: Fiz uma expressão regular para aceitar valores de 0.0 até 10.0 e a letra F e justamente com ela estou tendo problemas, acaba negando na msg do próprio AddMethod().

<form id="formularioContato" method="post">

    Nota:<input type="text" id="nota" name="nota">

    <input class="submit" type="submit" value="Enviar" />
</form>

Comment: Acho que a expressão poderia ser `^(F|10\.0|\d\.\d)$`, pois "10.0" vale porém "11.0" já não vale... se o decimal for opcional, pode ser assim: `^(F|10(\.0)?|\d(\.\d)?)$`
Comment: A máscara mask("*9.9") não deveria ser um mask("A9.9")?    http://igorescobar.github.io/jQuery-Mask-Plugin/
Comment: J.Bruni essa que você me enviou funcionou porêm ele não aceita a 09.0
Answer: O problema está nas regras (rules)... substitua nota: "required nota" por nota: true
        rules:{
            nota:{
                nota: true,
                required: true
            }
        },

Answer: Sua expressão regular não deveria estar assim:
^(([F]{0,1})|((([1]{1}[0]{1})\.([0]{1}))|((([0]{1})(\d){1}))\.(\d{1})))?$

Acho que você cometeu um pequeno typo. Trocou {0,1} por {0-1}.
Comment: Não funcionou, tinha tentado uma solução semelhante também, obrigado pela atenção.
Comment: Aqui funciona: http://jsfiddle.net/fXac6/ A não ser que eu não tenha entendido a pergunta.
Comment: O engraçado que ele também aceita nesse site http://regex101.com/ será que é algo com os rules ?


Are standard VAEs enough for most representation learning tasks?

Question: I've tried VAEs a couple of times in both my applied research and on stock datasets such as MNIST, and it seems like for MNIST it works fairly well with minor hyperparameter tuning (for example architecture, beta in beta-VAEs) but for applied work it seems problems of posterior collapse/degeneracy spring up very quickly and can be pretty difficult to troubleshoot.
Is there a sense in the research community that the original standard VAE (i.e. one that relies on a prior of $N(0,1)$) has limited uses and will be eventually supplanted completely by more flexible models such as ones that use the VampPrior?
Answer: There are two aspects to your question:

Are the limits of the original VAE, with a simple prior of $ \mathcal{N}(0,1) $, recognized by the community?
Yes. A lot of research is being done towards developing more expressive probabilistic generative models. Examples are normalizing flows for generative modeling [1], Wasserstein autoencoders [2] or back constrained Gaussian process latent variable models [3].

Can VAEs be useful in practical applications?
Yes. There are tricks to make the training more robust. One useful example is annealing [4]. Consider the variational loss in VAEs, which is called the evidence lower bound (ELBO). It has two components, a regularization and a reconstruction term:
$$
    \mathcal{L}\big(\theta,\phi|x\big) \;\; = \;\; \underbrace{KL\Big(\,q_\phi(z) \,\big|\big|\, p_(z)\,\Big)}_{\textrm{Regularization term}} \;\; + \quad \underbrace{\mathbb{E}_{q_\phi(z)}\Big[ \log p_\theta(x|z) \Big]}_{\textrm{Reconstruction term}}
$$
where $q_\phi(z)$ is the variational distribution and $\phi$ are the variational parameters; $p_\theta(x|z)$ is the likelihood and $\theta$ are the likelihood parameters; and $p(z) = \mathcal{N}(z\,|\,0,1)$ is the prior. Clearly, reconstruction is a very difficult task, and the model may have trouble learning both the reconstruction and the regularization term at the same time and from scratch. Annealing solves this in the following way: it multiplies the regularization term by a weight $w_r \in [0,1]$ that is set to 0 at the beginning of the training, and slowly grows all the way up to 1 as the training progresses. This way, the VAE can focus on learning to reconstruct during the first epochs.
For example, one relatively atypical application where annealing was used to train VAEs is molecular generation [5]. This is usually considered a challenging problem, much more so than MNIST.

References
[1] Normalizing Flows for Probabilistic Modeling and Inference. Papamakarios et al. https://arxiv.org/abs/1912.02762
[2] Wasserstein Auto-Encoders. Tolstikhin et al. https://arxiv.org/abs/1711.01558
[3] Local distance preservation in the GP-LVM through back constraints. Lawrence et al. https://doi.org/10.1145/1143844.1143909
[4] Generating Sentences from a Continuous Space. Bowman et al. https://arxiv.org/abs/1511.06349
[5] Automatic Chemical Design Using a Data-Driven Continuous Representation of Molecules. Gómez-Bombarelli et al. https://doi.org/10.1021/acscentsci.7b00572


In how many ways can you split 100 identical coins to 5 people, so that no one gets more than 50 coins?

Question: In how many ways can you split 100 identical coins to 5 people, so that no one gets more than 50 coins? I know the general formula : $\binom{n+k-1}{n-1}$
Can someone give me some directions?I was thinking maybe put aside 50 coins first but then I don't know how to continue
Answer: Count the total number of ways to distribute the coins, with no restriction. You know how to do that.
Now subtract the number of bad distributions, in which someone gets more than $50$ coins. The lucky person can be chosen in $5$ ways.
Say Alicia is the lucky person. We count the number of ways to distribute the coins, with Alicia getting $51$ or more. Give her $51$ coins. That leaves $49$ coins to be distributed among the five people, including Alicia. This can be done in $\binom{49+5-1}{5-1}$ ways.
So the total number of bad distributions is $5\binom{53}{4}$.
Comment: You are welcome.
Comment: So the final answer is all the ways minus the bad ways right (what you wrote at the end) right?
Comment: Yes, that's right. I like to concentrate on the logical structure of the argument and leave something for you to do.
Comment: But if now I have all the bad distributions of someone getting 51 coins... What about all the bad distributions of someone getting 52? 53? 54...
Comment: That *has been taken care of* in the solution, We gave Alicia  $51$ coins. Then (please see answer) we distributed $49$ coins between **five** people, **including Alicia**.  Thus Alicia might end up with $77$ coins, all cases are counted.  The complete answer to the problem is $\binom{104}{4}-5\cdot\binom{53}{4}$. (Well, then we could calculate, not interesting.)


void*v[]; v[i] = v[j]; why this is right?

Question: A void* is a pointer that points to nothing, i.e. it's only an address! How could one dereference it? But in the book The C programming language (second edition) page 121, the swap function seems to do it.
Comment: What? Please rephrase your question, it makes absolutely no sense!
Comment: Interesting question, but you should get someone to help you write it in clear English.
Comment: @Joe My english is poor,I don't know how
Comment: @ytyisme: I've edited your question, please have a look whether I got it right.
Comment: @DarkDust Thank you! It's right. How to open my question again?
Comment: You can't :-) Other people with higher reputation can vote to reopen it (which I just did).
Comment: @DarkDust Thank you! I want to know that we don't know how far between two void pointer how do know where it point to?
Answer: void *v[] is an array of pointers. So v[i] = v[j]; assigns an element at index j to the position i which does not involve dereferencing the pointer but merely copying the pointer(address).
Comment: Can you edit my questions become more clear?
Comment: `v[0]` is of type `void *`, not type `void`.
Comment: @PerJohansson oh,maybe,got it
Answer: You need to typecast the pointer into desired type. For instance, void* x; (int*)x - suddenly it's a pointer to int.


Does Python allow for multiple input parameters to a class method?

Question: I can not seem to find an answer for this question on the interwebs. In Python, am I able to do something like this:
class MyClass(object):
    """It's my class, yo!"""
    def __init__(self, string_of_interest_1):
        self.string1 = string_of_interest_1
        self.string2 = None
        self.int1 = None
    def __init__(self, string_of_interest_1, string_of_interest2):
        self.string1 = string_of_interest_1
        self.string2 = string_of_interest_2
        self.int1 = None
    def __init__(self, int_of_interest_1):
        self.string1 = None
        self.string2 = None
        self.int1 = int_of_interest_1

I call this "method-overloading", but it seems the standard overloading is when I have some variables that I assign a default value to within the call itself.  (E.g., def __init__(self, string_of_interest_1, string_of_interest_2 = None))  While this tiny example does not demonstrate it, I would like the potential to have truly different methods depending upon how many, and what type, of parameters are passed to it.
Thanks!
Comment: No, this doesn't work, you just replace the previous definition. However, you can have variable number of arguments and optional argument/keywords to do the same thing.
Comment: Plus, in python you never presume the type of an input variable - it simply needs to be able to do the things required of it, see "duck typing".
Comment: Python will make no distinction between `string_of_interest_1` and `int_of_interest_1`. It will not do any type checking at that time.
Comment: You might be interested in [multimethods](http://www.artima.com/weblogs/viewpost.jsp?thread=101605) and [PEAK-Rules](https://pypi.python.org/pypi/PEAK-Rules). `multimethods` will allow you to dispatch based on the type of arguments. `PEAK-Rules` will allow you to dispatch on the type and value of arguments. I'm not sure what facilities it may or may not have for dispatching based on the number of arguments.
Answer: In python there is no overloading of functions or methods, but there is a change - *args and **kwargs. Example:
>>def test(*args, **kwargs):
>>    print args # list of positional parametrs
>>    print kwargs # dict of named parametrs

>>test(1, 2, test_param='t')
[1, 2]
{test_param: 't'}

Answer: All variable in Python is object even int is also a object.
Method overriding used in C, JAVA etc..
Python has magic variable * and **. * is used for position argument, and ** used as keyword argument
try this
def test_method(*args, **kwargs):
    print args
    print kwargs

Call this function with different different argument and you will get idea about these magic methods.
Answer: You can take all the arguments that you want even when your function doesn't know the number. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args. What *args allows you to do is take in more arguments than the normal of formal arguments that you previously defined. Check this thread to see an example of how you can do it

*args and **kwargs?


Probability of winning a dice roll when the two players have difference die sizes

Question: Say for a moment two people each have a single die. One has $m$ sides while the other has $n$ sides. Assuming the dice are each fair (as in, each die has an equal chance to roll any side... obviously if $m > n$ it doesn't seem fair!) how can I calculate the chance of either one winning?
In my exact situation, my "dice" have many thousands of sides, so it would be prohibitive of me to make a "truth table" so to speak. I doubt that affects the formulas but figured I should add it for relevance.
I was thinking that assuming $m > n$, then when $m$ rolls a 1, then $n$ wins $n-1$ number of times (i.e. when they don't roll a 1). Same situtation where $m$ rolls a 2, $n$ has $n-2$ rolls that win. So we have this $n - 1 + n - 2 ...$ which seems to be $(n *( n+1))/2$ for large n. Since there are $m*n$ number of possible combos, the chance of $n$ winning is $((n*n+1)/2)/(m*n)$ and cancelling $n$ yields $(n+1)/(2*m)$ but I could be completely off base with it and could use some guidance.
This result doesn't sit well with me because for very large n (say 5000 and 5001) they should be very, very close to eachother where this gives a massive bonus to the 5001. So clearly I messed something up!
For purposes of this, you may ignore ties. It is sufficient to select one player as the "interesting" player and simply determine if that player "wins" or not. For such large n, ties are effectively irrelevant anyway.
Answer: The number of outcomes where player $M$ beats (or ties) player $N$ is given by the sum
$$\sum_{i=1}^{n}\sum_{j=i}^m1 = \sum_{i=1}^{n}(m-i) = mn - \sum_{i=1}^{n}i = mn-\frac{n(n+1)}{2}.$$
Dividing through by the total number of outcomes $mn$ yields
$$P(\text{M does not lose}) = 1 - \frac{n+1}{2m},$$
which for large $n, m$ roughly equal is close to $\frac{1}{2}$ as expected.
Comment: Oh duh, of course the $2m$ in that denominator means it's about 1/2... I was thinking it should be 1 but that makes so much sense, logically.
Comment: In general, if $n$ and $m$ are large then we can ignore the 1 in the numerator to get $P(loss) = \frac{1}{2}\cdot\frac{n}{m}$, which makes sense since intuitivelly the win/loss ratio should depend solely on the ratio of $n$ to $m$.
Comment: Yet another way of looking at it: if the $m$-sided die rolls $\gt n$ then it always wins; the probability of this is $(m-n)/m$. If it rolls $\leq n$ (which happens with probability $n/m$) then $m$ wins with probability $(n^2-n)/2n^2$ = $(n-1)/2n$.  So the total probability that the $m$-sided die wins is $\frac{m-n}m+\left(\frac nm\right)\left(\frac{n-1}{2n}\right)$ $=\frac{2(m-n)}{2m}+\frac{n-1}{2m}$ $=\frac{2m-n-1}{2m}$, the same expression that Andrew derives.
Answer: Assuming "winning" means having a greater number than the other player.
Die $n$ has sides $1,2,3,...,n$ and die m has sides $1,2,3,...,m$.
We can treat this as a probability tree, starting with $n$ rolling.
Each side $i$ of $n$ has a $1/n$ probability of being rolled. Given a side $i$, the probability of $m$ winning is $(m-i)/m$.
Thus, the initial formula is:
$$\left(\frac{1}{n}\right) \times \sum_{i=1}^n\frac{m-i}{m}$$
The sum can be written as:
$$\frac{nm - \sum_{i=1}^ni}{m}$$
Since $\sum_{i=1}^ni = \frac{n(n+1)}{2}$, the final formula then becomes:
$$\frac{2m-n-1}{2m}$$
Comment: This is excellent - is there a cute trick that would allow me to calculate that sum? Like, in Excel? =)
Comment: You can undoubtedly do it using python, I'm not super familiar with excel but I imagine there should be some similar trick.


Proving independence of discrete variables and the product of them

Question: Given that P(A) and P (B) are independent and
\begin{equation}
$P(A=1)=\frac{1}{2}$
$P(A=-1)=\frac{1}{2}$
$P(B=1)=\frac{1}{2}$
$P(B=-1)=\frac{1}{2}$
There is a random variable $C = A \cdot B$,
C is independent with A, with B but not with A and B.
I have a couple of questions about this:
1.Will C be
$P(C=1)=\frac{1}{2}$
$P(C=-1)=\frac{1}{2}$
because $P(A=1)P(B=1)+P(A=-1)P(B=-1)=\frac{1}{2}$ and $P(A=-1)P(B=1)+P(A=-1)P(B=1)=\frac{1}{2}$? Is it allowed just to multiply $P(A)$ and $P(B)$ to get $P(C)$?
2.How can I prove that C and A are independent? Do I have to prove that $P(A, C)=P(A)P(C)$? Can I find $P(A, C)$? Is $P(A,C)$ the same as $A \cdot C$?
How can I also prove that C and A and B are NOT independent? Do I show that $P(C,(A,B)) \neq P(C)P(A,B)$?
Will P(A,B) be
\begin{equation}
P(A, B)=
    \begin{cases}
          \frac{1}{4}, \text{if A = 1, B = 1},\\
          \frac{1}{4}, \text{if A = 1 ,B = -1},\\
          \frac{1}{4}, \text{if A = -1,B = 1},\\
          \frac{1}{4}, \text{if A = -1,B = -1}\\
    \end{cases}
\end{equation}
Comment: $A$, $B$ and $C$ seem to be random variables taking values rather than events, so you should not write $P(A)$ etc. You seem to have $P(A=1)=\frac12$ and $P(A=-1)=\frac12$ and similarly with $B$, and in fact also with $C=AB$.  For example $P(C=1)=P(AB=1)$ $=P(A=1,B=1)+P(A=-1,B=-1)$ $=P(A=1)P(B=1)+P(A=-1)P(B=-1)$ using the independence.
Comment: $A,B,C$ are _pairwise_ independent random variables but not _mutually_ independent random variables.
Comment: $P(A=1,B=1,C=1)=\frac14$ while $P(A=1)P(B=1)P(C=1)=\frac18$ so they are not mutually independent
Comment: Does $P(A=1,B=1,C=1)=\frac{1}{4}$ because when A=1 and B=1, C must also equals to 1, therefore  $P(A=1,B=1,C=1)=P(A=1,B=1)$?
Answer: When working with binary variables (or other variables with small numbers of possible values), it helps to make a table.
A complete table will display all possible combinations of the values along with the probabilities of those outcomes.  (It is a good idea to enumerate the combinations systematically, because that reduces errors and reveals patterns.  Below, I have listed the outcomes in lexicographic order.)  At the outset, we often don't know all the probabilities.  In this case, I will just call them $p,q,r,$ etc.
Here is the most general table describing your situation.  It was constructed by enumerating all possible combinations of $(\mathscr{A},\mathscr{B})$ and computing their products in the $\mathscr{C}$ column.
$$\begin{array}{l|rrr}
\text{Probability} & \mathscr{A} & \mathscr{B} & \mathscr{A}\mathscr{B}=\mathscr{C}\\
\hline
p & -1 & -1 & 1\\
q & -1 & 1 & -1\\
r & 1 & -1 & -1\\
s & 1 & 1 & 1
\end{array}$$
It will always be the case that the probabilities sum to $1.$  Additionally, your information includes four more equations that can be read directly off the table.  For instance, the event $\mathscr{A}=-1$ comprises the first two rows of the table, whence its chance must be the sum of the probabilities in those rows, $p+q.$  Proceeding in this fashion you may instantly write down all equations by inspecting the table:
$$\begin{aligned}
1 &= p + q + r + s\\
1/2 &= \Pr(\mathscr{A}=-1) = p + q\\
1/2 &= \Pr(\mathscr{A}=1) = r + s\\
1/2 &= \Pr(\mathscr{B}=-1) = p + r\\
1/2 &= \Pr(\mathscr{B}=1) = q + s
\end{aligned}$$
Straightforward linear algebra proves the most general solution to this system of linear equations is determined by one parameter.  Let's use $p.$  Here is that general solution.
$$\begin{array}{l|rrr}
\text{Probability} & \mathscr{A} & \mathscr{B} & \mathscr{C}\\
\hline
p & -1 & -1 & 1\\
1/2-p & -1 & 1 & -1\\
1/2-p & 1 & -1 & -1\\
p & 1 & 1 & 1
\end{array}$$
Finally, because probabilities cannot be negative, you must restrict these solutions to $0 \le p \le 1/2.$  As an extreme example, when $p=1/2$ the distribution is
$$\Pr(-1,-1) = \Pr(1,1) = 1/2.$$
You may check this is consistent with all the information in the question.  Extreme examples (on the boundary of the constraints) often are simple and provide useful examples to help you think through the concepts.  I encourage you to do that with this one.
So: to reason about independence, apply the definition of independence to this general solution.  I leave the easy calculations to you.
Comment: Is it correct to say that $C$ is independent of $A$ by looking at the first and last row of the system of linear equations and say that the $P(C=1) = p$ for both when $A$ is 1 and -1., and similarly for when $P(C=-1) = \frac{1}{2}-p$ for the second and third row. Therefore $A$ and $C$ are independent?
Comment: Yes.  The table shows that $\Pr(\mathscr C = 1\mid \mathscr A = 1)=p = \Pr(\mathscr C = 1 \mid \mathscr A = -1).$ That suffices to prove independence in this situation.


How to get full explanation of Elasticsearch query Java?

Question: I'm currecntly trying to test out some new score functions on my Elasticsearch query but I'm not yielding the results I am expecting.
I found this on their site about explaining queries here
I can run as a curl command but does anyone know how to translate this to use the Java api?
Comment: https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-search.html
client.prepareSearch() and QueryBuilders are pretty much the bread and butter of the Java API.  The nesting of method calls is also pretty much the same as the nesting in a JSON query.
Answer: If you're using the ES5 Java API, you can get the explanation like this:
QueryBuilder query = matchAllQuery(); // your query

ExplainRequest request = new ExplainRequest("index", "type", "id").query(query);
ExplainResponse explainResponse = client.explain(request).actionGet();
Explanation explanation = explainResponse.getExplanation();

Where client is your org.elasticsearch.client.Client instance.


The limit of sequence tends to $0$

Question: I am trying to show that if $0<x<1$,  $$ \lim_{n\to \infty}  {n^2 x^n (1-x)}=0 $$
I can't think of a clever way to show it.
Comment: Abandoning cleverness, l'Hôpital $\lim_{n\rightarrow\infty} (n^2/ (1/x)^n)$.
Answer: Because of
$$\left|\frac{(n+1)^2 x^{n+1} (1-x)}{n^2 x^n (1-x)}\right| = \frac{(n+1)^2}{n^2}x\stackrel{n\to\infty}{\longrightarrow} x \lt 1$$
The series
$$\sum_{n=0}^{\infty} {n^2 x^n (1-x)}$$
converges absolutely
Hence ${n^2 x^n (1-x)}$ has to tend to zero.
Answer: My way of solving it would be to introduce
$$u_n = n^2 x^n (1-x)$$
The ratio $ \frac{u_{n+1}}{u_{n}} $ is given by
$$ \frac{u_{n+1}}{u_{n}} = x \, \left[ \frac{n+1}{n} \right]^{2} $$
We have $\lim\limits_{n \to + \infty} \frac{n+1}{n} = 1$.
As $|x| < 1$, for $n$ large enough we will have $\left| \frac{u_{n+1}}{u_{n}} \right| < 1$.
It means that for $n$ large enough, the terms of the sequence can be bounded by a geometric progression, with a ratio strictly inferior to $1$.
Hence, we have $\lim\limits_{n\to+\infty}u_{n}=0$.
Answer: Write $n^2x^n=\exp(2\ln n+n\ln x)$. The argument of the exponential is equivalent to $n\ln x$ when $n\to\infty$. As $0<x<1$, $\ln x<0$ so $n\ln x\to-\infty$ and then $\exp(2\ln n+n\ln x)\to 0$.

The limit of sequence tends to $0$


Substitution in a complex lambda calculus formula

Question: I have the following lambda expression:
$$( (y \lambda x \rightarrow \lambda y \rightarrow f y) (\lambda f \rightarrow f y z) )[y := f x]$$
So, my questions are,

I see $y$ before a lambda abstraction, what does that mean ? Is that y free ?
Is it correct to put parenthesis like this in the expression ?

$$(y (\lambda x \rightarrow \lambda y \rightarrow f y)) (\lambda f \rightarrow f y z) )[y := f x]$$
Then, I would have the term $f x$ applied to the lambda expression:
$$(\lambda x \rightarrow \lambda y \rightarrow f y)$$
However, is that $f$ free ?
I learned, for example:

a variable is bound if it is within the scope of a lambda term; otherwise, it is free.
I can only substitute free occurrences of a variable.
I should avoid variable capturing by using alpha conversion.

I thought I understood the basics of lambda calculus substitution, but I can't grasp this example. I clearly have gaps in my understanding.
Answer:
I have the following lambda expression:
$((yλx→λy→fy)(λf→fyz))[y:=fx]$

Uh, this is a weird syntax, I assume it should be read as $((yλx.λy.fy)(λf.fyz))[y:=fx]$.

I see $y$ before a lambda abstraction, what does that mean ? Is that $y$ free ?

A variable (or more precisely, an occurrence of a variable) isn't free in general, but only free (or bound) in a given term. Here, the first occurrence of $y$ is indeed free in the term $(yλx→λy→fy)(λf→fyz)$. But in the whole term you give it is substituted, so it doesn't even exist as a "true" variable occurrence — and thus, is neither free nor bound. (The other occurrence of $y$ is bound by $\lambda y$ in any case.)
This is where the subtility of this example arises, because you substitute $fx$ to $y$ in a λ-expression where

$y$ appears both free and bound, which may be overcome depending on the way you define substitution (see this answer);
$f$ appears bound, which forbids substitution without performing α-conversion first.

The minimal conversion you must do is the following (I put the fresh variables in capital letters):
$((yλx→λy→fy)(λf→fyz))[y:=fx] \\
=_α ((yλx→λy→fy)(λF→Fyz))[y:=fx] \\
= ((fx)λx→λy→fy)(λF→F(fx)z)$
but it would be cleaner (and might be required by your definition of the substitution) to convert also the bound $y$:
$((yλx→λy→fy)(λf→fyz))[y:=fx] \\
=_α ((yλx→λY→fY)(λF→Fyz))[y:=fx] \\
= ((fx)λx→λY→fY)(λF→F(fx)z) $

Is it correct to put parenthesis like this in the expression ?

I would say yes. But this depends on the way you defined the syntax of the λ-calculus, there are several valid choices for the scope of the constructors and the placing of the parentheses. (See the curious, yet very practical Krivine notation.)

Then, I would have the term $fx$ applied to the lambda expression: $(λx→λy→fy)$. However, is that $f$ free ?

Yes, these two $f$ are free.
Comment: Yes, exactly. :-)
Comment: Using the syntax I'm used to I would just substitute in the right subterm, but again, *you* decide what is the scope of the substitution operation. (And `[x := z+z]` should disappear in the second expression.)
Comment: Thank you very much. What's your definition of fresh variable ?
Comment: It's a new variable that is not used anywhere else in the term. When you need, for some reason, to perform α-conversion on some $λx.x$, you take a new "fresh" variable $y$ (this is always possible because the set of variables is infinite) and you rewrite $λx.x$ to $λy.y$.
Comment: Thank you ! And do you know what happens in this case $(λy → (λz → z)) x$ ? Is it reduced to `(λz → z)`. I ask because lambda $y$ doesn't appear in the body.
Comment: Thank you very much.
Comment: Sorry to bother you. Do you know whether I have to substitute both lambda expressions if I have: `(λx → x) (λy → y * x) [x:=z+z]` ? So, would I get: `(λx → z + z) (λy → y * (z + z))`. And why is that ? I think I should only substitute in the rightmost lambda expressions. I can't seem to find precedence rules for the substitution operation.
Comment: What you suggest is incorrect, the $x$ in $λx.x$ is bound and should not be substituted. About precedence rules: syntax is a matter of choice and taste, just fix a rule you like and stick to it. ;-)
Comment: Sorry, my mistake. I meant going from: `(λw → x + w) (λy → y * x) [x:=z+z]` to `(λw → (z+z) + w) (λy → y * (z+z)) [x:=z+z]`. Is sensible to replace both abstractions, or just the rightmost lambda abstraction ?
Comment: Thank you so much. Yes, I should remove that `[x := z+z]` in the second expression.


How can I use "A simple connected graph has an Euler Circuit iff .." to show/prove something?

Question: We are given the following theorem in our textbook (Discrete Mathematics, Rosen)

A connected multigraph with at least two vertices has an Euler circuit if and only if each of its vertices has an even degree.

My main confusion lies in understanding the iff part. I understand that it means "equivalence" and "if and only if" however, I am having trouble understanding how to use it to show/prove something.
I have seen that when we have an iff statement, we have to show something both ways i.e. $\implies$ and $\impliedby$; in this case, does that mean have to show:

We have an Euler circuit $\implies$ each vertex has even degree
If all the vertices have an even degree then ($\impliedby$) then Euler circuit?

I have a feeling that this is incorrect. Can someone please clarify this?
Thanks for your time
Comment: What you have is correct. If the graph has an Euler circuit, then each vertex has even degree, and if each vertex has even degree, then the graph has an Euler circuit.
Comment: Fantastic! Thanks for your reply. If you could post your comment as an answer, I would be more than happy to accept it! :)
Comment: Done! I also added just a little information.
Answer: What you have is correct. On the one hand if the graph has an Euler circuit, then each vertex has even degree; this is the easier direction. On the other hand, if the graph is connected and each vertex has even degree, then the graph has an Euler circuit; this is a bit harder. (If it's not connected, each component has an Euler circuit.)


Strong attribute on NSArray and retain cycle

Question: I'm making an iOS app in which i have an Event class and a Participant class.
The Event class as an NSArray *participants property with a strong attribute.
The Participant class needs to have a property refering to the event the participant is in.
I'm asking myself if the fact that the participants array as a strong attribute implies that each participants in this NSArray also as a strong attribute ? Therefore, does the event property of the Participant class needs to have a weak attribute to avoid a retain cycle ?
Thanks for your help
Answer: You are correct that the Participant class should have a weak reference to its Event if your Event class has a strong reference to its Participant's. However, you have mistaken the strong attribute of your NSArray to mean that the array holds a strong reference to each Participant. An NSArray will ALWAYS maintain a strong reference to the items its holds. It is the Event class's reference to its array that is strong.
Comment: Be aware that changing the reference to the participants array to weak will NOT prevent the retain cycle.
Comment: Yes I see, i wasn't aware that NSArray always as a strong reference to it's objects. Thanks !
Answer: Yes, the inverse relationship (participant -> event) should be weak, and since a participant cannot exist without the event, this would cause no problem. Meaning that if you remove the event, the participants will be deallocated automatically as well.
Answer: If you declare an NSArray strong, you are retaining the reference at that array.
Is the NSArray that retains objects in itself.
And YES, to avoid retain cycle if the object A retains B, B should just have a weak reference to A. But be careful to the management of the object in that array.
Finally i can't figure out your structure, but maybe the participants array is of objects Participant?
Consider the possibility to use Delegation pattern or KVO.


Can you compile a LINQ to Entities query that is composed with if statements?

Question: I have a fairly complex LINQ to Entities query I'd like to try compiling because it's a bit slower than I'd like.
I build it in a series of steps though. Here's a simple example:
public static List<Employee> GetEmployees(EntityContext ctx, bool showTerminated)
{
    var q = ctx.Employees;

    if(showTerminated==false)
    {
        q = q.Where(e => e.TerminationDt == null);
    }

    //...more conditional filters / Group By / Select applied...

    return q.ToList();
}

Is there any way to take advantage of compiled queries when you have this type of conditional query composition?
Answer: No. However, you could rewrite the query into a compilable version:
var q = ctx.Employees.Where(e => showTerminated || !e.TerminationDt.HasValue);
// rest of method

Comment: var q = ctx.Employees.Where(e => !showTerminated || !e.TerminationDt.HasValue);


Is that possible to get file content continuously from remote server

Question: I know locally it is possible to get file content line by line.
just like
Scanner s = new Scanner(new File("D:\\Users\\qding\\Desktop\\spy.log"));
    while (s.hasNextLine()) {
        String line = s.nextLine();
        System.out.println("[Method Server] " + line);
}

Is it possible to get file content from remote (Windows/Linux)?
Also, on the remote, the file was a log file, and it is updated always.  So the second question is if is possible to file content continuously (with multiple thread?)?
Answer: A1. Yes it is possible to get file content from remote system, provided it is accessible over any protocol.
A2. On unix systems, to read content of a file that is changing continuously, we have tail -f ... command. Please refer to File Monitoring. And to read such files over network, you definitely require help of Threads to wait and read the updates. Apache commons has custom tail implementations that may help you.
You can refer to a similar posting on SO, for detailed suggestions and discussions.
Update:
A2: For windows, there is a third party GUI tool Tail for Win32, but never I worked on it.
You can also refer to some more suggestions at Windows ... equivalent of "tail -f"?.
Comment: Ravinder, thanks a lot, it is useful, especially the Apache implementation of tail. Emm..., is there any reference about getting file content continously from remote windows?
Comment: what I mean is on Linux we have _tail -f_, but on windows, have we to implement this function ourselves?
Comment: @ShrekDing I have updated my answer with other references to windows equivalent versions of `tail -f`.
Answer: Well let me try to answer this,

I am assuming that you have used Socket, to communicate with the Server.
Use socket.shutdownOutput() ("socket" in socket.shutdownOutput() identifies the Server address and port nos) on the client side, as you dont need to write something but need to keep reading from the Server.
If you are handling the Server part also, make sure every request to the Server runs on its own thread.
Now on the client side use this below link to read from the "file" on the server
http://www.java-samples.com/showtutorial.php?tutorialid=215


Remove differences between two video frames

Question: Im trying to remove the differences between two frames and keep the non-chaning graphics. Would probably repeat the same process with more frames to get more accurate results. My idea is to simplify the frames removing things that won't need to simplify the rest of the process that will do after.
The different frames are coming from the same video so no need to deal with different sizes, orientation, etc. If the same graphic its in another frame but with a different orientation or scale, I would like to also remove it. For example:
Image 1

Image 2

Result (more or less, I suppose that will be uglier but containing a similar information)

One of the problems of this idea is that the source video, even if they are computer generated graphics, is compressed so its not that easy to identify if a change on the tonality of a pixel its actually a change or not.
Im ideally not looking at a pixel level and given the differences in saturation applied by the compression probably is not possible. Im looking for unchaged "objects" in the image. I want to extract the information layer shown on top of whats happening behind it.
During the last couple of days I have tried to achieve it in a Python script by using OpenCV with all kinds of combinations of absdiffs, subtracts, thresholds, equalizeHists, canny but so far haven't found the right implementation and would appreciate any guidance. How would you achieve it?
Comment: So, you are wanting to keep parts of the two images that are the same.   The tricky part is how you appear to be defining "same":   it applies to objects rather than pixels.   You'll need to nail down this definition further...
Comment: I have modified it a bit, hope that its clearer. Let me know if thats not the case.
Comment: I think this is a hard problem in Computer Vision, in many respects.   What is the ultimate goal, e.g., learning the rules of the game  by "watching" play?   You *might* be able to come up with a more application-specific approach.
Comment: please provide a set of pictures, and the code, that cause you trouble. you need to provide a [mre].
Answer:
Im ideally not looking at a pixel level and given the differences in saturation applied by the compression probably is not possible. Im looking for unchaged "objects" in the image. I want to extract the information layer shown on top of whats happening behind it.

This will be extremely hard. You would need to employ proper CV and if you're not an expert in that field, you'll have really hard time.
How about this, forgetting about tooling and libs, you have two images, ie. two equally sized sequences of RGB pixels. Image A and Image B, and the output image R. Allocate output image R of the same size as A or B.
Run a single loop for every pixel, read pixel a and from A and pixel b from B. You get a 3-element (RGB) vector. Find distance between the two vectors, eg. magnitude of a vector (b-a), if this is less than some tolerance, write either a or b to the same offset into result image R. If not, write some default (background) color to R.
You can most likely do this with some HW accelerated way using OpenCV or some other library, but that's up to you to find a tool that does what you want.


Universal click step in cucumber rails (with and without selenium)

Question: I want to make a universal click step which I could call in scenarios with and without @javascript flag.
So far it is :
When(/^I click "([^"]*)"$/) do |clickable|
  click_on(clickable)
end

It is working fine, when It is not using WebDriver. But when I use WebDriver, it puts focus on the link or button, but does not click it.
If I simulate pressing "Enter" then it works fine with WebDriver, but raises an exception in Pure Capybara tests.
Is there a way to have one step which works with both?
UPDATE:
By putting sleep 1 before click, I managed to get clicking on links working( highly doubt that it is efficient). I have no javascript or asynchronous loading in the page at this point. But clicking on button is still not working.
Comment: try `find_link(link_name).trigger(:click)`
Comment: @OlegSobchuk I want it to work with both- links and buttons
Comment: find(:link_or_button, locator).trigger(:click)
Comment: trigger function show to have been deprecated. And find does not work with values. only css selectors (as far as I know)
Answer: You can probably try finding the element to be clicked using the css selector and then click on the element.
def click_element(selector)
  begin
    el = find(:css, selector)
  rescue Capybara::ElementNotFound => e
    puts "Element with Selector - #{selector} not found on the page"
    raise e
  end
  call_click el
end

def call_click (selector)
  if (IS_HEADLESS)
    selector.trigger('click')
  else
    selector.click
  end
end

Answer: The code you show should work correctly both with and without selenium.  If it's not it generally means you have some JS code that is blocking the clicks, or with recent versions of selenium-webdriver that your elements may be hidden behind other elements (fixed header/footer bar for instance) - although that would normally show an error.
Assuming it's not failing on every click you attempt, then you need to look at the ones that are failing and see what common things are being done (maybe post some of the html) - Since you say a 1 second sleep fixes it, I would guess you have some fields being transformed by JS libraries and the clicks are being ignored until the libraries have finished transforming the elements.
Comment: I took out all javascript from the page and then the link worked. Though when I tried submitting form with the same step it did nothing(even with no javascript). It is weird though, that javascript was preventing from clicking on that link given that nothing in that page is referenced or done in javascript.
Comment: It sounds like you either have delegated listeners that are a little overzealous in which clicks they're grabbing, or possibly some errors in your JS that are preventing JS you think should be working from actually happening (remote form submission, etc) -  Adding some example html to your question would help


compact ms access database in vb.net without copy of the database

Question: I have searched the net on this topic and found, that if an ms access database should be compacted, then I should give the database itself and a new path.
Why is this necessary? If I check in ms access, that it should compact the database after closing, it don't creates a compacted database and deletes the old one, but it compacts only the one database. Or it is so fast, that I can't see it?
Answer: Access creates the compacted db as a new file, deletes the old (uncompacted) db file, and renames the new file to the old name.
It always works that way regardless of whether you compact from external code, from within an active Access session, or with compact on close at the end of an Access session.
With a small enough db file, the entire process can complete so quickly that you might not notice the transitional new db file.  But with a large enough db file --- 1 GB should do it --- you can watch in Windows Explorer as the new db file is created and grows to it final (compacted) size.
Incidentally, be cautious about compact on close.  Many experienced Access developers recommend against that option.  The reason is that if anything goes wrong during compact, the new db can be corrupted and your original uncompacted version will be gone ... so no hope of recovery.


rearrange xml nodes including sub-nodes by xslt

Question: I have a xml document, now i want to translate it to another xml document with same content but different element orders.
The original xml document like:
<?xml version = "1.0" encoding = "UTF-8"?>
<order xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" >
 <ship>
    <zipcode>78712</zipcode>
    <street>1234 Main Street</street>
    <country>CN</country>
    <city>Beijing</city>
 </ship>
 <items>
    <quantity>1</quantity>
    <itemno>1234</itemno>
 </items>
 <items>
    <quantity>3</quantity>
    <itemno>1235</itemno>
 </items>
 <price>456</price>
 <customer>Tom Hill</customer>
</order>

The expected output xml document like:
<?xml version = "1.0" encoding = "UTF-8"?>
<order xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" >
 <customer>Tom Hill</customer>
 <ship>
    <street>1234 Main Street</street>
    <city>Beijing</city>
    <zipcode>78712</zipcode>
    <country>CN</country>
 </ship>
 <items>
    <itemno>1234</itemno>
    <quantity>1</quantity>
 </items>
 <items>
    <itemno>1235</itemno>
    <quantity>3</quantity>
 </items>
 <price>456</price>
</order>

I used following xslt document to translate it.
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/order">
 <xsl:copy>
  <xsl:copy-of select="customer" />
  <xsl:copy-of select="ship" >
  <xsl:call-template name="TShip" />
  </xsl:copy-of>
  <xsl:copy-of select="items">
  <xsl:call-template name="TItems" />
  </xsl:copy-of>
 <xsl:copy-of select="price" />
 </xsl:copy>
</xsl:template>

<xsl:template name="TShip">
 <xsl:copy>
  <xsl:copy-of select="street" />
  <xsl:copy-of select="city" />
  <xsl:copy-of select="zipcode" />
  <xsl:copy-of select="country" />
 </xsl:copy>
</xsl:template>

<xsl:template name="TItems">
 <xsl:for-each select="items">
  <xsl:copy>
   <xsl:copy-of select="itemno" />
   <xsl:copy-of select="quantity" />
  </xsl:copy>
 </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

However, the translated result is not my expected.
Translated result xml:
<?xml version = "1.0" encoding = "UTF-8"?>
<order xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" >
 <customer>Tom Hill</customer>
 <ship>
    <zipcode>78712</zipcode>
    <street>1234 Main Street</street>
    <country>CN</country>
    <city>Beijing</city>
 </ship>
 <items>
    <quantity>1</quantity>
    <itemno>1234</itemno>
 </items>
 <items>
    <quantity>3</quantity>
    <itemno>1235</itemno>
 </items>
 <price>456</price>
</order>

It just made the first level nodes in expected order. All sub-nodes are kept in original order. How can i make the order of all nodes as my expected ?
Answer: xsl:copy-of copies all child nodes as well and child nodes of it are not evaluated.
So your TShip and TItems templates are never even being evaluated. <xsl:copy-of select="ship"> copies all of <ship>...</ship>.
This modification to your template will demonstrate that your TShip and TItems templates are not being called.
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/order">
 <xsl:copy>
  <xsl:copy-of select="customer" />
    <xsl:copy-of select="ship">
  <xsl:call-template name="TShip" />
</xsl:copy-of>
  <xsl:copy-of select="items">
  <xsl:call-template name="TItems" />
  </xsl:copy-of>
 <xsl:copy-of select="price" />
 </xsl:copy>
</xsl:template>

<xsl:template name="TShip">
 <xsl:copy>
  <test>TShip called</test>
  <xsl:copy-of select="street" />
  <xsl:copy-of select="city" />
  <xsl:copy-of select="zipcode" />
  <xsl:copy-of select="country" />
 </xsl:copy>
</xsl:template>

<xsl:template name="TItems">
 <xsl:for-each select="items">
  <xsl:copy>
  <test>TItems called</test>
   <xsl:copy-of select="itemno" />
   <xsl:copy-of select="quantity" />
  </xsl:copy>
 </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Notice that the output does not contain the <test> elements I added.
What you need to do instead is recursive implicit copying. Usually xsl:copy, xsl:copy-of and xsl:for-each are a sign of bad xsl template design--there are very few problems which xsl:template and xsl:apply-template with an identity transform do not handle better.
This is how I would do it:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output encoding="UTF-8" indent="yes" method="xml" />

    <xsl:template match="order">
        <xsl:copy>

            <xsl:apply-templates select="@*" />

            <xsl:apply-templates select="customer" />
            <xsl:apply-templates select="ship" />
            <xsl:apply-templates select="items" />
            <xsl:apply-templates select="price" />

            <xsl:apply-templates select="*[not(self::customer or self::ship or self::items or self::price)]"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="ship">
        <xsl:copy>
            <xsl:apply-templates select="@*" />
            <xsl:apply-templates select="street" />
            <xsl:apply-templates select="city" />
            <xsl:apply-templates select="zipcode" />
            <xsl:apply-templates select="country" />
            <xsl:apply-templates select="*[not(self::street or self::city or self::zipcode or self::country)]"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="items">
        <xsl:copy>
            <xsl:apply-templates select="@*" />
            <xsl:apply-templates select="itemno" />
            <xsl:apply-templates select="quantity" />
            <xsl:apply-templates select="*[not(self::itemno or self::quantity)]"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Notice how many fewer assumptions this template design makes about the structure of your source XML. It is also much easier to change: for example, if you want to silence or rename a particular element that may itself have children, you just add a new xsl:template that matches that element, do whatever you need to do, and xsl:apply-templates on the children.
You should learn more about this XSLT pattern because it is very versatile and makes template authoring much less tedious and your templates much less brittle.
Comment: Your answer saved me! Thank you.
Answer:
How can i make the order of all nodes as my expected ?

The short answer: By using <xsl:apply-templates/> and <xsl:template> instead of <xsl:copy-of>

Here is a complete transformation:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="order">
   <xsl:copy>
    <xsl:apply-templates select="customer"/>
    <xsl:apply-templates select="*[not(self::customer)]"/>
   </xsl:copy>
 </xsl:template>

 <xsl:template match="ship">
  <xsl:copy>
   <xsl:apply-templates select="street"/>
   <xsl:apply-templates select="city"/>
   <xsl:apply-templates select="zipcode"/>
   <xsl:apply-templates select="country"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="items">
  <xsl:copy>
   <xsl:apply-templates select="itemno"/>
   <xsl:apply-templates select="quantity"/>
  </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:
<order xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" >
    <ship>
        <zipcode>78712</zipcode>
        <street>1234 Main Street</street>
        <country>CN</country>
        <city>Beijing</city>
    </ship>
    <items>
        <quantity>1</quantity>
        <itemno>1234</itemno>
    </items>
    <items>
        <quantity>3</quantity>
        <itemno>1235</itemno>
    </items>
    <price>456</price>
    <customer>Tom Hill</customer>
</order>

the wanted, correct result is produced:
<order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <customer>Tom Hill</customer>
   <ship>
      <street>1234 Main Street</street>
      <city>Beijing</city>
      <zipcode>78712</zipcode>
      <country>CN</country>
   </ship>
   <items>
      <itemno>1234</itemno>
      <quantity>1</quantity>
   </items>
   <items>
      <itemno>1235</itemno>
      <quantity>3</quantity>
   </items>
   <price>456</price>
</order>

Explanation:
<xsl:copy-of select="someElement"/>

copies the whole subtree rooted by someElement exactly as is (and if we had an instruction that rearranges the descendants, how would this instruction know the order that we want???).
In order to change the order of any siblings - elements, we must specify the new, wanted order.
This can be done by writing a sequence of <xsl:apply-templates> instructions, each selecting the desired element -- in the desired order. We could write <xsl:copy-of> instructions, but only for copying elements, whose descendents we want to remain in their original order.


Pass the id of one node by url for new node

Question: I have 2 content types, person and date. Date have a relation with person, in one node of person, you can see the dates of that person.
I want add a link in the nodes of person for add a date for that person (this is easy), i need pass the id of the person node automatically to the new node of date.
I don't know how to do this, anyone can help me?
Thanks.
EDIT:
Will try to explain it better:
I use node reference module for create the relation between the two content types. When i add a node of date, all fields are in blanc, if i add one date node through node of person, the id of that node, will add automatically to the new date node in the field that relation the two content types.
Answer: One easy way to do this is with the module
nodereference_url

The Node Reference URL Widget module adds a new widget to the Node
  Reference field type. It auto-populates a node reference field with a
  value from the URL, and does not allow this value to be changed once
  set. It can automatically provide a link on the referencing node
  types, that will contain the proper URL to prepopulate the field.
Comment: Yea, sorry, I read the wrong name of the module, i read nodereference only xD, is it about the fatigue. Sorry.i going to try with it.
Comment: I forgot to say that I am already using that module. thank for the answer.
Comment: Are you using nodereference_url for the form widget? (different from the nodereference module only) if so, that should work fine.
Comment: I solve it. I use nodereference_url module, and the custom url is created with this php code in a block and put the block in the person content type:
nid;
 $name = $node->title;
}
?>
A&ntildeadir cita a


Passing one functions variable to another function correctly?

Question: Ok peeps, say I've got something like:
Function Get-Reports {
 # Get managers direct report, calls function above
 $DirectReports = Get-DirectReport $Manager -norecurse  | Select-Object samAccountName
 if ($null -ne $DirectReports) {
     #$LogLine = "Gathering direct reports for " + $Manager
     #Log-Write -LogPath $sLogFile -LineValue $LogLine
 } else {
     $LogLine = $Manager + " has no reports."
     #Log-Write -LogPath $sLogFile -LineValue $LogLine
     #Continue
 }
}
Function Set-RTGmembers {
    # Get manager's 'report to <manager>' group again to update members
    $managerReportToGroup = Get-ADGroup -SearchBase $ou -Filter "Name -like 'Report to $Manager'"
    if ($managerReportToGroup) {
        Add-ADGroupMember -identity $managerReportToGroup.Name -members $DirectReports
        Add-ADGroupMember -identity $managerReportToGroup.name -members $Manager
        $LogLine = "Report to " + $Manager + " updated."
        #Log-Write -LogPath $sLogFile -LineValue $LogLine
    } else {
        $LogLine = "Could not find group for " + $Manager
        #Log-Write -LogPath $sLogFile -LineValue $LogLine
    }
}

Foreach ($manager in $managers) {
    Get-Reports
    Set-RTGmembers
 }

I get an error saying the Add-ADGroupMember's -members $DirectReports value is empty. I've debug it and it's indeed empty. How do I pass a variable created in a function to another function?  Should I combine them maybe?
Comment: Your functions need to define some parameters which you pass object in by.  Additionally you'll probably want your functions to output some objects  https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions?view=powershell-7.1
Answer: What you need to do is to return something from the function and pass it as a parameter for the other one. But in your case, the first function is not needed Something like this
Function Set-RTGmembers {
    Param(
        $Reports,
        [string]$Manager,
        [string]$OU
    )
    # Get manager's 'report to <manager>' group again to update members
    $managerReportToGroup = Get-ADGroup -SearchBase $OU -Filter "Name -like 'Report to $Manager'"
    if ($managerReportToGroup) {
        Add-ADGroupMember -identity $managerReportToGroup.Name -members $Reports
        Add-ADGroupMember -identity $managerReportToGroup.name -members $Manager
        $LogLine = "Report to " + $Manager + " updated."
        #Log-Write -LogPath $sLogFile -LineValue $LogLine
    } else {
        $LogLine = "Could not find group for " + $Manager
        #Log-Write -LogPath $sLogFile -LineValue $LogLine
    }
}

$ou = 'SomeOUName'
Foreach ($manager in $managers) {
    $DirectReports = $null #This is to make sure if the Get-DirectReport fails on the last loop, it won't use the last set value
    $DirectReports = Get-DirectReport $manager -norecurse  | Select-Object samAccountName
    if ($null -ne $DirectReports) {
         #$LogLine = "Gathering direct reports for " + $Manager
        #Log-Write -LogPath $sLogFile -LineValue $LogLine
    } else {
         $LogLine = $manager + " has no reports."
         #Log-Write -LogPath $sLogFile -LineValue $LogLine
         Continue
     }
    Set-RTGmembers -Reports $DirectReports -Manager $manager -OU $ou
}

Remember that each function has its own scope and the variables declared inside them gets cleared when the function finishes
Comment: Inside the function, you can declare the param you're passing using `Param()` at the beginning of the function so those variables belong to the function scope and when you passe them using `-ParamName` (When ParamName means the Variable declared inside the `Params()` section) you set those variables values, therefore, you can use them inside the function
Comment: In case you need a bit more information, you could check here (https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions?view=powershell-7.1) and here (https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-7.1) or here (https://www.tutorialspoint.com/how-to-pass-the-parameters-in-the-powershell-function)
Comment: Question though, in my original code I'm passing (or trying to pass) $DirectReports to the next function Set-RTGmembers. In your example there's no source for $Reports.  Now $Manager I define up at the beginning of the script but $Reports or $DirectReports was originally a loop that I was trying to turn into a function.


What is the range of $f(x,y)=e^{-(x^2+y^2)}$

Question: I know the domain is $\mathbb{R^2}$.
Is the range $\mathbb{R}$?
Comment: The output is a scalar, how could the range even be $\mathbb R^2$?
Comment: $f:\mathbb{R}^2 \rightarrow \mathbb{R}$.
Comment: If you raise $e$ to a power that is a real number, you always get a positive number.  So $0$ and negative numbers cannot be within the image of this function.
Answer: $$x^2+y^2\ge 0 \implies e^{-(x^2+y^2)}\le e^{-0}=1$$
$$x^2+y^2<\infty \implies e^{-(x^2+y^2)}\gt e^{-\infty}=0$$
So the range of $f(x,y)$ is $(0,1]$.
Comment: Note that this answer just proves that $\text{ran}(f)\subseteq ]0,1]$. You still need to prove the other inclusion.
Comment: I am not familiar with symbol $]0$. What does it mean?
Comment: The symbol $]$ is another way to denote $($.
Comment: If $0 < r \le 1$, $f(0, \sqrt{\ln(1/r)}) = r$.
Answer: What are the possible values?  For example, $f(1,0)=e^{-1}$, so $e^{-1}$ is in the range.  Note $e^{-1}$ is not in $\mathbb{R}^2$.
Comment: So $[0, \infty)$? Since there is no way to get negative numbers
Comment: @RoyM. Can you get say, $e^2$? Can you get $0$?
Comment: Ah I see, no there is no way to get $e^2$ or $0$
Comment: @RoyM. Now what is special about $e^2$? What other numbers can't you get?
Answer: You are looking for all possible values of this function.
First note that $f: \mathbb{R}^2 \rightarrow \mathbb{R}$, so the possible values of $f$ are real number.
Next notice that $x^2+y^2$ for $(x,y) \in \mathbb{R}^2$ can reach all non-negative real value (choose real non-negative $t \in \mathbb{R}$, $x^2+y^2$ reach value $t$ for $(x,y)=(\sqrt{t},0)$ . Note that for $(x,y) \in\mathbb{R}^2$ $x^2+y^2$ don't reach negative value.
Now you can check range of $e^{-x^2-y^2}$:you know that range of $x^2+y^2$ (all non-negative real numbers), so $e^{-x^2-y^2}$ reach the same values like $e^{-t}$ for non-negative real $t$, so the range is $(0,1]$.


Help with Derivative

Question: So I'm trying to find the derivative of $f(x) = 3x + 4\sqrt{x}$
So far I got this far:
1.
$\displaystyle \frac{3(a+h)+ 4\sqrt{a+h} - (3a + 4\sqrt{a})}{h}$
2.
$\displaystyle \frac{3a + 3h + 4\sqrt{a+h} - (3a + 4\sqrt{a})}{h}$
3.
$\displaystyle \frac{3h + 4\sqrt{a+h} - 4\sqrt{a}}{h}$
I'm not sure what to do after step three in solving the square roots.
Comment: Do you have to use the limit definition? Have you already covered the sum and constant multiple rules for derivatives, and the derivatives of the identity and square root functions?
Comment: Otherwise, break your expression up as $3+4\cdot{\sqrt{a+h}-\sqrt a\over h} $. Then use the procedure of the answers below to deal with the square root term.
Comment: It would be a good idea if you edited your question and clarified that you have to find the derivative from first principles.
Comment: @DavidMitra You should probably post this as an answer. The sum rule and the constant product rule are exactly what he needs. I would post it as an answer myself but that would just be rude.
Answer: If you've heard of rationalizing the denominator, then now you get to rationalize the numerator; multiply top and bottom by $4(\sqrt{a+h}+\sqrt{a})$; the top will now be free of square roots. The denominator won't be, but you will be able to take a limit.  (It would probably be easier to separate the $3h/h$ out first.)
Answer: Use the fact that
$$\frac{\sqrt{a+h}-\sqrt{a}}{h} =
\frac{(\sqrt{a+h}-\sqrt{a})(\sqrt{a+h}+\sqrt{a})}{h(\sqrt{a+h}+\sqrt{a})}=
\frac{1}{\sqrt{a+h}+\sqrt{a}} \to \frac{1}{2\sqrt{a}}$$
as $h\to 0$.

Help with Derivative


Running mssql-server-linux image in QUIET mode

Question: I am using microsoft/mssql-server-linux:2017-latest MS SQL docker image.
It works fine, but outputs dozens of information, which I would be happy to omit. I couldn't find command line or environment options to run it in quiet mode, can anyone help me?
FYI command line is:
docker run -e ACCEPT_EULA=Y -e SA_PASSWORD="<BestPwd>" -e MSSQL_PID=Express -it microsoft/mssql-server-linux:2017-latest

Just appending -q didn't help..
UPD
I know containers can be run in daemon mode, what I need is to reduce log to warnings level and not removing it completely.
Also I would appreciate generic methods; which are NOT connected with stdout redirection or grepping / filtering output.
Answer: You can use -d option to run the container in the background using below command.
docker run -e ACCEPT_EULA=Y -e SA_PASSWORD="<BestPwd>" -e MSSQL_PID=Express -d microsoft/mssql-server-linux:2017-latest

If you want to see the logs then you can give docker logs -f 'containerid'
Comment: Yes, I know that, actually I run container with `docker-compose`. What I need is the way to **reduce** sql server output to lets say warning level.


Which space is the completion of Riemann integrable class?

Question: It seems to me, on $\mathbb{R}$ or $[0, 2\pi]$, the completion of Riemann integrable functions should be $L^1$. However, on p.76 of Stein's Fourier analysis: an introduction, it is also claimed the completion is $L^2$.
I'm a little confused. Should I understand it as, we can equip different norms on the vector space of Riemann integrable functions. Then, if we equip the norm as the Lebesgue integral of absolute value, the completion is $L^1$. But if we equip an inner-product and make it into a pre-Hilbert space, then the completion becomes $L^2$?
Does this mean other spaces can also be the completion of Riemann integrable functions?
Thanks in advance.
Comment: Related: https://math.stackexchange.com/q/4675674/1104384 Completions are always tied to a metric (here a norm), so of course the completion will change based on the norm you imbued the space of Riemann integrable functions with.
Comment: Depends on the norm you are considering. Both answers are correct. In fact, the coalition of the space of Riemann integrable functions under the norm $\|f\|_p=\Big(\int^b_a |f|\big)^{1/p}$, $0\leq p<\infty$ is $\mathcal{L}_p([a,b]$ (identifying a.s. zero functions). The reason is that all continuous functions are Riemann integrable.
Comment: One or both of these questions deserve actual answers @BrunoB.
Comment: @LeeMosher I mean, the one I linked was pretty much just helping OP with hints then saying "yes your solution works", I don't really think it needs an answer (though I won't prevent anyone from making one!), but sure I can turn my comment here into an answer I guess. Don't really know what else to add though, is the thing.
Comment: Well, small answers are sometimes really good.
Answer: For a given set there is almost never one single completion, as you need to set a metric (or norm, but it's tied to that as you can consider the metric induced by the norm) on your set to speak of completeness and completions, and each metric may provide a different completion.
For instance, due to the density of continuous functions in every $L^p$ for the $L^p$ norm, and the fact that Riemann integrable functions contain continuous functions and are contained in $L^p$, the completion of the Riemann integrable functions for the $L^p$ norm is $L^p$. In fact, there is even a metric, that of uniform convergence, for which the Riemann integrable functions form a complete space themselves, meaning they are their own completion for that metric.


How do I get a freshly updated value (i.e. not the cached value) using entity_metadata_wrapper?

Question: In my code I am inserting a new value into the database directly using db_insert (i.e. inserting an entirely new row).  The type of field, however, already exists in Drupal which is called "field_data_field_email_address".  Previous to the insert call no value existed in the database which is associated with an entity.
Later in code I am relying on entity_metadata_wrapper to retrieve the values associated with the entity.  The problem is that the wrapper doesn't retrieve the most recently inserted value but instead returns nothing.  Yet when I look in the database table I can clearly see the existence of the newly inserted value.
As you may have already guessed I narrowed the issue down to a caching issue because if I clear the Drupal cache the wrapper returns the newly created value just fine.
My question is this: How can I force the entity_metadata_wrapper call to not retrieve the cached version but refresh and return to me the actual current values that exist in the database.  I need my wrapper to represent the freshest data and not the cached version.
Thank you in advance!
Comment: The short answer is to never bypass the Field API to update an entity.  The long answer depends on what caching strategies / modules your site is using.
Comment: Actually I think after my db_insert call I can use entity_load() and set the optional parameter $reset to true to update its internal cache.  Testing now, will respond with results in a second.
Comment: Bam! That worked perfectly.
Comment: Related http://drupal.stackexchange.com/questions/108188/is-it-proper-to-perform-a-db-update-on-an-entity-table
Answer: The cache can actually be cleared using the entity_load function and passing a value of true for $reset which will clear the cache and update future references to it including wrappers retrieved from entity_metadata_wrapper:
entity_load("node", array($nid), null, true);

Comment: I am actually not 100% sure this is accurate.  IIRC, the `$reset` has to do with the static cache, and not {cache_field} nor the entity cache tables.
Comment: Hmm... the result I was looking for worked.  Any insight into what was going on for it to work the way I intended then?
Comment: I am not sure.  I would want someone more familiar with the Entity controllers to weigh in, though mikeytown2 did give a detailed link (and he is a smart dude).
Answer: For nodes, I found this snippet on hook_node insert helpful:
entity_get_controller('node')->resetCache(array($w->getIdentifier()));


Existem ambientes online de aprendizagem de programação com exercícios práticos e desafios para C#?

Question: Existem alguns sites, tal como o URI Online Judge, que permitem aos programadores praticarem programação e compartilhar conhecimento através de exerícios específicos e desafios lógicos e matemáticos.
Porém alguns são restritos quanto à linguagem. O mencionado acima, por exemplo, aceita apenas respostas em C++ e Java.
É possível encontrar outros ambientes de aprendizagem de programação que aceitem outras linguagens, preferencialmente com suporte à C#.
Answer: Alguns sites que aceitam C#:

TopCoder
CodeJam
USACO Training Program
CodeChef
Sphere Online Judge
Timus Online Judge
ProjectEuler
CodeEval
Code Hunt


Why are these two projective schemes isomorphic?

Question: From Ravi Vakil's Foundations of Algebraic Geometry, exercise 7.4.C: Let $R = k[x, y, z]/(xz, yz, z^2)$. Show that $\operatorname{Proj} R \cong \mathbb{P}_k^1$ (as schemes).
My thought was to induce a map of schemes via the ring morphism $\phi: R \rightarrow k[s, t]$, with $x \mapsto s, \; y \mapsto t, \; z \mapsto 0$. But I don't know how to show that this induces an isomorphism of schemes. In particular, in $\operatorname{Proj} R$ the two ideals $(x + y)$ and $(x + y + z)$ (for example) are different, which doesn't seem to have a counterpart in $\mathbb{P}_k^1$.
Edit: It's been suggested that we can check this locally. To check locally, define $\alpha:k[s,t]→R$
by $s,t↦x,y$. This induces $\pi:\operatorname{Proj}R→\mathbb{P}_1^k$
such that $\pi^{-1}(D(s))=D(x)$
and $\pi^{-1}(D(t))=D(y)$. I can see that $\pi$
gives a bijection on each of these open sets, but I can't see that it gives isomorphisms of schemes: for example, taking $\varphi:\mathcal{O}_{\operatorname{Proj}R}→\mathcal{O}_{\mathbb{P}_1^k}$
induced by $\alpha$
, we get $\varphi(D(s)):k[\frac{t}{s}]→k[\frac{y}{x},\frac{z}{x}]$
, which is not an isomorphism. Am I doing this wrong?
Comment: Do you know that you can check that this map is an isomorphism locally? (One small formatting tip: `$\operatorname{Proj}$` produces $\operatorname{Proj}$, which displays a little better than what you had before. I've made the change for you this time.)
Comment: One can have nonisomorphic rings $R$ and $S$ which give rise to the same $Proj$ (an exercise in Hartshorne II.5 gives an example I think). In this case, you should check this locally.
Comment: I wouldn't even check this locally, I am pretty sure Vakil shows that taking a subring of a graded ring consisting of the graded pieces with indices multiples of some $d>1$ doesn't change the $\operatorname{Proj}$. In this case if you do this (this is called taking the Veronese subalgebra) you get something familiar.
Comment: To check locally, define $\alpha: k[s, t] \rightarrow R$ by $s, t \mapsto x, y$. This induces $\pi: \operatorname{Proj} R \rightarrow \mathbb{P}_k^1$ such that $\pi^{-1}(D(s)) = D(x)$ and $\pi^{-1}(D(t)) = D(y)$. I can see that $\pi$ gives a bijection on each of these open sets, but I can't see that it gives isomorphisms of schemes: for example, taking $\phi: \mathcal{O}_{\operatorname{Proj} R} \rightarrow \mathcal{O}_{\mathbb{P}_k^1}$ induced by $\alpha$, we get $\phi(D(s)): k[\frac{t}{s}] \rightarrow k[\frac{y}{x}, \frac{z}{x}]$, which is not an isomorphism. Am I doing this wrong?
Comment: Please put that work in your question with an [edit]. (Yes, you've made a small mistake there, I'll write an answer once you've put your work in the question.)
Answer: You're on the right track with checking locally, but you have made a small error in calculating the sections of $\operatorname{Proj} R$ on the open sets $D(x)$ and $D(y)$. Recall that $\mathcal{O}_{\operatorname{Proj} R}(D(x))\cong R_{(x)}$, the homogeneous localization of $R$ at the element $x$. In other words, this is $(R_x)_0$, the degree-zero portion of the graded ring $R_x$. This is $$k\left[\frac{y}{x},\frac{z}{x}\right]/\left(\frac{z}{x},\frac{yz}{x^2},\frac{z^2}{x^2}\right)\cong k\left[\frac{y}{x},\frac{z}{x}\right]/\left(\frac{z}{x}\right)\cong k\left[\frac{y}{x}\right]$$ and indeed the map of sections here is an isomorphism, identifying $\frac{y}{x}$ and $\frac{t}{s}$.
Alternatively, as suggested in the comments, one may use the fact that if $S=\bigoplus_n S_n$ is a graded ring, the Veronese subring $S^{(d)}=\bigoplus_n S_{nd}$ has the same Proj. In this case, since $R=k[x,y,z]/(xz,yz,z^2)$ has $R_d\cong k[x,y]_d$ for any $d\neq 1$, then we can use this fact twice to obtain the claim.


How to retrieve image from database of image datatype to the PhotoBox in c#

Question: The code below is my photo selecting selector (the other button I have in my project is just sending the picArray to the table in the column of image datatype):
private void FileSelectorButton_Click(object sender, EventArgs e)
    {

        OpenFileDialog ImageSelectorWindow = new OpenFileDialog();
        ImageSelectorWindow.Filter = "JPG |*.jpg|PNG |*.png|Bitmap |*.bmp";
        ImageSelectorWindow.Title = "Choose an Image";
        if (ImageSelectorWindow.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            fileName = ImageSelectorWindow.FileName;

            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            picArray = new byte[fs.Length];

            fs.Read(picArray, 0, Convert.ToInt32(fs.Length));
            fs.Close();
        }

        TBFilePath.Text = fileName;

    }

Below is my image retrieval code:
SqlCommand cmd2 = new SqlCommand("SELECT avatar FROM Members WHERE Id = '" + value + "'", con);

SqlDataReader dr = cmd2.ExecuteReader();

MemoryStream ms = new MemoryStream((byte[])dr[0]);

PBMemberImage.BackgroundImage = new Bitmap(ms);

This is giving me the following exception:

Can someone help me figure out why?
Answer: Retrieve Images from sql server database
Take a look at that and try the code below for retrieving your image. Let me know if that works or not.
byte[] img = (byte[])cmd2.ExecuteScalar();
MemoryStream ms = new MemoryStream();
ms.Write(img, 0, img.Length);
PBMemberImage.BackgroundImage = new Bitmap(ms);

Comment: **Its giving this exception now after your code** @forwardi
System.ArgumentException: Parameter not Valid
Comment: Which line specifically is it saying that's on?
Comment: PBMemberImage.BackgroundImage = new Bitmap(ms); //On this line


Jogar uma classe html dentro de um código asp.net

Question: Tenho esse código:
<%# Eval("DsPathDocumento") != null && !String.IsNullOrEmpty(Eval("DsPathDocumento").ToString()) ? String.Concat("href='/UpLoads/", Eval("DsPathDocumento"), "'") : "style='cursor: default; color:#000000;'" %>>

Como eu faria para jogar essa classe: class="linkUpload" dentro da primeira condição da expressão ternária? Ou seja, gostaria de apenas a parte após o "?" pegasse essa classe para que a minha função jquery pudesse rodar.
$(document).ready(function () {
        $('.linkUpload').click(function (event) {
            event.preventDefault();
            window.open($(this).attr("href"), "popupWindow", "scrollbars=yes");
        });
    });

Answer: Resolvi assim:
<a <%# Eval("DsPathDocumento") != null && !String.IsNullOrEmpty(Eval("DsPathDocumento").ToString()) ? String.Concat("href='/UpLoads/", Eval("DsPathDocumento"), "'","class='linkUpload'") : "style='cursor: default; color:#000000;' class='disabled'" %>>
                        <%# Eval("NmTipoDocumento") %>


How to update a task dynamically in the syncfusion's gantt (only one task)

Question: In the gantt's documentation, i didn't find a method to update a single task data. All we have for updating is the updateDataSource() method and the worst is that we need call refresh() after it to see the update in the dom which refresh all the tasks and not the only modified task.
In this stackblitz demo i've tried only pass the task i need to update to updateDataSource() but the result is that only that same task will be displayed
In the gantt's editing demo when a task is updated via the dialog, only that task will refresh and not all task , there should be a method that is not exposed in the api that does it
i'm using gantt's react lib.
Answer: We can update a particular task using updateRecordById method. For this we need to inject Edit module. Please refer the below documentation link.
Documentation - https://ej2.syncfusion.com/react/documentation/gantt/managing-tasks/#update-task-values-using-method
<code>var ganttObj = document.getElementById('Default').ej2_instances[0];
var data = { TaskID: 2, Duration: 7 };
ganttObj.updateRecordByID(data);
</code>
Sample - https://stackblitz.com/edit/react-6lscfc-hynwz7?file=index.js


Struggling with combinatorics and intuitive thinking

Question: Ok I have a basic exercise that wants me to explain in my own words the following :
$a) \ \ L_{k}^{or}(N)=N\cdot L_{k-1}^{or}(N) $
$b) \ \ L_{k}^{os}(N)=(N-k+1)\cdot L_{k-1}^{os}(N) $
$c) \ \ L_{k}^{ns}(N) \cdot L_{k}^{os}(k)= L_{k}^{os}(N)$
$\cdot \ \textbf{or}$ means $\textbf{ordered}$ samples $\textbf{with}$ replacement
$\cdot \ \textbf{os}$ means $\textbf{ordered}$ samples $\textbf{without}$ replacement
$\cdot \ \textbf{nr}$ means $\textbf{non-ordered}$ samples $\textbf{with}$ replacement
$\cdot \ \textbf{ns}$ means $\textbf{non-ordered}$ samples $\textbf{without}$ replacement
$-$ The first one is pretty easy, if I pickup $k$ samples from $N$ and replace it every-time, I still have $N$ choices next time.
$-$ The second one too, if I pickup $k$ samples from $N$ and I don't replace them in the bag, I will have $N-(k-1)$ choices the next time $\iff$ $N-k+1$
$-$ But I have no idea for the third one. I struggle a lot with intuitive thinking in combinatorics, probability etc.. Any help would be great !
Comment: Should one of those "with"s be "without"?
Comment: thanks, solved it
Answer: I assume all objects as distinct. In third case, we are selecting without replacement.
LHS means that you choose $k$ objects from $N$ objects without considering order, and after choosing you order them.
RHS means that you choose $k$ objects from $N$ objects, but you also consider the order of these $k$ objects while selection.
Alternatively
We have that $L_{k}^{ns}(N) = \binom{N}{k}$ and $L_{k}^{os}(k) = k!$. Also $L_{k}^{os}(N) = k! \binom{n}{k}$


How to access gradle test reports from a docker container

Question: I'm using a docker container to build and run my java application and I want to see the test results that would usually be available from build/reports/tests/test/index.html.
Here's my Dockerfile:
FROM alpine:latest

RUN apk add gradle openjdk17

WORKDIR /home/proj
COPY . .

RUN gradle build

ENTRYPOINT [ "java", "-jar", "./app/build/libs/app.jar" ]

Here's my docker-compose.yml:
version: "3.8"
services:
  app:
    build: .

I typically build my container with docker-compose build and run it with docker-compose up and would like this to stay as it is.
EDIT
I've tried changing my docker-compose.yml to:
version: "3.8"

services:
  app:
    build: .
    volumes:
      - ./tests:/home/proj/app/build/reports/tests/test

But this just creates an empty directory called tests in my project's root directory. I am 100% sure the right path is /home/proj/app/build/reports/tests/test as you can see here:
Comment: If we want to access data from a container after the container has terminated, we usually use [volumes](https://docs.docker.com/storage/volumes/). There are, however, a few things to consider, mainly access rights. If the docker daemon runs under root profileges, the directories and files in the mount are also owned by root on the host.
Answer: I've hit this same issue. Unfortunately volumes are only availible to docker run, they aren't part of the docker build portion of the docker compose process.
I even looked into the new RUN --mount=type=bind,source=.,target=./build/reports,rw gradle build and while in the container I can see (with a RUN ls ./build/reports) the reports being generated, but that mount (even as RW) only puts files in the container as a layer and they never appear on the host machine.
There is a hacky way to recover those test results, in the docker output, just above the failure you'll see this line ---> Running in f98e14dd1ee4. This is the layer ID, with that value you can copy from the failed layer to the local machine using
$ docker cp f98e14dd1ee4:/tmp/build/reports ./

$ ls reports/
checkstyle/ jacoco/     tests/

It shouldn't be to difficult to automate this kind of recover but it feels like it would be fragile automated.
I'm very interested if anyone has a better solution to this, even with an alternative to docker. I know I can build the container with gradle but I'd rather everything happens inside the container build process to keep the build environment defined as code.


C++ portable way to getting the value representation of a u8 string literal

Question: Let's consider:
char const str[] = u8"ñ";
auto const* u8_code_units = reinterpret_cast<unsigned char*>(str);
// using u8_code_units elements

Is that fully portable and C++ standard compliant? Or there's some clause that says that it's undefined behaviour or depends on any unspecified value? I know that unsigned char and char shall have the same alignment requirements and reinterpret_cast<T*>(v) equals in that case to static_cast<T*>(static_cast<void*>(v)), so, I think it is completly safe and portable to use it but I'm not sure.
Answer:
Is that fully portable and C++ standard compliant?

Kinda, but not for the reason you think.
See, you have to actually save that file to disk in some format. Which means your compiler has to be able to read that same format. And what text formats a compiler supports is implementation-defined.
However, if your compiler supports the format you saved it in, and that format can save Unicode-encoded characters, then your compiler will do the right thing here.
Even the reinterpret_cast is fine, because the compiler requires that char arrays can be accessed through unsigned char arrays, even if the platform's char is signed. And the standard explicitly requires that, when reading a UTF-8 formatted char array through an unsigned char, you will get the bits you expect from the UTF-8 formatting.
Note however:

I know that unsigned char and char shall have the same alignment requirements and reinterpret_cast(v) equals in that case to static_cast(static_cast(v)),

That would not be enough to protect you. It works because the standard explicitly says that it works in this particular case, not because of alignment requirements and such. char and unsigned char have exceptions to the rules on aliasing to allow this; alignment has nothing to do with it.
Comment: @Peregring-lk: No, I meant what I said: if you have an `unsigned char` on the range 0-255, it has a 1:1 mapping with a unique `char` value when converting back and forth. So 255 will convert to *some* `char` value, and that value will uniquely convert back to 255. So doing `some_char == (char)0xFF` is well-defined in C++, even if `char` is signed.
Comment: the alignment requirement is needed to ensure the cast from `void*` to `T2` returns the same memory location as `t2` before `static_cast(t2)`. That is why I remarked it. And thanks for pointing me out the "alias" thing. I googled and I have already found that strict aliasing exception in the standard (3.10§10).
Comment: Related-question: is that the only way to read the underlying bytes?
Comment: @Peregring-lk: You could just read it as `char`s. The standard guarantees that, within the `unsigned char` range 0-255, there is a 1:1 mapping to `char` values. So if you cast the value 0x80 to a `char`, it is guaranteed to compare equal to the `unsigned char` value of 0x80. Of course, if you want to do bit fiddling for UTF-8 operations, you'll need to read them as `unsigned char`s.
Comment: In the range 0-127 you mean? How signed values are represented is implementation-defined.


Return a dictionary of words and their number of occurrence's found in a string

Question: I have a large list of specific keywords I would like to count in a large string description. I would like to return a dictionary of the keywords and their number of occurrences in said string, for example:
description = "Apples and oranges are the best fruit, I'm growing some trees outside. Apples are my favorite, oranges are cool too"
keywords = ['apples', 'oranges', 'fruit', 'trees']

I'd like to count the number of times these keywords are found in the string and return something like this:
{'apples': 2, 'oranges' 2, 'fruit': 1, 'trees': 1}

I'm not exactly sure how to go about this, I've tried using Counter but was only able to figure out how to count the number of words in a list. Could I also use NLTK for this? I'm trying to think of a solution I could scale up for huge lists and descriptions. Any help in the right direction would be greatly appreciated.
Answer: Try this clear and concise dictionary comprehension using str.count():
{word: description.lower().count(word) for word in keywords}


Setting String Character Limit PHP

Question: I am creating a vine script, and I am trying to collect the thumbnail .jpg from a selected vine video url set by my script as seen below is how it's called on my og:image:secure_url
<meta property="og:image:secure_url" content="{php} echo vine_pic($this->_tpl_vars['p']['youtube_key']);{/php}" />
What I need help with
Setting a string limit of 147 Characters. Because when thumbs are generated from the vine video url they appear like this..
https://v.cdn.vine.co/r/thumbs/6A6EB338-0961-4382-9D0D-E58CC705C8D5-2536-00000172EBB64B1B_1f3e673a8d2.1.3.mp4.jpg?versionId=i7r_pcP2P1noapLmoI0QgrtvsD8ii43f

og:image:secure_url will not read right if it contains the extra characters as listed
?versionId=i7r_pcP2P1noapLmoI0QgrtvsD8ii43f
My Code to Put the string limit in
function vine_pic( $id )
{

$vine = file_get_contents("http://vine.co/v/{$id}");

preg_match('/property="og:image" content="(.*?)"/', $vine, $matches);

return ($matches[1]) ? $matches[1] : false;

// As you see below, I made an attempt but it doesn't work.
substr(0, 147, $vine, $matches);

}

Comment: Your function always returns before substr() can be called.
Answer: Your substr() syntax is incorrect.
It should actually be:
substr ($string, $start, $length)

To use substr(), you'll need to store the thumbnail URL in a variable, like so:
function vine_pic( $id )
{
    $vine = file_get_contents("http://vine.co/v/{$id}");
    preg_match('/property="og:image" content="(.*?)"/', $vine, $matches);
    $thumb = ($matches[1]) ? $matches[1] : false;
    $thumb = substr($thumb, 0, 147);
    return $thumb;
}

It might be a good idea to check if $thumb is set before trying to use substr():
if ($thumb) {
    $thumb = substr($thumb, 0, 147);
    return $thumb;
}

Setting String Character Limit PHP


Why is a particular measure of Rach Prelude in C# minor always played slowly?

Question: I've noticed that in many renditions of Rachmaninov's Prelude in C# Minor (Op. 3 No. 2) that the fourth measure of the Agitato section is always played in a slow, unusual (almost weird) fashion.  You can hear what I'm talking about here:
Video
I normally play that part the same speed as the rest of the section, just quieter (since it says "dim.") but many famous performers do not.  Is this something originated by Rachmaninov in his live performances that others just stuck with? What is the correct way to play that?
Answer: You did notice that the performance you linked is by Rachmaninov himself, right? He plays the other parts with quite a free tempo, too. In this particular point it's natural to take back because of the diminuendo and end of phrase. Making the melody triplets+thirds work might also be hard in faster tempo. It also contrasts measure 8 where it's natural to go a little forward. Finally the Agitato marking just allows some instability in tempo. So, there you have some reasons to play it like this. Still, there's no correct way so if you can make it work without slowing down, you can do that, too.
Comment: Yeah, I noticed it was him.  Good explanation!


Windows AD domain - Server 2008 level - How to forward DNS requests for a single subdomain only to an external DNS server?

Question: Internally, our AD domain is contoso.com, and our internal DNS servers present that domain authoritatively.
We're at Server 2008 forest/domain level.
Externally, contoso.com is a domain owned and registered by us that is registered with an external DNS provider.
Internally, we'd like to forward requests for subdomain.contoso.com to the external DNS provider.
I tried to set up a conditional forwarder for this but got the highly useful error message "A problem occurred while trying to add the conditional forwarder.  A zone configuration problem occurred."
I read elsewhere this is because our DNS presents the contoso.com domain authoritatively... in order to resolve this we'd need to forward requests for that to this provider, which unfortunately is not an option.
Is there a way we can accomplish this?
Answer: Because this is a subdomain of your AD domain you can't use a conditional forwarder. What you can do is to configure a delegation of the subdomain to the external DNS servers.
Right click your AD DNS zone and select New Delegation and follow the prompts.
Comment: Glad to help...