Slice a string after a certain phrase?

Question: I've got a batch of strings that I need to cut down. They're basically a descriptor followed by codes. I only want to keep the descriptor.
'a descriptor dps 23 fd'
'another 23 fd'
'and another fd'
'and one without a code'

The codes above are dps, 23 and fd. They can come in any order, are unrelated to each other and might not exist at all (as in the last case).
The list of codes is fixed (or can be predicted, at least), so assuming a code is never used within a legitimate descriptor, how can I strip off everything after the first instance of a code.
I'm using Python.
Comment: In your examples, what are the codes, and what should the output look like?
Answer: The short answer, as @THC4K points out in a comment:
string.split(pattern, 1)[0]

where string is your original string, pattern is your "break" pattern, 1 indicates to split no more than 1 time, and [0] means take the first element returned by split.
In action:
>>> s = "a descriptor 23 fd"
>>> s.split("23", 1)[0]
'a descriptor '
>>> s.split("fdasfdsafdsa", 1)[0]
'a descriptor 23 fd'

This is a much shorter way of expressing what I had written earlier, which I will keep here anyway.
And if you need to remove multiple patterns, this is a great candidate for the reduce builtin:
>>> string = "a descriptor dps foo 23 bar fd quux"
>>> patterns = ["dps", "23", "fd"]
>>> reduce(lambda s, pat: s.split(pat, 1)[0], patterns, string)
'a descriptor '
>>> reduce(lambda s, pat: s.split(pat, 1)[0], patterns, "uiopuiopuiopuipouiop")
'uiopuiopuiopuipouiop'

This basically says: for each pat in patterns: take string and repeatedly apply string.split(pat, 1)[0] (like explained above), operating on the result of the previously returned value each time.  As you can see, if none of the patterns are in the string, the original string is still returned.

The simplest answer is a list/string slice combined with a string.find:
>>> s = "a descriptor 23 fd"
>>> s[:s.find("fd")]
'a descriptor 23 '
>>> s[:s.find("23")]
'a descriptor '
>>> s[:s.find("gggfdf")] # <-- look out! last character got cut off
'a descriptor 23 f'

A better approach (to avoid cutting off the last character in a missing pattern when s.find returns -1) might be to wrap in a simple function:
>>> def cutoff(string, pattern):
...     idx = string.find(pattern)
...     return string[:idx if idx != -1 else len(string)]
...
>>> cutoff(s, "23")
'a descriptor '
>>> cutoff(s, "asdfdsafdsa")
'a descriptor 23 fd'

The [:s.find(x)] syntax means take the part of the string from index 0 until the right-hand side of the colon; and in this case, the RHS is the result of s.find, which returns the index of the string you passed.
Comment: `the_string.split(pattern,1)[0]` is the same I think.
Comment: Mark with the split, what happens if there is no code in the string (a slightly although existing possibility)? And with both is there not a better way to check multiple codes at once. Both examples only appear to deal with one at a time.
Answer: You seem to be describing something like this:
def get_descriptor(text):
    codes = ('12', 'dps', '23')
    for c in codes:
        try:
            return text[:text.index(c)].rstrip()
        except ValueError:
            continue

    raise ValueError("No descriptor found in `%s'" % (text))

E.g.,
>>> get_descriptor('a descriptor dps 23 fd')
'a descriptor'

Answer: codes = ('12', 'dps', '23')

def get_descriptor(text):
    words = text.split()
    for c in codes:
        if c in words:
            i = words.index(c)
            return " ".join(words[:i])
    raise ValueError("No code found in `%s'" % (text))

Answer: I'd probably use a regular expression to do this:
>>> import re
>>> descriptors = ('foo x', 'foo y', 'bar $', 'baz', 'bat')
>>> data = ['foo x 123', 'foo y 123', 'bar $123', 'baz 123', 'bat 123', 'nothing']
>>> p = re.compile("(" + "|".join(map(re.escape, descriptors)) + ")")
>>> for s in data:
        m = re.match(p, s)
        if m: print m.groups()[0]
foo x
foo y
bar $
baz
bat

It wasn't entirely clear to me whether you want what you're extracting to include text that precedes the descriptors, or if you expect each line of text to start with a descriptor; the above deals with the latter.  For the former, just change the pattern slightly to make it capture all characters before the first occurrence of a descriptor:
>>> p = re.compile("(.*(" + "|".join(map(re.escape, descriptors)) + "))")

Answer: Here's an answer that works for all codes rather than forcing you to call the function for each code, and is a bit simpler than some of the answers above. It also works for all of your examples.
strings = ('a descriptor dps 23 fd', 'another 23 fd', 'and another fd',
                  'and one without a code')
codes = ('dps', '23', 'fd')

def strip(s):
    try:
        return s[:min(s.find(c) for c in codes if c in s)]
    except ValueError:
        return s

print map(strip, strings)

Output:
['a descriptor ', 'another ', 'and another ', 'and one without a code']

I believe this satisfies all of your criteria.
Edit: I realized quickly you could remove the try catch if you don't like expecting the exception:
def strip(s):
    if not any(c in s for c in codes):
        return s
    return s[:min(s.find(c) for c in codes if c in s)]

Answer:     def crop_string(string, pattern):
        del_items = []
        for indx, val in enumerate(pattern):
            a = string.split(val, 1)
            del_items.append(a[indx])

        for del_item in del_items:
            string = string.replace(del_item, "")
        return string

example:
I want to crop the string and get only the array out of it..
strin = "crop the array [1,2,3,4,5]
pattern["[","]"]

usage:
a = crop_string(strin ,pattern )
print a

# --- Prints "[1,2,3,4,5]"

Slice a string after a certain phrase?


Linear combination of two linearly independent sets

Question:
Let $\beta = \{ e_1, e_2, ..., e_n\}$ be a basis of the vector space $(\Bbb R, V, +)$. Is $ \alpha = \{ e_1 - e_2, e_2 - e_3, ..., e_{n-1} - e_n, e_n - e_1\}$ a linearly independent set?

I think the answer is yes and here's my argument
We can always take the basis $\beta$ and reorder its elements to get $\beta' = \{e_2, e_3, ..., e_n, e_1\}$. Given that both $\beta$ and $\beta'$ are linearly independent we get
$$k_1e_1 + \dots + k_n e_n = 0, \qquad k_1' e_2 + \dots + k_n' e_1 = 0 \Rightarrow (k_1-k_n')e_1 + \dots + (k_n-k_{n-1})e_n = 0$$
Given that $k_1 = k'_n$ and so on, $ \alpha = \{ e_1 - e_2, e_2 - e_3, ..., e_{n-1} - e_n, e_n - e_1\}$ is linearly independent.
Do you agree? :)
Answer: No.
$$1 \cdot (e_1 - e_2) + 1 \cdot (e_2 - e_3) + \cdots + 1 \cdot (e_n - e_1) = \mathbf{0}.$$


access a project link on ubuntu machine without port number

Question: I have a project running on ubuntu (installed on vm machine(ipaddress-172.22.240.54) on server ), jboss server port 8180
I need to access that link via  http://172.22.240.54/employeeConnect/rest(without mentioning port number)
What changes are required in httpd file and server.xml file?
Answer: You will need to add the following to your httpd.conf
ProxyPass /employeeConnect/rest http://localhost:8180/employeeConnect/rest
ProxyPassReverse /employeeConnect/rest http://localhost:8180/employeeConnect/rest


Show $f(z)=\int_{c} \frac{g(w)}{w-z}$ $dw$ is analytic on any domain $D$ not containing points of $C$

Question:
I know how to show that $f(z)$ is continuous but I'm stuck at showing that $f(z)$ is analytic.
$f(z)$ is continuous:
$$|f(z)-f(a)|=\left|\int_{c} \frac{g(w)}{w-z}-\frac{g(w)}{w-a} dw\right|=\left|\int_{c} \frac{g(w)(z-a)}{(w-z)(w-a)}dw\right|$$
By ML-Formula:
$$\left|\int_{c} \frac{g(w)(z-a)}{(w-z)(w-a)}dw\right|\leq L(C)M|z-a|$$
where $L(c)$ is the length of the curve and M is bound of $\frac{g(w)}{(w-z)(w-a)}$ over the curve $C$ which exists since it is continuous on $C$.
Hence, we can let $\delta = \dfrac{\epsilon}{L(C)(M+1)}$
Any hints or solutions as to show $f(z)$ is analytic?
Answer: One way to do this would be to use Morera's theorem: https://en.wikipedia.org/wiki/Morera%27s_theorem
Since proving analyticity is local we can assume that $D = B(0,R)$  for some $R > 0$.
Let $\gamma: [0,1] \rightarrow D$, then
$\int_{\gamma}\int_{C}\frac{f(z)}{w-z}\,dw\,dz = \int_{C}g(w)\int_{\gamma}\frac{1}{w-z}\,dz\,dw = 0 $, since the inner integral is $0$.
Answer: Define
$$f_1(z)=\int_C\frac{g(w)\,dz}{(w-z)^2}.$$
This is what $f'(z)$ "ought" to be. Now prove that
$$\frac{f(z)-f(a)}{z-a}-f_1(a)\to0\tag{*}$$
as $z\to a$. One can write the LHS of $(*)$ as an integral, and
it should not be too hard to get an estimate on the integrand sufficient
to prove $(*)$.
Indeed
$$\frac{f(z)-f(a)}{z-a}-f_1(a)
=\int_C g(w)\left(\frac{a-z}{(w-z)^2(w-a)}\right)\,dw$$
etc.


Find the absolute maximum and minimum of $f(x) = \left|\cos^2(x) - \frac{3}{4}\right|$ on $[0,\pi]$

Question:
Find the absolute maximum and minimum of $f(x) = \left|\cos^2(x) - \frac{3}{4}\right|$ on $[0,\pi]$

I have learnt that in order to find the absolute maximum, I need to check the value of the function at the:

sides of $[0,\pi ]$
in points that the function isn't differentiable.
in points that satisfy $f'(x)=0$

 How do I approach this question? I have no idea how to differentiate it with the absolute value, and how could I find the points that aren't differentiable in $[0,\pi ]$.  any help is appreciated.
Comment: $\cos^2 x \le \frac{3}{4} \iff -\frac{\sqrt3}{2}\le \cos x\le \frac{\sqrt3}{2}$.
Comment: What is the range of $\cos^2 x$ on $[0,\pi]$?
Comment: Thanks for the help! I missed up on that, now I can write my function as 2 parts:  $x\le \frac {\pi } {6} $ and $ \frac {\pi } {6} <x \le \pi $, right?
Comment: $\cos^2x $ is a number between $0$ and $1$ inclusive, so $\cos^2x-\frac 34$ is a number between $-\frac 34$ and $\frac 14$. Taking the absolute value changes the range to $[0,\frac 34]$.
Answer: Well, I will give you some (big) hints:

Notice that when $x\in\left[0,\frac{\pi}{6}\right]$ we have $\left|\cos^2\left(x\right)-\frac{3}{4}\right|=\cos^2\left(x\right)-\frac{3}{4}$;
Notice that when $x\in\left[\frac{\pi}{6},\frac{5\pi}{6}\right]$ we have $\left|\cos^2\left(x\right)-\frac{3}{4}\right|=\frac{3}{4}-\cos^2\left(x\right)$;
Notice that when $x\in\left[\frac{5\pi}{6},\pi\right]$ we have $\left|\cos^2\left(x\right)-\frac{3}{4}\right|=\cos^2\left(x\right)-\frac{3}{4}$;
Notice that:

$$\cos^2\left(x\right)=\frac{1+\cos\left(2x\right)}{2}\tag1$$

Notice that:

$$\frac{\text{d}}{\text{d}x}\left(\cos^2\left(x\right)-\frac{3}{4}\right)=\frac{1}{2}\cdot\left\{\frac{\text{d}}{\text{d}x}\left(1\right)+\frac{\text{d}}{\text{d}x}\left(\cos\left(2x\right)\right)\right\}-\frac{3}{4}\cdot\frac{\text{d}}{\text{d}x}\left(1\right)=$$
$$\frac{1}{2}\cdot\left\{0+\frac{\text{d}}{\text{d}x}\left(\cos\left(2x\right)\right)\right\}-\frac{3}{4}\cdot0=-\frac{1}{2}\cdot\sin\left(2x\right)\cdot\frac{\text{d}}{\text{d}x}\left(2x\right)=$$
$$-\frac{1}{2}\cdot\sin\left(2x\right)\cdot2\cdot\frac{\text{d}}{\text{d}x}\left(x\right)=-\frac{1}{2}\cdot\sin\left(2x\right)\cdot2\cdot1=-\sin\left(2x\right)\tag2$$

Notice that, likewise $(2)$ only with a flipped sign:

$$\frac{\text{d}}{\text{d}x}\left(\frac{3}{4}-\cos^2\left(x\right)\right)=\sin\left(2x\right)\tag3$$
Comment: Thanks! This really clears it, but I got one question about the 3rd line where you said when $x\in [0, \frac {5\pi } {6} ]$ , is it a typo and you meant $x\in [\frac {5\pi } {6} , \pi ]$?
Comment: @Pwaol you're right, I fixed it. I am glad that I could help you.


RNN functionality and outputs

Question: This is a very basic question about the functionality of RNN / LSTM. My question is about the RNN outputs. Is there a single output for only the last element in the sequence, or is there an output for every element of the sequence?
Answer: There is an output for every node, referred as hidden state in vanilla RNN (LSTM nodes has 2 outputs). In certain cases you only care about the output of the last node so you just avoid previous ones. But each hidden state is still used: Hidden states of the nodes transfered to subsequent nodes thus they are used to construct hidden state (output) of the last node in the sequence.

RNN functionality and outputs


Use a managed file in a menu_item

Question: Is there a way to create a menu that links to a managed file? I tried many times, but nothing I tried works.
Do you have any idea?
Comment: Managed file is new to me but looks interesting. Is this what you're referencing? http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#managed_file ?
Answer: If you enter the full path of the file, it should work but if you're looking to create the menu with a relative path, see https://stackoverflow.com/questions/4335700/drupal-primary-link-item-to-a-relative-file-on-the-server or How can I add relative path to a pdf file link in drupal menu
Comment: Webfm doesn't have a version for drupal 7, is there any similar solution for Drupal 7?

Use a managed file in a menu_item


How many distinct four-letter words beginning with A can be formed from letters with two similar letters and two different letters?

Question:
Four-letter words are made from letters A, A, D, E, E, M, S, Y such that two letters are similar & another two are different & each word begins with letter 'A'. The total number of such words  will be
a) $\ 60 \quad $  b) $\ 80\quad $  c) $\ 100\quad $  d) $\ 120$

My try:
Distinct letters: A, D, E, M, S, Y
Since each word begins with 'A' hence word structure will be
$\  \boxed{A} \boxed{X}\boxed{X}\boxed{X}$
If we take another 'A' then rest three places can be filled by total
$=3\times 5\times 4$
$=60$
If we take two 'E' then rest three places can be filled by total
$=3\times3 \times 4$
$=36$
Total number of required words of four letters
$=60+36$
$=96$
but there is no option for $96$. My answer is wrong. My teacher says that option (d) 120 is correct answer. But I don't know how. Somebody please help me solve this problem. Thanks
Comment: As I say, the phrasing is very unclear.  I get $72$ but that's using my interpretation of the question (and I probably have it wrong).  That said, I don't see a way to get to $120$ (but perhaps I lack imagination).  I'd ask for clarification on the question.
Comment: Note:  I can't follow your second case computation.  If the first letter is $A$ and there are two $E's$ then we have $3$ ways to place the two $E's$ and $4$ ways to fill the empty slot.  That's $12$.
Comment: The phrasing is unclear.  Does it mean that there is one duplicate, say $A,A$ and the other two are distinct?  So...$AAEM$ would work but $AAEE$ would not?  Or does it mean something else?  We could reverse engineer the question from the official answer, but that's not a good way to do things.
Comment: @lulu: Yes , AAEM.. will work but not AAEE.  If second case gives 12, I can't  still get 120.
Comment: @lulu: I have edited the question for clarification
Answer:
If we take two 'E' then rest three places can be filled by total
  =3×3×4
  =36

(take two E)(another one Q other than A)(choose a position for Q) so
$$(1)\cdot({|\{D,M,S,Y\}| \choose 1})\cdot({3\choose1})=4\cdot3=12.$$
Why you get 36?


Spreading row indices into columns in R

Question: I have a data frame in R in the following format:
> old.dat
       id type minDate maxDat eventNum
1    001    A     may   june        1
2    002    B     apr    oct        1
3    002    C     may    nov        2
4    002    B    july    dec        3

I want to turn rows into columns, based on eventNum.  The max eventNum is 3, so if some IDs only have 1 eventNum, I want them filled with NA.
Goal:
      id type1 minDate1 maxDat1 eventNum1 type2 minDate2 maxDat2 eventNum2 type3 minDate3 maxDat3 eventNum3
1    001     A      may    june         1  <NA>     <NA>    <NA>        NA  <NA>     <NA>    <NA>        NA
2    002     B      apr     oct         1     C      may     nov         2     B     july     dec         3

Here is a code chunk to bring in the starting point.
old.dat <- data.frame(id = c("001","002","002","002"),
                      type = c("A","B","C","B"),
                      minDate = c("may","apr","may","july"),
                      maxDat = c("june", "oct", "nov", "dec"),
                      eventNum = c(1,1,2,3))

I wrote a for loop, but its rather slow, and its taking a long time to churn through my data set, so any faster suggestions would be great.  Thanks!
Comment: Your goal is pretty much the worst format I can imagine ... Anyway, both data.table and reshape2/tidyr offer functions for reshaping. Try them out.
Answer: Why? I don't know if I can imagine a situation in which that format will be useful, but here is an approach using tidyr.
First, I am saving a list of the new column names to make things easier to pull together:
newCols <- c("type", "minDate", "MaxDat")

(I will be adding the numbers below).
Then, I am uniteing the values you want for each event, spreading the results to get a new column for each eventNum, then separateing the results back into separate columns (and appending the number of the event to it)
old.dat %>%
  unite(toSpread, type, minDate, maxDat, sep = "::") %>%
  spread(eventNum, toSpread) %>%
  separate(`1`, paste0(newCols, "_1"), sep = "::") %>%
  separate(`2`, paste0(newCols, "_2"), sep = "::") %>%
  separate(`3`, paste0(newCols, "_3"), sep = "::")

Returns:
   id type_1 minDate_1 MaxDat_1 type_2 minDate_2 MaxDat_2 type_3 minDate_3 MaxDat_3
1 001      A       may     june   <NA>      <NA>     <NA>   <NA>      <NA>     <NA>
2 002      B       apr      oct      C       may      nov      B      july      dec

Here is an alternative approach that converts the data to a long format first (with gather), then generates the new column names and does the spreading. The complicated mutate line assigning factor levels to the new columns is only needed to sort the columns and uses parse_number from readr to extract the event numbers. If you are OK with the output columns being sorted alphabetically, you can skip that step. This approach is robust to additional event numbers, as it will automatically add events for each unique value in eventNum.
old.dat %>%
  gather(Metric, Value, type, minDate, maxDat) %>%
  unite(newColHead, Metric, eventNum) %>%
  mutate(newColHead = factor(newColHead
                             , levels =
                               unique(newColHead) %>%
                               {.[order(parse_number(.))]}
                               )) %>%
  spread(newColHead, Value)

For this use case, the output is identical to the above.
(And, if you want evidence for why this may be better; note my edit -- I originally mislabeled event numbers 2/3.)
Comment: Thank you for your help! I realize the format is far from optimal but it was required for circumstances out of my control.

Spreading row indices into columns in R


stationarity of vector autoregression and Gibbs sampling

Question: I'm estimating a vector autoregression (VAR) using Gibbs sampling. At each iteration, I'd like to check the coefficients to ensure the VAR is stationary. An older, related question has been posted here, but no solutions have been suggested.
Is a Gibbs sample from a posterior biased if a draw is redrawn and it doesn't yield a stationary VAR? Is there another method to overcoming draws that lead to nonstationary VARs?
Answer: You have to impose the constraints inside the prior. This means proposals that do not meet the constraints are rejected but it does not produce a biased output. And it leaves you free to pick whatever proposal distribution you wish without imposing the stationarity constraint on the proposal. This means in practice

start with a value of the parameters within the constrained zone
at each Gibbs move, check whether or not the constraints hold:
if not, keep the current value of the parameter and move to another component Gibbs move;
if so, accept the new Gibbs value and move to another component Gibbs move

This remains valid when you replace Gibbs with a Metropolis-within-Gibbs proposal/move. On the other hand, if you use Gibbs and only Gibbs for every component of the parameter vector, then simulating one given Gibbs proposal until the constraints hold is also valid. It may just be fairly time-consuming if those constraints are unlikely at this conditional stage.
Comment: Regarding "On the other hand, if you use Gibbs and only Gibbs for every component of the parameter vector, then simulating one give Gibbs proposal until the constraints hold is also valid." Why only in this case? Does this mean that if the algorithm is not purely a set of Gibbs blocks, you'd have to keep the previous set of parameters rather than trying until successful?
Comment: Thank you for your response. Could you please elaborate a little more? I think I understand what you mean.
Answer: I had posted that older question. I only noticed the issue because so many papers use an analytic Bayesian approach. The analytic formula was often more likely to be stationary than the simulated set of parameters I was dealing with.
In retrospect, it's a hard problem that I shouldn't have expected an answer from on the site. Gary Koop has some papers that you might find informative and can check out the references therein.
I don't much use Gibbs sampling these days. Regardless, here are probably the things I would focus on

Fit the Bayesian VAR with stationary data. This means that there
won't be any coefficients near one and it is a little easier to
think about setting priors tightly near zero.
A corollary of 1 is to use a VECM structure when dealing with cointegration, rather than a regression in levels. Again, keeping the coefficients near zero is helpful for thinking about priors.
Reduce the dimension. I don't mean throw out
some variables. But if you have a large VAR, you can instead convert it to an factor-augmented VAR with PCA and only do the VAR on the smaller subset. This will reduce the computational load.
Use something like a Minnesota prior on the
coefficients

I'm using Stan more recently, though I haven't fit VARs in it. I would probably use some of the above tricks. Stan would probably do a good job with considering the correlation among the parameters. Really, Stan was created to deal with hierarchical parameters, where the problem is correlations between them. For a given parameter, I would expect the coefficients on its own lags to have stronger correlation than the coefficient of the other variables. Nevertheless, anytime I think of something like rejecting non-stationary sets of parameters I just imagine that it would be incredibly slow.


How to look for following problem in Ring theory?

Question: Let $R$ be an integral domain such that every non zero prime ideal is maximal in $R[x]$. Choose the correct statement.
a) $R$ is a Field.
b) $R$ contains $\mathbb Z$ as a subring
c) $R$ contains $F_p$ as a subring for some prime $p$
Now I think c) is false clearly because taking $R$ as $\mathbb Q$  then c is out.  But do not know further how to look for others?
Answer: Indeed a is the correct choice. If $R$ is not a field, then it contains a nonzero proper ideal $I$.  $I+(x)$ is then a proper ideal of $R[x]$, while $(x)$ is a prime ideal properly contained in $I+(x)$.


What does this mean $\mu\{x:\bigcap_\limits{k\geqslant 1}^{}\bigcup_\limits{n}^{}\bigcap_\limits{l\geqslant n}^{}{|f_l-f|}\leqslant \frac{1}{k}\}$

Question: I am studying the following theorem: Consider $E\in\mathscr{F}$(sigma-algebra), and $E\in\Omega$ defined on a measure space $(\Omega,\mathscr{F},\mu)$. Suppose $\mu(E)<\infty$, and $\{f_n\}$ is a sequence of measurable functions on $E\to\mathbb{R}$ which are finite almost everywhere and converge almost everywhere to a function $f:E\to\mathbb{R}$ which is also finite almost everywhere. Then $f_n\to f$ almost uniformly in $E$.
The proof starts with the following: $\epsilon$>0
What does this mean? How do I read this intersection and union signs in this case? Thanks!$\mu\{x:\bigcap_\limits{k\geqslant 1}^{}\bigcup_\limits{n}^{}\bigcap_\limits{l\geqslant n}^{}{|f_l-f|}\leqslant \frac{1}{k}\}$
Comment: Intersections correspond to $\forall$ and unions correspond to $\exists$. So you can simply read as $$ \textstyle \Big\{ x : \bigcap_k \bigcup_n \bigcap_{l \geq n} |f_l(x) - f(x)| \leq \frac{1}{k} \Big\} = \{ x : \forall k,  \exists n, \forall l \geq n, |f_l(x) - f(x)| \leq \frac{1}{k} \}. $$ Since $\Bbb{R}$ is first countable, this is equivalent to the following more friendly expression $$ \textstyle \Big\{ x : \bigcap_k \bigcup_n \bigcap_{l \geq n} |f_l(x) - f(x)| \leq \frac{1}{k} \Big\} = \{x : f_n (x) \text{ converges to } f(x) \}. $$
Comment: That "x:" is not standard notation, nor using "cup" for "$\exists$" or "cap" for "$\forall$." The standard notation would be $\mu\{\bigcap_\limits{k\geqslant 1}^{}\bigcup_\limits{n}^{}\bigcap_\limits{l\geqslant n}^{}{(|f_l-f|}\leqslant \frac{1}{k})\}$.   As @SangchulLee explains, this is the $\mu$ measure of the set where $f_n\to f$ (pointwise).
Comment: Also, in your statement you wrote "E\in\Omega", it should be $E\subseteq\Omega$.
Comment: @VictorZurkowski Do not forget that $\mu$ compromises the measure of $(\Omega,\mathscr{F})$ and the dominion of the function is $E$ and $x\in E$ that is why you write the $x$ as Sangchul Lee did.
Comment: Right. Then the notation I have seen is $\mu\{\bigcap_\limits{k\geqslant 1}^{}\bigcup_\limits{n}^{}\bigcap_\limits{l\geqslant n}^{}{E(|f_l-f|}\leqslant \frac{1}{k})\}$
Comment: On Introduction to measure and integration by Taylor, it was written as Sangchul Lee did with the x. I may be mistaken but it makes sense to me.
Answer: Define $E(k,l) = \{x \in \Omega: |f_l(x) -f(x)| \le \frac{1}{k}\}$.
This is a well-defined measurable set in $(\Omega,\mathscr{F})$ whenever all $f_n$ and also $f$ are measurable.
Then reformulate $f_n(x) \rightarrow f(x)$ for a certain $x \in \Omega$. The statement of pointwise convergence at $x$ means by definition:
$$\forall \varepsilon > 0: \exists n \in \mathbb{N} \forall l \ge n: |f_l - f(x)| < \varepsilon$$
WE cna uee $\le$ instead of $<$ as well,and as the values of $\frac{1}{k}$ get as small as we like we can replace the $\forall \varepsilon>0$ by $\forall k$ and $\varepsilon$ by $\frac{1}{k}$, to make everything countable (Which is what you want in measure theory). So $f_n(x) \rightarrow f(x)$ means for some $x$:
$$\forall k \in \mathbb{N} :\exists n \in \mathbb{N}: \forall l \ge n: |f_l(x) -f(x)| \le \frac{1}{k}$$
We can write that last statement using the definition of $E(k,l)$ as:
$$\forall k \in \mathbb{N} :\exists n \in \mathbb{N}: \forall l \ge n: x \in E(k,l)$$
And as we have sets now, we can also reformulate as intersections and unions, so $f_n(x) \rightarrow f(x)$ iff (indices implicitly over $\mathbb{N}$):
$$x \in \bigcap_{k} \bigcup_{n} \bigcap_{l \ge n} E(k,l)$$
which is a measurable set $P = P((f_n, f))$ say (it depends only on the sequence and its pointwise limit a.e.),as all $E(k,l)$ are, which is the whole point of writing it like this. So saying that $f_n$ converges to $f$ almost everywhere on $E$, means that the complement of $P$ in $\Omega$ has measure $0$, which seems to be used in the remainder of the proof, I'm guessing. It implies that $\mu(P \cap E) = \mu(E)$.
Your notation of the set sort of confuses the quantor definition with the operations write-up in terms of unions and intersections.
Comment: @PedroGomes I think we know that $\mu(E\cap P) = \mu(E)$. Almost all points of $E$ are points of pointwise convergence, i.e. are in $P$.
Comment: Thank you a lot for your replies, you have been very helpful. There is something I do not quite understand in your last equation $\forall \varepsilon > 0: \mu(E \cap P) \ge (1-\varepsilon)\mu(E)$, On this equation you are implying that $\mu(P)\geqslant\epsilon\mu (E)$. How can this be if the $\epsilon$ is defined on function codomain?
Comment: What is the interpretation of $\forall \varepsilon > 0: \mu(E \cap P) \ge (1-\varepsilon)\mu(E)
$? Where did it come from?


Why does an imperfect cadence not include IV-I?

Question: I am learning that an imperfect cadence only involves inverted chords with the V-I. Why is IV not included? Should an 'imperfect' plagal cadence be avoided?
Answer: This is by definition. The terms perfect and imperfect are defined specifically with regard to authentic (V-I) cadences. This is due to the exceptionally common nature of authentic cadences in a variety of different forms, each of which has a different musical effect.
Plagal cadences don't commonly occur in so large a variety of forms, so they are not given similar subcategories.
However, if we extend the "perfect" and "imperfect" definitions to include plagal cadences, then imperfect would actually be the norm. In a perfect authentic cadence, the final chord includes the tonic in the top voice. However, in a plagal cadence, scale degree 5 is very frequently in the top voice.
Plagal cadences tend to be in root position — that is, the lowest voice moves from 4 to 1 — but the top-most voice can have any of the pitches of the final tonic chord. Plagal cadences in which the IV and/or I chords are inverted are uncommon.
Answer: There are different terms used - depending which side of the Atlantic you are. On the right, there are basically four cadences, whereas on the left, some of those are split again, regarding which inversion/voicing is used.
On the right, 'perfect' is one term. On the left, 'Authentic' is used instead, which then gets split into at least 'perfect authentic' and imperfect authentic'. This causes confusion (at least to me...).


The process of using taylor series to evaluate limits.

Question: For instance we want evaluate this simple limit using taylor series :
$$L=\lim_{x\to 0}\frac{\sin x}{x^5}=\lim_{x\to 0}\frac{x-\frac{x^3}{3!}+\frac{x^5}{5!}-\frac{x^7}{7!}+\frac{x^9}{9!}+\cdots}{x^5}$$
In this case we only care about coefficient of $x^5$ to cancel out $x^5$s in  the fraction and get $L=\frac{1}{5!}$. This is a simple example of what we usually do when evaluating limit using taylor series.
My question is why we ignore other terms of the numerator? I mean:
$$L=\lim_{x\to0}\color{red}{\frac{1}{x^4}-(\frac{1}{3!}\times\frac{1}{x^2})}+\color{green}{\frac{1}{5!}}\color{red}{-(\frac{1}{7!}\times x^2)+(\frac{1}{9!}\times x^4)+\cdots}$$
I don't understand why we can ignore other terms (showed in red color) and confirm $\frac1{5!}$ as the answer. It is obvious that terms appeared on the rightside of $\color{green}{\frac1{5!}}$ are equal to zero but what about other side?
Comment: Here limit is infinite.
Comment: the limit is not $\frac1{5!}$
Comment: We can't ignore $\frac 1{x^4},\frac 1{x^3 }$ here.
Comment: @PNDas  the limit is equal to $\frac1{5!}$ so we ignored all the term except green one.
Comment: Sorry. I choosed a bad example. I meant in general when we use taylor series we consider only coefficient of same terms in denominator and numerator and cancel them out. for example here: https://math.stackexchange.com/questions/3881372/evaluating-lim-x-to-0-frac-cos-sin-x-1x2-frac-12x4/3881393?noredirect=1#comment8004826_3881393 we only considered coefficient of $x^4$
Comment: Oh. I understood it now. I thought in both case we have $x^n$ in denominator and also remain some $x^{n-k}$  on numerator. Now I understood.
Answer: We can't ignore the other terms, we obtain indeed
$$\frac{x-\frac{x^3}{3!}+\frac{x^5}{5!}-\frac{x^7}{7!}+\frac{x^9}{9!}+\cdots}{x^5}=\frac1{x^4}-\frac1{3!x^2}+\frac1{5!}+O(x^2) \to \infty$$
the limit is finite for
$$\lim_{x\to 0}\frac{\sin x-\left(x-\frac{x^3}{3!}\right)}{x^5}=\lim_{x\to 0}\frac{\frac{x^5}{5!}-\frac{x^7}{7!}+\frac{x^9}{9!}+O(x^{11})}{x^5}=\frac1{5!}$$
Comment: @JyrkiLahtonen Sorry but I can't really understand what is your point here. This is a perfectly fine question and my answer do not prevent for other answers to be given and posted by any other user. I'll be happy to read them and in case upvote the good ones according to my preference and I'm sure that also the asker will be happy with that. Recall that we should focus our attention on the content, not the person.
Comment: Actually, $\frac1 {x^4} - \frac 1{6x^2}$ is in $\infty - \infty$ form. You have to modify it first.
Comment: Yes but  by the standard way $$\frac1 {x^4} - \frac 1{6x^2}=\frac1{x^4}\left(1 - \frac {x^2}{6}\right) \to \infty$$ that is $1/x^4$ tends to \infty faster than all other terms.
Comment: You have alread answered hundreds (if not thousands) of questions about limits using Taylor series. I think it is high time you let those who have less rep show what they can. Did you even search for duplicates this time either. It is your duty as a trusted user.
Comment: [This old thread](https://math.meta.stackexchange.com/q/7178/11619) in meta. The discussion was revitalized [here](https://math.meta.stackexchange.com/q/28376/11619) and more recently [here](https://math.meta.stackexchange.com/q/32665/11619). Don't worry. I will not be targeting you. I just downvote all the high rep users when they post something that they know has already been posted.
Answer: The limit is not $\frac{1}{5!}$, in fact the limit does not exist (or, you could say the limit is $+\infty$). You need to take the limit of each individual term. Notice that the first 2 terms diverge at $x=0$ after you divide by $x^5$.
In short, you can't just blindly ignore the other terms. That only works if all the other terms go to $0$.
Comment: It is not sufficient to show that all other terms go to zero, because there can be an infinite number of them...
Answer: Others have pointed out that the limit does not really exist... But, addressing the general question, it is probably easier to understand (and more correct) if you use Taylor's polynomial instead of taylor's series. Imagine you want to compute a limit that actually exists, like the well known $\lim_{x \to 0}\dfrac{\sin x}{x}$, using Taylor's formula. You know that
$$
\sin x = x - \frac{\cos (\xi_x)}{3!} x^3, \quad \xi_x \in (0,x)
$$
and so,
$$
\lim_{x \to 0} \frac{\sin x}{x} = \lim_{x\to 0}\dfrac{x - \dfrac{\cos (\xi_x)}{3!} x^3}{x} = 1-\frac 16 \underbrace{\lim_{x \to 0}\cos(\xi_x)x^2}_{=0} = 1
$$


Adding files to an application c#

Question: I have some files and I want that files to be copied to a folder in temporary folder when running my application. My application is written in c#. How can I add these files to my application so that when I run my app these files will get copied to temporary folder?
I have tried by adding the files as Resources, but still I have to keep those files manually. Is there any way to embed the files in my application so that when I run it will get copied to temporary folder?
Thanks
Comment: Could this be done by adding the files to the project and setting their "Copy to output directory" as "Copy Always"?
Comment: Typically, this is done by using an **installer** that installs your application and also any support files it needs.
Comment: Right click on Application folder of setup and click on add and file. whenever you install your app these file will be copied in default location of your app.
Answer: Indeed, there is.
If you right click 'properties' for the files in question, you'll see that you can change the "build action", set this to "content" and then set "copy if newer". They will then be placed in output folder, in the same structure of folders that they are in, in the solution.
Answer: There is no way to embed files in your .exe so that they will be automatically copied when the exe is run. (You can set properties in the solution explorer so that they are copied when the exe is compiled as @noon silk has suggested. Similarly you can use an installer to install an application along with some files, but again they are not copied when the application is run, only when it is installed).
To embed files in an exe so they are copied out when it runs, you can do this:

add the file to your project in the solution explorer using Add Existing Item. As you add them, on the file open dialog, click the little down arrow at the right end of the Add button, and choose the Add as Link option. Instead of copying the current file into your project (so you have to manually update it each time it changes) this will just reference your original file, and copy the latest version into your app each time it is compiled.
get properties on the added file in solution explorer and set the type to Embedded resource
add code to your app to write the file to disk. use Assembly.ExecutingAssembly().GetManifestResourceStream() to read the data into a byte array, and then save that data to disk in the location of your choice by writing the array to a FileStream.

For example:
Stream dataStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyApp.SomeFolder.DataFile.dat");
byte[] fileData = new byte[dataStream.Length];
dataStream.Read(fileData, 0, (int) dataStream.Length);

using (FileStream outStream = new FileStream(@"C:\Temp\RealFileOnDisk.dat", FileMode.Create))
    outStream.Write(fileData, 0, fileData.Length);

Adding files to an application c#


MVC 3 & JQuery - ajaxStop or ajaxComplete not firing

Question: It would appear that ajaxStart in my MVC 3 project is working but not ajaxStop or ajaxComplete.  The problem is not browser specific as I've tested this in IE9, Mozilla and Chrome.
My project is just taking a series of letters and finding the combinations/permutations and displaying them to the user.  The ajax function is initiated, the ajaxStart is fired and the "please wait" indicator appears.  When the ajax call is complete (I would assume) the table is populated but the ajaxStop/ajaxComplete is never fired and the "please wait" indicator never goes away.
Here's the javascript I use:
$(document).ready(function () {
    $(document).ajaxStart(function () {
        $('#ajaxBackground').show();
        $('#ajaxProgress').show();
    });

    $(document).ajaxStop(function () {
        $('#ajaxBackground').hide();
        $('#ajaxProgress').hide();
    });

    $('#submit').click(function () {
        var p = $('#prefix').val();
        var l = $('#letters').val();
        var s = $('#suffix').val();

        $.ajax({
            url: '@Url.Action("Search", "Home")',
            type: 'POST',
            dataType: 'json',
            data: { prefix: p, letters: l, suffix: s },
            success: function (jsonresults) {
                $('#searchResults').find('tr').remove().end();
                for (var i = 0; i <= jsonresults.length; i++) {
                    $('#searchResults').append('
' + jsonresults[i].word + '	' + jsonresults[i].length + '	' + jsonresults[i].score + '
');
                }
            },
            error: function () {
                alert('error');
            }
        });
    });
});

Is there something I missed.  Any help would be greatly appreciated.  Thanks.
Comment: have you checked the firebug for any errors
Comment: That's very bizarre.  I tested almost exactly your code and the ajaxStart and ajaxStop callbacks are properly being called.
Answer: Normally this should work. I suspect that your #submit is either a form submit button or an anchor. You have subscribed to the click event of this element which is where you fire the AJAX request. But you do not cancel the default action of this element because you didn't return false at the end of your function. So your AJAX request is trigerred and then the browser is redirected away and doesn't have time to finish the processing of this AJAX request.
So try returning false just after the $.ajax function.
Comment: I have similar issue - but there is no postback as mentioned here - http://stackoverflow.com/questions/25745682/jquery-ajax-stop-is-not-invoked-no-error-200-ok


URL Rewriting, Temporary Solution, ASP.Net 3.5

Question: We've got a test site hosted only by IP address.  We really need to test some functionality that depends on what subdomain someone is using to get to the site.  But of course we can't even USE subdomains with an IP only site.
So, one thought I had was that instead of subdomains, we could have the testers open the site with a URL like this:  http://192.168.0.1/smith or http://192.168.0.1/jones and I would then redirect them to http://192.168.0.1/default.aspx?site=smith etc...
Our testers are at the client, and asking them to enter in the querystring would be problematic.  Plus, I'd really like to get a quick intro into URL Rewriting.
Can anyone give me any idea if what I want to do is possible, and if so, a pointer to some code or explanation or something?
We are using asp.net 3.5 and iis6, I believe.
Thanks for any help!
Answer: I wrote up an introduction to URL Rewriting in ASP.NET on my blog, for what its worth. Feel free to post more questions here to clarify any specific issues you have.
Answer: you could possibly change the hosts file on the testing machine to point domains (and subdomains) at that IP, that way you wouldnt have to rely on DNS and could test as if the domains were assigned.
more information here:
http://labnol.blogspot.com/2004/10/tweak-your-windows-hosts-file.html
Comment: Great answer, but won't work in our situation.  Testing machines aren't known to us -- there are close to 100 of them lined up, all across the US and trying to get them all to update their hosts file would really really irritate our client.  Again, great idea.
Comment: :)  Good testers are worth their weight in gold.
Answer: this will definitly work in your situation
http://www.urlrewriting.net/149/en/home.html
we have implemented same what you required is, its open source dll and you need to write some rules in web.config, according to your scanario, your rule something like
<code><add name="index" virtualUrl="^~/(.*)/Default.aspx" rewriteUrlParameter="ExcludeFromClientQueryString" destinationUrl="~/Default.aspx?site=$1&urw=t" ignoreCase="true"/>
</code>
Answer:
Using ASP.NET Routing Without
ASP.NET MVC
Using ASP.NET
Routing Independent of MVC

this is part of .Net 3.5 and is the
  same mechanism used by MVC

This makes your life easy, due to the fact that everything is held in the HttpContext.CurrentContext.Items[""]
I have adapted this code for a few project where I have an XML configuration file. I then use this file to build the RouteCollection. This code has also been easily extended to handle 301 redirects for SEO.
This method is also loaded once in your AppPool and removes the need to parse xml files and configurations for every call. This so far has been the best solution for me performance wise.
If you need any assistance please let me know. I will gladly lend a hand.
Edit : 13/09/09
I have not run into that problem yet since I usually handle the membership / authentication  verification in every page. I usually have a control or method I call on the page to validate/ authorize a user. My clients rarely use the ASP.Net membership, they usually rely on proprietary sub systems which we need to connect to.
I have extended the examples provided in the above links so that I can write one xml routing table which gets loaded when the application starts up or when I force a RouteCollection update.
so far this has proven itself to work pretty well.
this can also allow for a change in routes while the application is running, with no down time.
Comment: Your example works great, but when I plug it into my solution, it doesn't ever hit my MSO object.  I believe this is due to ASPNet Membership Services.  All requests, if not logged in yet, rediret to login.aspx.  I think this handler gets run before mine, so I don't have a chance to deal with it.

Any suggestions?  Otherwise, I love your method.  Pretty cool.


Shellscript action if two files are different

Question: I am importing a file to my server using this command:
scp zumodo@shold:/test/test/test/server.py /test/test/test/test.py~/;

I want to restart my server if the newly imported file test.py~ differs from the test.py that already exists. How would I do this using a shellscript?
Comment: I hope you mean "restart my daemon" not "restart my server"
Comment: You probably don't want the final '/;' on that command, because it's not a directory and you don't have another command on the same line.
Comment: @peter do you mean if a load of files is different to one file and check each one? in your comment on my answer below.
Answer: if ! cmp -s test.py test.py~
then
  # restart service
fi

Breaking that down:

cmp -s test.py test.py~ returns true (0) if test.py and test.py~ are identical, else false (1).  You can see this in man cmp. The -s options makes cmp silent, so it doesn't give any output (except errors), but only an exit code.
! inverts that result, so the if statement translates to "if test.py and test.py~ are different".

ps: If you are not sure the 2nd file exists, you may want check that too. (cmp still works in this case, but gives an error message, suppressing error message may be enough too (cmp ... 2>/dev/null)
Comment: You could also use `cmp -s` to suppress terminal output of the comparison.
Comment: This will be correct even if the file/files do not exists.
Comment: @PolyBug: Yes, it is, but it's the convention in Unix/Linux.  The reason is that there's only one type of success, but there can be many types of failure, which can return different status codes.  See for example the Exit Status sections of `man ls` or `man grep`.
Comment: +1, but -q is non-standard.  Redirect to /dev/null will always work.
Comment: Sorry, could someone explain the first line for a bash noob? What is the precedance for the argument of the if operator? Why are there those two redirects and what do they mean?
Comment: @AndrewSchulman: Thanks, I used in a script. If I understand this, the Boolean output and the stdout are both sent to the if, so to just have the boolean answer, you have to send the stdout to the bit bucket.
Comment: `if` always uses just the exit status (0/1) of the command. stdout will go to the terminal, so the redirects just make that be quiet.
Comment: Why does bash's if treat a return (0) as true, and (1) as false?  Isn't that counter-intuitive to conventional boolean logic?
Answer: You could diff() the two files.  A return code of zero (0) means there are no differences.  A return code of one (1) says the files differ.
Comment: Why use diff when `cmp` is built for this?
Comment: This is exactly what I want to do. Again I am a novice, do you think you provide me an example or a link to an example?
Comment: @peter see my answer for example/link.
Answer: diff <path_to_file_1> <path_to_file_2> && echo "files are same"
Answer: I'd do something like
zumodo@shold$ cat /test/test/test/server.py | ssh zumodo@otherhost 'cat - > /test/test/test/test.py.new ; cmp /test/test/test/test.py /test/test/test/test.py.new || (mv /test/test/test/test.py.new /test/test/test/test.py ; echo issue restart command here)'


Attempting to show $P(|S_n| <1)$ for a martingale $(S_n)$

Question:
Now, I am stuck on the last part of the question. I managed to find the solutions, but I don't udnerstand them completely.

What I don't understand is: How they got that indicator function, and why they are using double expectation to calculate the probability. I'd appreciate it if someone coudl help out, thanks.
Comment: The solution you found somewhere seems more complicated than necessary. Note that the build-up questions show that $S_n\in\{a(S_{n-1}),b(S_{n-1})\}$ almost surely for two deterministic functions $a$ and $b$ such that $a_n(x)\cdot b_n(x)=-1$ and $a_n(x)\ne\pm1\ne b_n(x)$ for every $x\ne0$. Thus, $|a(S_{n-1})|<1<|b(S_{n-1})|$ (or the other way round) and the proof is complete since $P(S_n=a(S_{n-1}))=P(S_n=b(S_{n-1}))=\frac12$.
Comment: Note that $a(x),b(x)=x\pm\sqrt{1+x^2}$ hence $[S_n=a(S_{n-1}]=[X_n=+1]$ or $[S_n=a(S_{n-1}]=[X_n=-1]$, depending on the choice of $a$ and $b$.
Comment: @Did how did you get $P(S_n = a(S_{n-1}) = 1/2$?
Answer: First, we can show the function $f:\mathbb{R}\to \mathbb{R}$ given by $f(x)=\sqrt{1+x^2}$ is such that:

$\forall x,f(x)\geq 1$. Also $f(x)=1\iff x=0$.
$x< 0 \implies 0<x+f(x)<1$. Similarly $x>0\implies -1<x-f(x)<0$

Second, to prove
$$
1_{\{|S_n|<1\}}=\frac{-X_nsign(S_{n-1})+1}{2}
$$
note this:
\begin{eqnarray}
\frac{-X_nsign(S_{n-1})+1}{2} =1 & \iff & -X_nsign(S_{n-1})=1\\
& \iff & (X_n=-1\:\wedge\:S_{n-1}>0)\vee(X_n=1\:\wedge\:S_{n-1}<0)\\
& \implies & |S_n|<1
\end{eqnarray}
(the last line is consequence of the second property of $f(x)$ previously mentioned). On the other hand
\begin{eqnarray}
\frac{-X_nsign(S_{n-1})+1}{2} =0 & \iff & -X_nsign(S_{n-1})=-1\\
& \iff & (X_n=-1\:\wedge\:S_{n-1}<0)\vee(X_n=1\:\wedge\:S_{n-1}>0)\\
& \implies & |S_n|>1
\end{eqnarray}
(the last line is consequence of the first property of $f(x)$ previously mentioned).
Third, by the previous point
$$
\mathbb{P}[|S_n|<1]=\mathbb{E}[1_{\{|S_n|<1\}}]=\mathbb{E}[(-X_nsign(S_{n-1})+1)/2]
$$
in other words, computing the desired probability is the same as computing
$
\mathbb{E}[(-X_nsign(S_{n-1})+1)/2]
$. Computing this directly looks pretty tedius (you'd need to compute the distribution of $X_nsign(S_{n-1})$, etc). Luckily, using the Law of total expectation, the conditional expectation
$$
Y_{n-1}:=\mathbb{E}[(-X_nsign(S_{n-1})+1)/2|\mathcal{F}_{n-1}]
$$
verifies:
$$
\mathbb{E}[(-X_nsign(S_{n-1})+1)/2]=\mathbb{E}[\mathbb{E}[(-X_nsign(S_{n-1})+1)/2|\mathcal{F}_{n-1}]=\mathbb{E}[Y_{n-1}]
$$
Hence
$$
\mathbb{P}[|S_n|<1]=\mathbb{E}[\mathbb{E}[(-X_nsign(S_{n-1})+1)/2|\mathcal{F}_{n-1}]
$$
and since $S_{n-1}\in \mathcal{F}_{n-1}$ and $X_n$ is independent of $\mathcal{F}_{n-1}=\sigma(X_1,...,X_{n-1})$, by properties of conditional expectation we deduce
$$
Y_{n-1}=\mathbb{E}[(-X_nsign(S_{n-1})+1)/2|\mathcal{F}_{n-1}]=\frac{\mathbb{E}[X_n]sign(S_{n-1})+1}{2}=\frac{1}{2}
$$
hence
$$
\mathbb{E}[(-X_nsign(S_{n-1})+1)/2]=\mathbb{E}[Y_{n-1}]=1/2
$$
Comment: Thank you for this answer, I am still fairly stumped as to why the double expectation gives you the probability required, could you elaborate on that please?
Comment: @lampj20la You are welcome. Yes. I've decided to modify the answer to show that the probability equals the double expectation, rather than answering as a comment, as it would be a rather lengthy comment.


The equation $a^2 - 4b = 3$ has no integer solution

Question:
Prove that: $$a^2 - 4b \neq 3$$ for all integers $a$ and $b$.

I'm not sure how to find a way to prove this statement. Some help would be appreciated.
Comment: Hint: Consider the possibilities for $a\pmod 4$.
Comment: Do you have any ideas?
Comment: What have you tried?  What must be true for a and b such that the statement is true?   Try finding a contradiction.
Comment: You could use a graph
Comment: @ajax333221: $a^2$ is not always even. Eg:$9$
Answer: Assume that it is true. So $a^2-4b=3$.
Case I :When $a$ is even. Then $a=2k$ where $k$ is an integer. Thus we have, $4(k^2-b)=3$. LHS is even and RHS is odd. Contradiction.
CaseII: When $a$ is odd. Then $a=2k+1$ where $k$ is an integer. Then, $(2k+1)^2-4b=3$, hence we have $2(k^2+k-b)=1$. Again LHS even, RHS odd. Contradiction.
Comment: $a$ cannot be even. $a^2$ is 3+4b which is always odd, and if $a^2$ is odd, then a must be as well.
Answer: Take $\mod4$
LHS $\equiv 0,1 \pmod 4$ but RHS $\equiv 3$
So no solutions


Java Swing - JButtons on New Line

Question: I am trying to print out a dynamically generated list of buttons with each button on a new line.
public void addComponentToPane(Container pane) {
    JTabbedPane tabbedPane = new JTabbedPane();

    //Create the "cards".
    JPanel card1 = new JPanel() {

 JPanel card1 = new JPanel()
 ...

int n = 10;
JButton[] jButtons = new JButton[10];
for(int i=0; i<n; i++){
   jButtons[i] = new JButton("test" + i);
   card1.add(jButtons[i]);
   //card1.add("
");//<--this is wrong; but hopefully you get my point.
   jButtons[i].addActionListener(this);
}

Answer: Put them into a box:
Box card1 = Box.createVerticalBox();

or, if you want all the buttons to have the same size, use GridLayout with one column:
JPanel card1 = new JPanel(new GridLayout(n, 1))

Answer: Here are two solutions using a constrained GridLayout and a BoxLayout

I prefer the GridLayout (on the left) since it normalizes the width of the buttons and makes it easy to add a small space between them.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class DynamicButtons {

    public static void main(String[] args) {
        final JPanel gui = new JPanel(new BorderLayout());

        final JPanel gridButton = new JPanel(new GridLayout(0,1,2,2));
        gridButton.add(new JButton("Button 1"));
        JPanel gridConstrain = new JPanel(new BorderLayout());
        gridConstrain.add(gridButton, BorderLayout.NORTH);

        final Box boxButton = Box.createVerticalBox();
        boxButton.add(new JButton("Button 1"));

        JButton b = new JButton("Add Button");
        b.addActionListener( new ActionListener() {
            int count = 2;
            public void actionPerformed(ActionEvent ae) {
                gridButton.add(new JButton("Button " + count));

                boxButton.add(new JButton("Button " + count));

                count++;
                gui.revalidate();
            }
        });

        gui.add(b, BorderLayout.NORTH);
        JSplitPane sp = new JSplitPane(
            JSplitPane.HORIZONTAL_SPLIT,
            new JScrollPane(gridConstrain),
            new JScrollPane(boxButton));
        gui.add(sp, BorderLayout.CENTER);

        gui.setPreferredSize(new Dimension(250,150));

        JOptionPane.showMessageDialog(null, gui);
    }
}

Answer: Use GridBagLayout and set GridBagConstaints.gridy field.
Comment: GridBagLayout is outdated and too complicated,  I'd advice not to use it in new projects.
Comment: GridBagLayout is maybe outdated, but is more powerfull / clear/ non_buggy than other Custom LayoutManagers +1
Comment: @user3663882 good point, but (if is compared to the MigLayout, TableLayout) GBC and SpringLayout (better alternative, easier and more intuitive) can't works with empty space correctly, (e.g resize of container generating for example situations when is required to divide 10/3, result is empty space in one pixel), in most cases is required to override getPrefferedSize, but answer is upvoted by me, because GUI can be correctly diplayed with little effort
Comment: @mKorbel BTW why is it considered outdated? Should we really avoid using it in current swing projects? If so, what's an alternative... ?
Answer: I suppose you need something like this :

For this you require a Box Layout , see this for more details :  How to Use BoxLayout
and if needed here is a demo : Java Tutorials Code Sample – BoxLayoutDemo.java

Java Swing - JButtons on New Line


How to combine typedef'd struct with instance creation?

Question: So you can do this to create c1 and c2 as instances of struct Complex:
struct Complex {
    int real;
    int imag;
} c1, c2;

And you can do this to typedef the anonymous struct:
typedef struct { ... } Complex;

But is there any way to do both at once?
Comment: Why would you want to do it? is it because `c1` and `c2` are global variables?
Comment: I'm not sure why...I guess I'm just exploring the limits of the syntax right now so I understand what's possible.
Comment: Well if this was possible, it would be certainly useless, at least it's my point of view, and it might of course be wrong.
Answer: No, you can't. typedef's syntax is
typedef T type_ident;  // T is type specified by the declaration specifiers

This means that anything after typedef T will be a type name, not the instance of that type. So, in
typedef struct { ... } Complex, c1, c2;

Complex, c1 and c2 are all typedef name with the type struct { ... }.
Answer: The standard (PDF) says it's impossible, cause typedef is just one of the type specifiers. It's as if you had written char int a;.
Answer: Storage-class specifiers (typedef, static, extern etc) always apply to the whole declaration. In the same way that one declaration cannot declare static and non-static variables, a typedef declaration can only define type definitions:
static int foo, bar; // Both foo and bar are static
typedef int c1, c2; // Both c1 and c2 are typedefs

Answer: The first form declares a structure tag; the second declares a typedef. The main difference is that the second declaration is of a slightly more abstract type,if users don't necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it...& Structures declared with tags, on the other hand, must be defined..So its not possible create c1 and c2 as instances of struct Complex....


Prove: if x^n = x, then prove that x + x = 0 for additive identity 0.

Question: Suppose $n$ is a positive integer.
Under a ring, suppose for any $x$, $x^n = x$. Then for any $x$, $x + x = 0$ for additive identity $0$.
How is this proven?
The case when $n$ is even is rather easy:
$x^n = (-x)^n$ so $x = -x$
However I am not able to find a proof for a general $n$.
Comment: Is it true? I think $\mathbb{Z} / 5\mathbb{Z}$ with $n=5$ is a counterexample.
Comment: @DirkLiebhold What's incomplete about the proof for even $n$?
Comment: Other counterexamples would include $n = 1$ or $\mathbb{Z}/p\mathbb{Z}$ and $n = p$ for every odd prime $p$. So I don't see how this would ever be considered true, unless of course if $n$ is even (note that in this case, you still need another proof, yours is not yet complete).
Comment: @Adayah On second thought, nothing. I read it wrong the first time, so it is ok as it is, sorry.
Answer: The statement is false. The In $\mathbb Z_3$, you have $2^3=2$ and $2+2=1\neq 0$.
Comment: But in your example $n=3$, right?
Comment: @Adayah oh yeah, right.
Comment: Thank you, I was scratching my head trying to prove it for a couple of minutes there.


Is the integral $\int_{[0, 1]} a^{-(b-x)} \ d\nu(x)$ small independently of the measure $\nu$?

Question: Let $\nu$ be a positive measure, $b>1$ and let $M\gg 0$ be fixed. Assume $a\ge M$. As part of a more challenging exercise, I am trying to evaluate the integral
$$\int_{[0, 1]} a^{-(b-x)} \ d\nu(x).$$
Better saying, I would simply say that this integral is small.
This conclusion seems true to me if, e.g., $\nu$ is the Lebesgue measure. In fact,
$$\int_{[0, 1]} a^{-(b-x)} dx =\frac{a^{-(b-x)}{\log(a)}\Big_{[0, 1]}.$$
My questions are:

Is that integral small, independently of the measure $\nu$?

If yes, how to prove that?

$\bf{EDIT:}$ Avoiding "drastic" examples like the ones exhibited (rightly) by Sudix in the comments, what about a measure whose support is contained in a compact?
Comment: The measure $\nu(A)=\infty$ for $A\neq \emptyset$ and $\nu(\emptyset)=0$ is one counter-example. The same can be achieved by 'scaling up' the lebesgue-measure, i.e. setting $\nu(A):=c\cdot \lambda(A)$ and letting $c\to\infty$
Comment: @Sudix, thanks.
Answer: If $x>0$, then $b-x<b$ and $-(b-x)>-b$ and $a^{-(b-x)} < a^{-b}$.  So
$$
\int_{[0,1]} a^{-(b-x)}\;d\nu(x) \le a^{-b} \nu\left([0,1]\right)
$$
with equality when $\nu$ is supported on $\{0\}$.  Then we get estimate $M^{-b} \nu\left([0,1]\right)$ as long as $a \ge M$.


Class-validator: remove a property on validation, based on the value of another property

Question: Using class-validator with NestJS, I have this working:
export class MatchDeclineReason {
  @IsString()
  @IsEnum(MatchDeclineReasonType)
  @ApiProperty()
  type: MatchDeclineReasonType;

  @ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
  @IsString()
  @ApiProperty()
  freeText: string;
}

so that if the delinceReason.type === Other, I expect to get a freeText string value.

However, if the declineReason.type is any different from Other, I want the freeText property to be stripped away.
Is there any way to achieve this kind of behaviour without writing a CustomValidator?
My ValidationPipe configuration:
  app.useGlobalPipes(
    new ValidationPipe({
      disableErrorMessages: false,
      whitelist: true,
      transform: true,
    }),
  );

Answer: It can be achieved by using a custom logic for value transformation:
  @ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
  @Transform((params) =>
    (params.obj.type === MatchDeclineReasonType.Other ? params.value : undefined)
  )
  @IsString()
  @ApiProperty()
  freeText: string;


Multiplying specific character with index value in string

Question: def word(s1,s2):

   index = 0
   while index < len(s1):
       if s2 in range(len(s1)):
           s1[index] = s1[index] * index
       index = index +1
   return s1

print(word("aratehadb", "a"))

I want the code to return "raatehaaaaaadb"
meaning I want it to multiply the chosen letter with the index its found at, I have tried
res = [i for i in range(len(s1)) if s1.startswith(s2, i)] to find the positions that the letters are at but I'm stuck at how I multiply with the index
Answer: Use enumerate
You can use enumerate to obtain the index of each value, determine if the letter matches what you want to multiply and do the multiplication if required.
def word(s1, s2):
    return ''.join([l*i if l == s2 else l for i, l in enumerate(s1)])

print(word("aratehadb", "a"))
# raatehaaaaaadb

Closer from your first implementation
def word(s1, s2):
    index = 0
    # string can't be mutated (changed) so we need to create
    # a list to change each character string and make it bigger
    # if needed
    l_s1 = list(s1)
    while index < len(s1):
        if s2 == s1[index]:
            # Here you can replace s1 with l_s1, we access the same string anyway.
            # Also, l_s1[index] *= index also works
            l_s1[index] = s1[index] * index
        index = index + 1
    return ''.join(l_s1)

print(word("aratehadb", "a"))
# raatehaaaaaadb

str.join() documentation
Comment: Thank you so much! so to do this I have to create a list from my string, and then multiply and add all the items, and then return the joined list. im going to read up om this join function , but thank you for the answer.
OMG I forgot strings cant be mutated....


Making a confusing sheet with 3 voices and triplets non-ambiguous

Question: Context
I've transcribed the Title Screen song from Pokémon Red/Blue/Yellow for classical guitar and I am now polishing the sheet.
Here are measures 15 and 16 of the direct transcription of the original song, which has 3 melody channels (voices) and a noise channel for percussion effects (which I omitted). Note the coloring of each voice on the left side of this image:

And here are the same measures in the guitar sheet, where I mixed (as best as possible) the 3 voices of the direct transcription into a single guitar sheet (remember that guitar is a transposing instrument which plays one octave below what's represented on the sheet):

This guitar sheet may seem confusing (which is the point of this question), so here's the same image but with additional text notes and colors to highlight each voice and the duration of the confusing musical notes (voice 1 is blue, voice 2 is green and voice 3 is red):

In my opinion, on measure 16, the three voices are such that it is very hard to create a non-ambiguous guitar sheet. Despite my best efforts, this was the best that I managed to do. I see four points that might cause confusion to readers on the guitar sheet:

Note 1: This piece is not meant for sight reading. Instead, it is meant to be thoroughly rehearsed before performing, as it is very tricky to read without the tab (and to play). I want to print two versions of the score: one with tab and the other without, so the sheet alone must be readable by itself.
Note 2: This score is being produced with Guitar Pro 8.
Note 3: In the answers, please ignore the confusing notation in the pictures for artificial harmonics, where both the harmonic pitch and the note pressed with the left hand are notated in the sheet. This notation is forced by Guitar Pro 8, I cannot do anything about it (as far as I know).
Questions
I have 5 questions: 4 of them for each one of the 4 points identified in red in the last image and a 5th one asking for a better alternative for measure 16 of the guitar sheet (if there is any). Please provide a point-wise answer, if possible:

Is the duration of every note in here clear (that C is a quarter note and the others are triplet quarter notes)? Also, note that the G from voice 1 (blue) is pointing down here.

Voice 1 is now pointing up instead of down like in the previous note (point 1). Is it clear that this is not a quarter note, but actually a triplet quarter note affected by the |--3--| notation below? In other words, is it clear that the G pointing up in point 1 is not affected by the triplet, but the F (also pointing up) in point 2 is?

Is the duration of each of the notes here clear? I'd say voice 3 (red) (the bottom note) is clear, but what about the other two?

Here, the stem of the quarter note E in voice 2 (green) is pointing up because if I pointed it down, its stem would blend with the stem of the eighth note F from voice 3 (red) below it, and then the E would seem like an eighth note as well. Is it clear that the E is a quarter note and not a triplet quarter note (affected by the |---3---| notation abouve it)?

What is a better solution to represent measure 16 of the guitar sheet in a legible, non-confusing and non-ambiguous way? I don't necessarily require answers taking Guitar Pro 8 into account (although it would be appreciated of course), because I am even finding it hard to imagine how measure 16 could look non-ambiguous on paper or in a better music notation software.
Comment: Consider that a single part of a single, monophonic instrument can still represent more than one voice. In particular, the octave+ jumps are suspicious! Besides that, consider if you really want to _transcribe_ the piece literally for academic correctness, or rather _arrange_ it for artistic effect.
Comment: As I understand the terms, "part" refers to what a single instrument plays. "Voice" refers to a coherent melody. Bach's violon solo suites often use "compound melody"; a single part plays two (or more) voices. Sometimes alternate notes belong to different melodies. The fugue in the famous d-minor pieces alternates melodic notes with a dominate pedal (hinting that fugue subject was originally composed for violin.)
Comment: @user1079505 Could you clarify to me the difference between _part_ and _voice_ please?
Comment: @user1079505 Also, I believe you are referring to the voice 1 (in blue) on the first half of measure 16. In these GameBoy songs (and other retro videogame consoles'), the composers typically had just 3 single-pitch MIDI channels and one noise channel for percussion effects. This was a typical hardware limitation of the consoles' sound chips. So sometimes we see things like voice 1 in this song, where they use the otherwise empty (with pauses) parts of the sheet and use that MIDI channel to fill up or complement the harmony. Nowadays, it would likely be written in an auxiliary sheet and voice.
Answer: TL;DR

Step by step solution
Following the standards laid out in Behind Bars, here is the process I went through.1
Step 1: MuseScore defaults for 3-voice entry

There is plenty of awkwardness here: quarter notes and dotted quarter notes sharing a stem (allowed, but awkward), overlapping stems (e.g. m. 16 beat 2), and overlapping ties (m. 16). It also make it seem that in m. 16 beat 1, the voice 3 F is part of voice 1's triplet.
Step 2: Down stems for lowest voice
This is not made explicit in Behind Bars, but is consistent throughout the examples.

This resolves some of the stem/slur crossing, but also creates the same problems in new places, such as the unclear stems in m. 15 beat 2.5. It also make m. 16, beat 3, voice 2 look like an eighth note rather than a quarter note.
Step 3: Adjust stems in middle voice
This step resolves various collisions. For example, in m. 15 beat 1, the dotted quarter notes in voices 1 and 2 are now combined, as with the following eighth notes and half notes. The stemming in m. 16 beats 1 and 2 is clarified, and voice 2's beat 2.5–3 tied eighth-note and quarter note, although the usual way to write is, is now combined into a single dotted quarter note, which is sufficiently clear, because the other voices clarify the beats and beat divisions.

An obvious problem, though, is that the voice crossing in m. 16 beats 1 and 2 is totally unclear, such that the voice leading is lost.
Step 4: Final adjustments

The main adjustment here is giving more space to m. 16 so that the individual beats are better clarified. Voice leading lines are also added to show where voice 1 crosses voice 2. In m. 15, I made voice 1 and 2's initial dotted quarter notes into tied quarter and eighth note to help the eye follow all three voices. I also adjusted some stem directions and lengths and note offsets for visual clarity.
Given that this is intended for study, so sight readability is somewhat secondary, this is the solution I find easiest to follow.

1 Gould, Elaine. Behind Bars (Faber Music, 2011). See especially pp. 310 – 313, "Keyboard: Part Writing." The guitar notation section does not address part writing.
Comment: @GandalfTheBard The down beat of m. 16 is a little strange looking, but I think clear enough once the performer has time to study the score. You could certainly cojoin the F with the triplet G, but then there should be an eighth rest for that voice in the triplet so that it remains clear which voice is which.
Comment: What a great answer! Thank you so much for the time you spent writing it so cleanly! I just have one point I'd like to debate: are the first three notes on the start of measure 16 of your solution unambiguous? There might be people who think they are not meant to be played at the same time.
Comment: (follow-up of my previous comment): The first F of measure 16 can a triplet quarter note, because the next F later on will be on the same guitar string and fret, and as such would stop the F quarter note from ringing through its entire duration.
Answer: First, a frame challenge: Why does the reader need to know the precise duration of every single note? Are they muting each note at the end of its duration? Are you muting each note when you play it? Play the piece yourself, simplifying where necessary, and match the notation to what you're actually doing; this will make it much more practical for someone else to follow, sight reading or not.
Second, ties are a tool to clarify rhythms. As a rule, any note value crossing a subdivision longer than itself (quarter across the half-measure, eighth across the beat, etc.) should be broken up across that subdivision. Your original three-staff version follows this rule, and I'm not sure why you made things harder by changing it.
Then, to answer your questions in rapidfire:

Yes, this is clear.
I think that would just be confusing. The triplet now looks like it goes with voice 3, which looks like an orphaned triplet-quarter.
Nope, not clear at all. I'd have to squint for a bit before I saw the top one as anything but a dotted eighth.
This is as clear as it can be in my opinion, especially with the upper voice in octaves. Others may disagree.
Here's a basis to build from, which happens to preserve your exact durations:

But again, don't take my word for it; play it through and try to reflect what you're actually doing and thinking.
You'll note that voices 1 and 3 adhere to my second point, but I've preserved the dotted quarter in voice 2 for a few reasons: One, the common 'tresillo' rhythm (dotted x, dotted x, x) is often given a pass due to its simplicity. Two, there's nowhere for a quarter stem to go in beat 3. And three, it makes voice 2 stand out visually, helping the stray quarter amidst the triplets make sense.
Three voices is a lot for one staff! There are good notational and cognitive reasons to pare it down to two distinct rhythms when possible. The good news is that a guitar is more like a percussion instrument than a violin, and, in extreme cases, you can just do this (EXAGGERATED FOR COMEDY; PLEASE DO NOT):
Comment: Also, thank you very much for this great and helpful answer! I decided to change this answer as the accepted one because it gives very meaningful advice for transcribing/arranging multi-voice songs such as this for guitar. However, for everyone else reading this, I highly recommend checking @Aaron's great answer, as it produced a clean sheet preserving even all of the original song's notes' durations. The guitar sheet trims down the first F of voice 3 to a triplet quarter note, which makes things a lot easier to notate in sheet.
Comment: Those are very good points. Usually I use the same original durations for the notes in the guitar. I reduce the duration of a note when it is impossible to play the entire duration and I never extend them beyond the original duration on the sheet, even that ends up happening because of the left hand shape. I just didn't reach that part of the arranging/transcription process for this particular sheet yet. Also, I am guilty of having used notation such as that last image back when I used Guitar Pro 5 and didn't know about multi-voice sheets. Good times! (but terrible sheets)


How to display error message and stop macro

Question: I'm a novice at coding VBA. I want to add a pop up box with the message "Today's date not found" and stop the macro if today's date is not found in column K. Not sure how to go about this and where the code should be.
<code>' Find the last row on the count sheet and the next row on the archieve sheet

lastRow = countSheet.Cells(countSheet.Rows.count, "K").End(xlUp).Row
nextRow = archieveSheet.Cells(countSheet.Rows.count, "K").End(xlUp).Row + 1

' Look at all rows in the count sheet
For thisRow = 1 To lastRow

    ' Check if column K contains today's date
    If countSheet.Cells(thisRow, "K").Value = Date Then

        ' Copy the entire row to the archieve sheet
        countSheet.Cells(thisRow, "K").EntireRow.Copy Destination:=archieveSheet.Cells(nextRow, "A")

        ' Move to the next row on the archieve sheet
        nextRow = nextRow + 1
    End If
Next thisRow
</code>
Answer: Adding some simple code at the beginning would keep everything simple
<code>If Application.WorksheetFunction.CountIf(countsheet.Range("K:K"), Date) = 0 Then
    MsgBox "Today's Date Not Found"
    Exit Sub
End If
</code>
Comment: This! Guard clauses FTW! Fail early, bail out fast - reduces nesting and keeps the "happy path" focused on doing its thing. :+1:
Comment: i am now getting an error: Object variable or block variable not set
Comment: @JamieB on which line?
Answer: Something like this should work for you:
<code>'Create a new boolean variable for keeping track of if the date has been found
Dim bDateFound As Boolean

'Set that boolean to false to begin with (this step is optional, it will be False by default if not defined)
bDateFound = False
lastRow = countSheet.Cells(countSheet.Rows.Count, "K").End(xlUp).Row
nextRow = archieveSheet.Cells(countSheet.Rows.Count, "K").End(xlUp).Row + 1

' Look at all rows in the count sheet
For thisRow = 1 To lastRow

    ' Check if column K contains today's date
    If countSheet.Cells(thisRow, "K").Value = Date Then
        'Add line here because a date was found to set your boolean variable to true
        bDateFound = True

        ' Copy the entire row to the archieve sheet
        countSheet.Cells(thisRow, "K").EntireRow.Copy Destination:=archieveSheet.Cells(nextRow, "A")

        ' Move to the next row on the archieve sheet
        nextRow = nextRow + 1
    End If
Next thisRow

'After your loop, put in a check to see if the date was found
If bDateFound = False Then
    'If the boolean is still false, then it was never found
    'Display a msgbox containing your error
    MsgBox "Today's date not found. Exiting macro.", , "Error"
    Exit Sub    'Exit the macro
End If

'If the date was found, then the code will continue here
</code>
Comment: @JamieB see the other alternative answer for that.


Mean of covariance matrices

Question: I'm trying to generalise a formula that takes the mean of some variances to it work with vectors.
I'm not sure it makes sense to take the variance between a bunch of vectors, rather it is more suited to generate a covariance matrix.
So, is there a way to take the mean of a bunch of covariance matrices?
Comment: Hi, the way the question is written sounds like you might just want to take the arithmetic mean of the matrices (see my answer). However, I have no idea whether this would produce a reasonable generalization of your formula. You might want to add more information, or perhaps post a separate question like 'How to generalise this formula to vectors/multiple dimensions/whatever'.
Comment: Great thanks for your answer, I will post another question.
Answer: If the original covariance matrices are of the same dimension, i.e., you have $n\times n$-matrices $\Sigma_1,\ldots,\Sigma_N$, you could just take the sample mean:
\begin{equation}
\bar{\Sigma} = \frac{1}{N}\left(\Sigma_1 +\ldots+\Sigma_N \right),
\end{equation}
which corresponds to taking elementwise means of the elements of the covariance matrices, i.e., the $i,j$th element will be
\begin{equation}
\bar{\Sigma}_{i,j} = \frac{\Sigma_{1(i,j)}+\Sigma_{2(i,j)}+\ldots+\Sigma_{N(i,j)}}{N}.
\end{equation}
Provided that the original covariance matrices are valid (positive-semidefinite), this will produce a valid covariance matrix, as positive-semidefiniteness is preserved under summing and multiplying by a positive constant ($1/N$).
Whether taking this mean is reasonable will depend on the context, which is not explained in the question.
Comment: Hey Juho, I've similar problem. I calculate covariance matrix every batch-iterations and I would like to have an estimate, of covariance matrix over several batches. I can't concatenate data, because they come from different time series (but from the same population).

Mean of covariance matrices


Python: how to separate certain number-text combination from string?

Question: for example: a=['Now is 20m before 10h','OK 15s after 6 punctual']. I want time_fragment=['20m','15s'].
I've seen answers that used split function and import re, but didn't see anything to address a number-text combination case. This has a bit text mining involved so the data is messy.
Comment: Split *can* be used to separate individual words, whether they have numbers in them or not.  Until you specify what kind of pattern you are looking for and/or how to identify it, and not just a single example with no explanation, not sure how much help you will get.
Comment: making adjustments to the question
Answer: If you only want the times before the word "before", you can use a lookahead in you regex.
<code>import re
s = 'Now is 20m before 10h'
rgx = re.compile(r'[0-9]+[hms](?= *before)')
print rgx.findall(s) # ['20m']
</code>


About the existence of an isomorphism of algebras between the algebras of $\mathcal{C}^0$ and $\mathcal{C}^1$ functions from $[0, 1]$ to $\mathbb{R}$

Question: Let $\mathcal{C}^0 ( [0, 1], \mathbb{R})$ denote the set of continuous functions from $[0, 1]$ to $\mathbb{R}$ and  $\mathcal{C}^1 ( [0, 1], \mathbb{R})$ denote the set of class $\mathcal{C}^1$ functions from $[0, 1]$ to $\mathbb{R}$, both of these sets are algebras over the field $\mathbb{R}$.
The question is whether we can find an isomorphism of algebras:
$\Phi:\mathcal{C}^0 ( [0, 1], \mathbb{R})\longrightarrow\mathcal{C}^1 ( [0, 1], \mathbb{R})$
it seems, well at least to me, that such a cheesy isomorphism cannot exist, however I couldn't prove it.
I tried the obvious choice, which is proof by contradiction, and tried taking the inverse of such a function which would map differentiable functions to continuous ones, considering that one set already contains the other, however no contradiction seemed to arise.
Comment: I'd consider the maximal ideals of each.
Comment: Maximal ideals of both are $V(x_0) = \{f \in A: f(x_0) = 0\}$, where $x_0$ is some point in $[0, 1]$, and $A$ is either $C^0([0, 1])$ or $C^1([0, 1])$. So, I don't think it helps much.
Answer: No such isomorphism exists.  A quick way to prove it is to observe that every element of $\mathcal{C}^0 ( [0, 1], \mathbb{R})$ has a cube root, but not every element of $\mathcal{C}^1 ( [0, 1], \mathbb{R})$ has a cube root (for instance, the function $f(x)=x$ does not since $x\mapsto \sqrt[3]{x}$ is not differentiable at $0$).


contradiction to characterization of second group cohomology

Question: Let $G$ be a group and $A$ be a $G$-module.
In Ken Brown book Cohomology of Groups, on page 93, $H^2(G,A)$ is characterized as the isomorphism classes of group extensions $ 0 \to A \to * \to G$ giving rise to the action $G \curvearrowright A$.
Now when I take $G=\mathbb{Z}/3$ and $A$ to be the trivial $G$ module $\mathbb{Z}/3$, this characterization says that $|H^2(\mathbb{Z/3},\mathbb{Z/3})|=|\mathbb{Z/3}|=3$ is the number of group extensions $ 0 \to \mathbb{Z/3} \to K \to \mathbb{Z/3} \to 0$.
This cannot be correct because any extension group $K$ must have order 9, therefore be abelian and therefore must be either $\mathbb{Z/3} \oplus \mathbb{Z/3}$ or $\mathbb{Z/9}$.  I claim that these gives rise to only 2 isomorphism classes of extensions:
The only subgroups of $\mathbb{Z/3} \oplus \mathbb{Z/3}$ of order $3$ are the ones generated by $(1,0)$, $(0,1)$, $(1,1)$ and there are automorphisms of this group that permute the generators any way one likes.  Hence there is only one isomorphism class of an extension $ 0 \to \mathbb{Z/3} \to \mathbb{Z/3} \oplus \mathbb{Z/3} \to \mathbb{Z/3} \to 0$.
The only subgroups of order $3$ in $\mathbb{Z/9}$ is the one generated by $3 \in \mathbb{Z/9}$.  Hence there is only one isomorphism class of an extension $ 0 \to \mathbb{Z/3} \to \mathbb{Z/9} \to \mathbb{Z/3} \to 0$.
These are inequivalent because the second extension does not split.
Question:  Where is the third extension that the group cohomology calculation predicts?
Answer: The point is that given two exact sequences of groups $$ 0 \to \mathbb{Z/3} \to K_1 \to \mathbb{Z/3} \to 0$$ and $$0 \to \mathbb{Z/3} \to K_2 \to \mathbb{Z/3} \to 0$$ such that $K_1\simeq K_2$, this does not necessarily imply that the extensions are equivalent in $H^2(\mathbb Z/3\mathbb Z,\mathbb Z/3\mathbb Z)$. What you need is a commutative diagram
\begin{array}{c}
0 & \to & \mathbb Z/3\mathbb Z& \to& K_1 &\to &\mathbb Z/3\mathbb Z \to &0\\
&&\downarrow&&\downarrow&&\downarrow \\
0 & \to & \mathbb Z/3\mathbb Z& \to& K_2& \to &\mathbb Z/3\mathbb Z  &0
\end{array}
such that the middle arrow is an isomorphism and the arrows on the left and right are the identity.
In our particular case of $\mathbb Z/9\mathbb Z$, you have two choices for the map $\mathbb Z_3\hookrightarrow \mathbb Z_9$ either take $x+3\mathbb Z$ to $3x+9\mathbb Z$ or to $6x+9\mathbb  Z $. Notice that they both determine the same subgroup $\{0,3,6\}$ in $\mathbb Z/9\mathbb Z$. Now we want an automorphism of $\mathbb Z/9\mathbb Z$ that restricts to the identity on both copies of $\mathbb Z/3\mathbb Z$ and makes the diagram commute. But we can see that the induced map on the kernel will have to be $ x+3\mathbb Z$ to $2x +3\mathbb Z$ which is not the identity.
This argument generalizes and actually shows that by using the trivial extension and the maps $x+p\mathbb Z \mapsto ix+p^2\mathbb Z$ for $i=1,2,\dots, p-1$, the group $H^2(\mathbb Z/p\mathbb Z,\mathbb Z/p\mathbb Z)$ is at least of size $p$.
Comment: Dear Ravi,
Thanks for this detailed answer.  Aren't the two extensions you mention isomorphic via the isomorphism
$\require{AMScd}$

$\begin{CD} 0 @>>> \mathbb{Z/3} @>i_1>> \mathbb{Z/3}\oplus \mathbb{Z/3} @>>> \mathbb{Z/3}  @>>>0 \\
@| @| @VV\begin{pmatrix} 1 & 0 \\ 1 & 1 \end{pmatrix}V @VV\text{induced cokernel map}V@| \\
0@>>> \mathbb{Z}/3 @>\Delta>> \mathbb{Z}/3 \oplus \mathbb{Z}/3  @>>> \mathbb{Z}/3 @>>>  0
\end{CD}$
 ?

If I am correct, then this still shows that there are only two isomorphism classes of group extensions $0 \to \mathbb{Z/3} \to * \to \mathbb{Z/3} \to 0$.
Comment: So this still doesn't resolve the contradiction between the group cohomology calculation, and what simple calculations like yours show.
Comment: You are absolutely correct. My answer was incorrect. I had to look up the defintion of isomorphic extensions and that is where I missed a detail. I fixed it now and you can see that it is actually $\mathbb Z/9\mathbb Z$ that gives two extension classes.
Comment: Oh yeah,  one more generalization using methods in my question:  The extension group must be an abelian group since it is of order $p^2$ and thus any iso class of group extensions with $\mathbb{Z/p}$ on the ends is an iso class of $\mathbb{Z}$ module extensions.  Hence this group is $Ext_{\mathbb{Z}}(\mathbb{Z}/p,\mathbb{Z}/p)=\mathbb{Z/p}$.  We can also see what all the cohomology groups are from the resolution.  But you have given me what the extensions are explicitly.  Thanks!


Pigeonhole principle subsets

Question:
I don't really know how to solve this problem using the pigeonhole principle. My attempt so far was to show that you can choose 10 possible 3 element subsets and from those you can choose 3 possible 2 element subsets, making for 30 possible options of pigeons that cannot be together? However, this doesn't really make sense to me because there's only 2 holes. Please give me advice on how to start thinking about this problem.
Answer: First question: yes
$$(1, 2), (2, 3), (3, 4), (4, 5), (5, 1)$$
$$(1, 3), (3, 5), (5, 2), (2, 4), (4, 1)$$

Pigeonhole principle subsets


date format from mysql database

Question: I have a column type DATE in mysql database and want to get date in format like this - 21-jan.
$stmt = $db->query('SELECT id, date, title, category FROM posts ORDER BY date DESC');
while($row = $stmt->fetch()){
    $date = strtotime($row['date']);
    $date = date_format($date, "d-M"); // line 49

Warning:
date_format() expects parameter 1 to be DateTimeInterface, integer given... on line 49
Any help ?
Answer: Try to do this:
$date = strtolower(date("d-M", $date));

Take a look at date function:
http://php.net/manual/pt_BR/function.date.php
Comment: It works, but can I have `21-jan` instead of `21-Jan` ?
Answer: Use date function instead of date_format:
$stmt = $db->query('SELECT id, date, title, category FROM posts ORDER BY date DESC');
while($row = $stmt->fetch()){
    $date = date("d-M", strtotime($row['date']));
    $formatedDate = strtolower($date);

Comment: It works, but can I have `21-jan` instead of `21-Jan` ?
Comment: @bonaca unfortunately date() function doesn't do that but you can accomplish it with help of strtolower() function
Comment: Thanks a lot. Solved.

date format from mysql database


"The TensorFlow library was compiled to use FMA instructions, but these aren't available on your machine." in VirtualBox

Question: My tensorflow has been able to run normally in the WIN10 system, and with cuda and cudnn installed, the GPU can be used normally.
I have a whim, I want to open a tf on my own virtual machine Ubuntu, maybe I can try distributed? The result is that after finally installing tensorflow, it cannot run.
When import tensorflow, it will prompt directly
F tensorflow/core/platform/cpu_feature_guard.cc:38] The TensorFlow library was compiled to use FMA instructions, but these aren't available on your machine.
I don't know where the problem is...
Answer: I am experiencing the same problem and just peeped this from another question:
How to install tensorflow GPU version on VirtualBox Ubuntu OS. And host OS is windows 10
In short, you can't access you GPU through VirtualBox. You must do this directly from Windows/whatever machine you have.
Apologies if I didn't quote correctly.
Comment: Thank you for your reply. I have found that GPU cannot be used in VirtualBox because there is no GPU in the listed devices.

Currently, we are using Ubuntu 20.04 and tensorflow 2.4. Theoretically, we should be able to use at least CPU, right? And I did use tensorflow1 in old versions of Ubuntu.


Recognizable vs Decidable

Question: What is difference between "recognizable" and "decidable" in context of Turing machines?
Answer: A language is Recognizable iff there is a Turing Machine which will halt and accept only the strings in that language and for strings not in the language, the TM either rejects, or does not halt at all. Note: there is no requirement that the Turing Machine should halt for strings not in the language.
A language is Decidable iff there is a Turing Machine which will accept strings in the language and reject strings not in the language.
Perhaps this link will be helpful: http://kilby.stanford.edu/~rvg/154/handouts/decidability.html
Comment: I feel its noteworthy to state that "recognizable = recursively enumerable" and "decidable = recursive". Am I wrong?
Comment: @EricLeschinski: I am not sure what you are trying to say. We are talking about Turing machines. Talking about programming languages seems irrelevant.
Comment: If valid words in a language define an infinite loop, that does not make it unrecognizable.  The program is not run to determine its recognizability.   Its property of being recognized means the program containing an infinite loop can be confirmed as a valid program in a finite amount of time and always accepts.  For example, languages like python can validate a program in a finite amount of time even if the program specifies an infinite loop.  Python is recognizable.
Comment: @PardonMeForMySuperPoorMaths: I believe you are right. Feel free to make an edit!
Answer: Disclaimer : I'll elaborate just a little.
When a Turing Machine(TM) is given an input, it can do one of three things :

Accept the input by reaching accept state ($q_{accept}$).
Reject the input by reaching reject state ($q_{reject}$).
Keep computing forever. This can be called a "loop".

If the machine keeps computing forever, we consider that the machine has rejected the string but it does so in an infinite number of steps. Thus, if the machine accepts a string, it must do so in a finite number of steps!
A Language of a Turing Machine is simply the set of all strings that are accepted by the Turing Machine. In this case, we say that the Language is recognized by the Turing Machine. This brings me to the definition of a Turing Recognizable Language :
Def : A Language is called Turing Recognizable if some Turing Machine recognizes it.
Now, consider a Turing Machine $M$ and a language $L$(over input alphabet $\Sigma$) that is recognized by $M$. Thus, $L$ is a Turing Recognizable Language (since the TM $M$ recognizes it). Consider the set of strings that are not in $L$(we call it $\overline{L}$). We know that the machine $M$ does not accept these strings. So, when we simulate a string $w$ $\in$ $\overline{L}$ on $M$, there are two possibilities :

M ends up on reject state ($q_{reject}$).
M keeps computing forever(goes in a "loop").

If the machine $M$ is such that for all $w$ $\in$ $\overline{L}$, it produces the output by going into the reject state, then we have a Turing Machine($M$) for $L$ which has the property that, for any input (over $\Sigma^{*}$) it never goes into a loop! Thus, we can say that for any input (over $\Sigma^{*}$), the Turing Machine $M$ decides whether to accept or reject the input in a finite number of steps. The machine $M$ is called a decider. The languages for which we can design Turing Machines with the above property are called Turing Decidable languages. In the above example, we say that $M$ decides $L$. Here is the definition :
Def : A Language is called Turing Decidable if some Turing Machine decides it.
Keeping it simple - A language $L$ is Turing Decidable if some decider $M$, decides it.
For more information you can refer to : An Introduction to the Theory of Computation by Michael Sipser.
Answer: My answer mostly agrees with Aryabhata's:
A language is "Turing-Recognizable" iff there exists a Turing Machine such that

when encountering a string in that language, the machine terminates and accepts that string;
when encountering a string not in that language, the machine either terminates and rejects that string or doesn't terminate at all.

A language is "Turing-Decidable" iff there exists a Turing Machine such that

when encountering a string in that language, the machine terminates and accepts that string;
when encountering a string not in that language, the machine terminates and rejects that string.

Note that "Turing-Decidable" is a stronger condition than "Turing-Recognizable", because, if a language is Turing-Decidable then its corresponding Turing Machine never runs forever.
Comment: [this](https://www.radford.edu/~nokie/classes/420/Chap3-Langs.html) explains it too but i found your answer most helpful

Recognizable vs Decidable


Basis for $\mathbb{Q}(\alpha, \beta)$ over $\mathbb{Q}$

Question: One can prove that a basis for $\mathbb{Q}(\sqrt{2}, \sqrt{3})$ is the set $\{1, \sqrt{2}, \sqrt{3}, \sqrt{6} \}$.  This got me wondering if the following is true:

Let $\alpha, \beta$ be elements that are (1) not rational and (2) not scalar multiples of each other (where the scalars come from $\mathbb{Q}$).  Then is $\{1, \alpha, \beta, \alpha\beta\}$ a basis for $\mathbb{Q}(\alpha, \beta)$ over $\mathbb{Q}$?

(Note: I said $\alpha, \beta$ are not rational instead of irrational since I am not assuming $\alpha, \beta \in \mathbb{R}$.)
If this is true, can you provide a proof?  And if not, perhaps give a counterexample?
Comment: Consider $\mathbb{Q}(\sqrt{2}, \sqrt[3]{2})$.
Comment: No: $\mathbf Q(\pi,\sqrt 2)$  is not even finite-dimensional.
Comment: @Bernard  This is a good one, thanks.
Answer: (Compiled from the comments and posted as CW in order to mark the question as answered.)
The proposition does not hold true in general. Counterexamples:

finite extension: $\;\mathbb{Q}(\sqrt{2}, \sqrt[3]{2})$
infinite extension: $\;\mathbb{Q}(\pi, \sqrt{2})$


Debugging API calls that use a proxy in package.json

Question: If I'm using a proxy in my package.json, for example, something like this:
"proxy": "https://my-api-url.com"
If I want to see the URL actually being fetched by the fetch API, how can I do so? I'm not sure that this question makes sense, but I'm doing my best -- in Chrome's network tab, I can see that the request url is http://localhost:3000/some/endpoint, but how do I know if the proxy is working correctly?
Apologies if this question doesn't make sense or is unclear.
Answer: I ended up using the following Webpack config, just in case it helps anyone else:
    proxy: {
        "/api": {
            "target": "https://link-to-your-api",
            "secure": false,
            "pathRewrite": {
                "^/api": ""
            },
            "changeOrigin": true,
            "logLevel": "debug"
        }
    }
},

With that config, I was able to make requests using the Fetch API like so:
  const response = await fetch('/api/path1/path2/endpoint/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Cache-Control': 'no-cache'
    },
    body: JSON.stringify(yourRequestBody)
  });


How to prevent user from interacting with web page via extension?

Question: I'm creating an extension that is supposed to show an overlay and highlight the element the cursor is on. When the overlay is visible, the user should not be able to interact with the page (buttons, links etc should not work).
The code:
let overlay = document.createElement("div");
overlay.setAttribute("class", "as-overlay");

let panel = document.createElement("div");
panel.setAttribute("class", "as-root");
panel.setAttribute("id", "as-panel");
overlay.appendChild(panel);
document.body.appendChild(overlay);

____

.as-overlay {
  position: fixed;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom:0px;
  z-index: 99999;
  cursor: default;
  pointer-events: none !important;
  background-color: rgba(0, 0, 0, 0.8);
}

I'm setting pointer-events to none in order to disable interactions. But it isn't working. Am I doing something wrong? (I've ensured the overlay takes full width and height, and it's z-index is high enough so that it renders on top of everything.)
Some help would be appreciated, I've been banging my head on this for quite a while, and a certain large language model was of no help ;-;
Edit: I've added in an example. Ideally, you'd expect clicking on the button or link to not do anything, since the overlay is there. But clicking on them works, I just can't seem to understand why.
Comment: `it isn't working` that's a pity, but not very helpful for debugging.  What does happen?  Is the overlay visible?  Does any of that code execute?  Can you see the overlay element appended to the dom in dev tools?  Ideally, you'll provide us with a runnable example of the problem.
Comment: Yes, the overlay shows up, but I can still interact with the elements on the page, even when the overlay is present. I've added in an example that shows the issue.
Answer: From the description of pointer-events

In addition to indicating that the element is not the target of
pointer events, the value none instructs the pointer event to go
"through" the element and target whatever is "underneath" that element
instead.

All you need to do is remove pointer-events: none and that should fix your problem.  At least it fixes the example you provided.
Comment: Jesus Christ, I'm disappointed I spent so much time figuring out what's wrong when the solution was that easy. Thanks for the help, it's working :)
Answer: For starters, these two have to be switched over because you can't have "panel" placed without the "overlay" being in place. Even if JS allows you to do this, it's pretty illogical and hurts my brain!
overlay.appendChild(panel);
document.body.appendChild(overlay);

But anyway, if you have covered the entire page with a "shroud" then who cares about pointer events? :)
They'll be clicking your shroud so if you haven't added a click event on it... what exactly is the problem?
Comment: I'm confused by your confusion. The OP is appending the `panel` to the `overlay`, then appending the `overlay` to the `body`. Pretty standard operation. It's standard to set up the DOM fragment the way you want it, then append the whole thing to the main DOM. But this answer doesn't seem to answer the question.
Comment: The shroud is meant to be transparent, it has a bg just to check if the overlay is showing up or not. The issue is that even though the overlay is present, and I'm clicking on a link/button below the overlay, the event for the link/button is being triggered, when it shouldn't, because of the pointer-events being set to none
Comment: It's like placing books on a bookshelf that hasn't arrived yet! :)