A problem on simple congruences.

Question: This is a problem on congruences given in the book of Andy Liu, titled "Arithmetical Wonderland".
A Dragon has $100$ heads, and it can only be killed if all its heads are cut off. A Prince has two swords. The long one can cut off exactly $21$ heads of the Dragon at a time. The short one can cut off exactly $4$ heads of the Dragon at a time, but every time this sword is used, the Dragon grows another $1985$ heads. The Prince must be careful not to leave the Dragon with $1, 2$ or $3$ heads, as his swords will be useless then. Can the Prince kill the Dragon?
My attempt:
As $100/21$ should give remainder, which can be minimum $16$.
It means that the short sword need be used too.
The additional condition seems useless unless the linear combination of $21x+4y$ can achieve a value of $99, 98,$ or $97$, for which the second additional condition of growing $1985$ heads on cutting snake by smaller sword should be applicable.
So, framing the equality : $100 = 21x + 4y$, we get solution for $x= 4, y =4$.
But, this framing of equality is wrong, as the $\gcd$ of $21,4=1$, and so it can be only $100=2100x +400y$.
Additional condition of growing $1985$ heads seems difficult to combine with the same equality. How should I frame equations such that the both additional conditions fit together in the same equality, is not clear.
Answer: Each cut with the short sword adds a net of 1981 heads (+1985 -4). Simply take 100+1981y = m. Then use modular arithmetic to determine if m is ever $0 \mod 21$ or $4 \mod 21$. There you can prove or disprove.
Comment: Thanks a lot. Taking the modulus of both sides (as the answer has only taken of the r.h.s.), get: $16 + 7y = m$. So, the value of $y$ should make any multiple of  $\gcd$ of $16, 7y = m$. It seems that I need to take the congruence w.r.t. $21$ again, as sum of $16+7y \mod 21$ should be $m$.  Before, trying out possible values for $y$ in naturals, such that $m=0,$ or $4$; we can see what are the possible residue classes of $16+7y \pmod{21}$, and see that the values we get are: $23(\equiv 2), 9, 16, 2$. This cycle goes on and on, so the prince is unsuccessful.
Answer: \begin{align}
   h_0 &= 100 \\
   h_{i+1} &= h_i + (-21 \ \text{or} \ 1981)
\end{align}
We note that $\gcd(-21,1981)=7$ and $100 = 2 \pmod 7$. It follows that, for all $i$, $h_i = 2 \pmod 7$. It follows that we can never cut off all of the heads of the dragon.
Response to a comment
If the $21$ had been a $29$, then we would get this sequence of head counts
\begin{align}
   h_0 &= 100 \\
   h_{i+1} &= h_i +
      \begin{cases}
         -29   & \text{if 29 heads are cut off.} \\
         1981  & \text{if 4 heads are cut off.} \\
      \end{cases}
\end{align}
The simplest strategy would be to cut off four heads until there are a multiple of 29 heads on the dragon. So we need to solve the congruence equation
\begin{align}
   1981x \equiv -100 \pmod{29} \\
   9x \equiv 16 \pmod{29} \\
   x \equiv 5 \pmod{29}
\end{align}
So we chop off $4$ heads $5$ times in a row. We get $h_0 = 100$ and
$h_5 = 10005 = 345 \cdot 29$. We cut of $29$ heads $345$ times and end up with
$h_{350}=0$
Comment: For the problem as stated either 21 heads get cut off or (-4+1985) heads get added at the end of each "time". So, for this problem, there will always be 7m+2 heads for some integer m.
Comment: @jitender Then you cut off 4 heads until the dragon has a multiple of 29 heads. That will turn out to be 5 times. Then just chop of 29 heads at a time until there are none left (345 times).
Comment: Thanks a lot for this novel approach. I have some confusion regarding the answer: There is a series generated with the next term being defined by the earlier term, among two other mutually exclusive quantities. This approach relies on the residue classes being in the forbidden set of values. But, had the two values were instead: $-29, 1981$, then their $\gcd=1.$ Then, how to pursue this approach is not clear. Please help.
Comment: If I modify the problem, so that the $\gcd=1,$ as done in my first comment to your answer, by choosing $-29$ and $1981$, then your approach seems not to work. I mean that in the new case (created by me), either $29$ heads get cut off or $(-4+1985)$ heads get added at the end of each sword movement.
Comment: Thanks for that. Your modified answer has shown the same approach as your 'earlier' answer, with difference that now $(29,1981)=1$. Hence, $100=0(mod 1)$. So, the last two lines of your 'earlier' answer can be modified for the 'new' case as:" It follows that, for all $i, h_i=100=0 \pmod 1.$ It follows that we can cut off all of the heads of the dragon. " ----Also, my approach is given next. Please vet it : $1981y + 100 \pmod 29 \implies 9y+13 \pmod 29$. The set of residue values are $=13, 22, 2, 11, 20, 0$. So, $5$ times need to use the smaller sword to get success by bigger sword.

A problem on simple congruences.


Exporting All Groups and Group Members from Active Directory

Question: I am relatively new to powershell and am trying to get a list of all groups in the domain with their respective members. Here's what I'm working with now:
Import-Module ActiveDirectory
$OutPutFile = New-Item -type file -force "AllGroups.txt"

#Filters for Groups

# 2 Global distribution group
# 4 Domain local distribution group
# 8 Universal distribution group
# -2147483646 Global security group
# -2147483644 Domain local security group
# -2147483640 Universal security group

$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Domain = [ADSI]"LDAP://$D"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize  = 10000

$Searcher.Filter = "(&(objectCategory=Group)(|(groupType=2)(groupType=4)(groupType=8)))"
$Searcher.SearchRoot = "LDAP://" + $Domain.Name

$Results = $Searcher.FindAll()
foreach ($Result in $Results)
{
    $Item = $Result.Properties

    foreach ($Member in $Item.member)
    {
    $Name = Get-ADUser "$Member" -Properties DisplayName | select -expand displayname
    $Item.cn, "$Name" | Out-File $OutPutFile -encoding ASCII -append
    }
}

I'd like the output to be Group;Displayname or Group-Displayname (so I can put it in Excel and format from there) however I cannot seem to get output in the same line. The output currently comes out like this:
Group
DisplayName
Group
DisplayName

What am I doing wrong or how can I adjust the code to give me the two items on the same line? I was also thinking about adding in the OU the groups are in but haven't had luck finding a way to get that from my results.
Comment: what version of powershell are you using?  Have you looked at `Get-ADGroupMember` or the `memberof` property of `get-aduser`?
Comment: It's the powershell included in Windows 2008 R2, not sure of the version. I did try initially to use the get-aduser but it outputs the opposite way.
Answer: When you pipe a list to Out-File -Append, it'll write each entry to a new line.
Instead, construct a string from the two values and pipe that:
$MemberLine = '"{0}","{1}"' -f $Item.CN,$Name
$MemberLine | Out-File $OutPutFile -encoding ASCII -append

Alternatively, use Export-Csv, it'll take care of comma-separating the values correctly:
$Members = foreach ($Result in $Results)
{
    $Item = $Result.Properties

    foreach ($Member in $Item.member)
    {
        Get-ADUser "$Member" -Properties DisplayName |Select @{Name='Group';Expression={$Item.CN}},@{Name='Member',Expression={$_.displayname}}
    }
}
$Members | Export-Csv $OutPutFile -Encoding ASCII -NoTypeInformation

As already mentioned, you can replace your [adsisearcher] with the Get-ADGroup cmdlet, much more concise:
$Groups = Get-ADGroup -Filter {GroupCategory -eq 'Distribution'}
$Groups | ForEach-Object {
  $Group = $_
  $Group.Member |ForEach-Object {
    Get-ADUser $_ -Properties displayName
  } | Select @{N='Group';E={$Group.Name}},@{N='Member';E={$_.displayName}}
} | Export-Csv $OutPutFile -Encoding ASCII -NoTypeInformation

Comment: That top one with memberline is what I was looking for. However the output comes out like this:
Comment: @bg.ranken update your question with the erroneous output
Comment: That top one with memberline is what I was looking for. The middle script seems to work well, however using both the output comes with the group blank:

    "","APC UPS Management Account"

The last one seems to just output an empty file.
Comment: @bg.ranken Use `$Item.Name` instead of `$Item.CN`
Answer: Just use following PowerShell code:
Get-ADGroup -filter "name -like 'CWS*'" | % {
$Group = $_.Name $_ | Get-ADGroupMember | select @{n="Group";e={$Group}},
@{n='Users';e={$_.Name}} | Export-CSV c:\temp\report.csv -NoTypeInformation -Append -Delimiter ";" }

Comment: When I run this I get the following error:

    Unexpected token '_' in expression or statement.
    At C:\Users\user\Documents\GetGroups5.ps1:2 char:20
    + $Group = $_.Name $_ <<<<  | Get-ADGroupMember | select @{n="Group";e={$Group}},
    + CategoryInfo          : ParserError: (_:String) [], ParseException
    + FullyQualifiedErrorId : UnexpectedToken
Comment: I don't know which PowerShell version you are using, but I have this one installed - https://www.microsoft.com/en-us/download/details.aspx?id=48729    Also try to remove line breaks and write code above as a single line, and if you want to get info about all groups you need to change filter to: Get-ADGroup -filter *


Is there an elementary proof that $\sum \limits_{k=1}^n \frac1k$ is never an integer?

Question: If $n>1$ is an integer, then $\sum \limits_{k=1}^n \frac1k$ is not an integer.
If you know Bertrand's Postulate, then you know there must be a prime $p$ between $n/2$ and $n$, so $\frac 1p$ appears in the sum, but $\frac{1}{2p}$ does not. Aside from $\frac 1p$, every other term $\frac 1k$ has $k$ divisible only by primes smaller than $p$. We can combine all those terms to get $\sum_{k=1}^n\frac 1k = \frac 1p + \frac ab$, where $b$ is not divisible by $p$. If this were an integer, then (multiplying by $b$) $\frac bp +a$ would also be an integer, which it isn't since $b$ isn't divisible by $p$.
Does anybody know an elementary proof of this which doesn't rely on Bertrand's Postulate? For a while, I was convinced I'd seen one, but now I'm starting to suspect whatever argument I saw was wrong.
Comment: It is a very strange phenomenon that many problem books seem to push the Bertrand's Postulate solution to this problem.  I remember that this came up as a problem (apropos of nothing) in my freshman year math class, and I had some problem book at hand and duly turned in a solution which used BP.  The next year I got the problem in a number theory course and by then was sophisticated enough to see the elementary solution involving the ord_2 function.
Comment: @Pete: that's interesting.  In high school competition math circles the 2-adic proof is very well known.  I first learned it on the AoPS website but it is probably also in some competition book.
Comment: Note that I include this exercise as a -- not fully worked out -- example in my (relatively advanced) undergraduate number theory course.  See the example on page 13 of http://math.uga.edu/~pete/4400intro.pdf.  (I should admit that a lot of the students have trouble with the corresponding homework problem that asks the details to be filled in.)
Comment: I remember that in my first semester I was asked about it and looking in some books I always arrived to the Bertrand postulate. But if you think so, Bertrand Postulate is still harder to prove.
Comment: [This](https://youtu.be/I7guLZvtrHc) video might help.
Comment: @QiaochuYuan, do you have the 2-adic solution, please?
Comment: From [a Harmonic Number page](https://en.wikipedia.org/wiki/Harmonic_number#Arithmetic_properties): "It is well-known that  $H_{n}$ is an integer if and only if  $n = 1$, a result often attributed to Taeisinger".
Comment: Possibly relevant: the first hint in https://math.stackexchange.com/a/438258/79359
Comment: Another good, simple explanation, but paywalled: https://www.jstor.org/stable/24496876
Comment: Quite a satisfactory approach is given here: https://math.stackexchange.com/a/4635543/239005
Answer: Hint $ $ There is a $\rm\color{darkorange}{unique}$ denominator $\rm\,\color{#0a0} {2^K}$ having maximal power of $\:\!2,\,$ so scaling by $\rm\,\color{#c00}{2^{K-1}}$ we deduce a contradiction $\large \rm\, \frac{1}2 = \frac{c}d \,$ with odd $\rm\,d \:$ (vs. $\,\rm d = 2c),\,$ e.g.
$$\begin{eqnarray} & &\rm\ \ \ \  \color{0a0}{m}  &=&\ \  1 &+& \frac{1}{2} &+& \frac{1}{3} &+&\, \color{#0a0}{\frac{1}{4}} &+& \frac{1}{5} &+& \frac{1}{6} &+& \frac{1}{7} \\
&\Rightarrow\ &\rm\ \ \color{#c00}{2}\:\!m &=&\ \ 2 &+&\ 1 &+& \frac{2}{3} &+&\, \color{#0a0}{\frac{1}{2}} &+& \frac{2}{5} &+& \frac{1}{3} &+& \frac{2}{7}^\phantom{M^M}\\
&\Rightarrow\ & -\color{#0a0}{\frac{1}{2}}\ \ &=&\ \ 2 &+&\ 1 &+& \frac{2}{3} &-&\rm \color{#c00}{2}\:\!m  &+& \frac{2}{5} &+& \frac{1}{3} &+& \frac{2}{7}^\phantom{M^M}
\end{eqnarray}$$
All denom's in the prior fractions are odd so they sum to fraction with odd denom $\rm\,d\, |\, 3\cdot 5\cdot 7$.
Note $ $ Said $\rm\color{darkorange}{uniqueness}$ has easy proof: if  $\rm\:j\:\! 2^K$ is in the interval $\rm\,[1,n]\,$ then so too is $\,\rm \color{#0a0}{2^K}\! \le\, j\:\!2^K.\,$ But if $\,\rm j\ge 2\,$ then the interval contains $\rm\,2^{K+1}\!= 2\cdot\! 2^K\! \le  j\:\!2^K,\,$ contra maximality of $\,\rm K$.
The argument is more naturally expressed using valuation theory, but I purposely avoided that because Anton requested an "elementary" solution. The above proof can easily be made comprehensible to a high-school student.
See the Remark here for a trickier application of the same idea (from a contest problem).
Comment: Beautiful! Much nicer than an ugly argument in the style of "writing everything as one fraction, one 'sees' that the denominator has more factors $2$" but essentially the same, though.
Comment: I am not able to understand how to use your hint for general $n$
Comment: did you try to show for $n=7$?
Comment: Please elaborate for n=8,16 etc
Comment: you also have to show that no other denominator contains $2^k$ as a factor.
Answer: An elementary proof uses the following fact:
If $2^s$ is the highest power of $2$ in the set $S = \{1,2,...,n\}$, then $2^s$ is not a divisor of any other integer in $S$.
To use that,
consider the highest power of $2$ which divides $n!$. Say that is $t$.
Now the number can be rewritten as
$\displaystyle \frac{\sum \limits_{k=1}^{n}{\frac{n!}{k}}}{n!}$
The highest power of $2$ which divides the denominator is $t$.
Now the highest power of $2$ that divides $\displaystyle \frac{n!}{k}$ is at least $t-s$. If $k \neq 2^{s}$, then this is atleast $t-s+1$ as the highest power of $2$ that divides $k$ is atmost $s-1$.
In case $k=2^s$, the highest power of $2$ that divides $ \dfrac{n!}{k}$ is exactly $t-s$.
Thus the highest power of $2$ that divides the numerator is atmost $t-s$. If $s \gt 0$ (which is true if $n \gt 1$), we are done.
In fact the above proof shows that the number is of the form $\frac{\text{odd}}{\text{even}}$.
Comment: It would probably be a good idea to flesh this out a little.
Comment: The exact same proof I gave works, just use $2^k$ instead of $p$. Again, you get that the sum is of the form $\frac{1}{2^k}+\frac{a}{b}$, where $b$ (being a divisor of the lcm of stuff divisible by at most $k-1$ copies of 2) is not divisible by $2^k$. This can't be an integer, otherwise $\frac{b}{2^k}+a$ would be an integer, which it isn't.
Comment: But what is there to say the sum of the $n!/k$s do not have $2^k$ dividing them?
Answer: I never heard of the Bertrand postulate approach before, although it turns out that the first proof that the $n$-th harmonic sum is not an integer when $n > 1$ uses Bertrand's postulate and determinants. It appeared in a paper of Theisinger (Bemerkung  über die harmonische Reihe, Monatsh. f. Mathematik und Physik 26 (1915), 132--134) that you can read here and he refers to Bertrand's postulate as Chebyshev's theorem. (Update: in several places I have seen Theisinger misspelled as Taesinger, and I am guilty of doing that myself in this answer until I corrected it.) The 2-adic proof is due to Kürschák (A Harmonikus Sorról, Mat. és Fiz. Lapok, 27 (1918), 299--300) and you read it here.
I like to think of this result as saying the $n$-th harmonic sum tends to infinity $2$-adically. That naturally raises the question of the $p$-adic behavior of harmonic sums for odd primes $p$, which quickly leads into unsolved problems. I wrote a discussion of that here.
Comment: +1: a new blurb.  If there were a listserve that would automatically notify me whenever there is a new blurb from KCd, I would gladly sign up for it!
Comment: @PeteL.Clark : You can create a feed for a webpage with pagee2rrss.com. In this case, add to you feeds reader: http://page2rss.com/rss/2b74436a91d372fca18b5f1645f1d59e
Comment: @leonbloy: Thannks, that sounds useful.  I'll give it a try...
Answer: What the heck -- I'll leave my comment as an answer.
See the Example on p. 13
This is discussed, together with (as a footnote) the strange phenomenon that this is often solved by an appeal to Bertrand's Postulate.  The discussion in the above text is intended to be "didactic" in that a few details are left to the reader, and I recommend it as a good exercise to flesh them out.
Comment: @BD: The construction uses something that happens to be a valuation, but I don't think that makes it valuation *theory*.  The definition of ord-p uses nothing more or less than the fundamental theorem of arithmetic, so is appropriate in an introductory course.  The point of this exercise is to get students used to making arguments of this kind which -- if they continue on in their study of number theory -- will be seen to be valuation-theoretic.  (Anyway the argument can certainly be phrased without using ord-2 if that's your taste.)
Comment: @Pete: But your exposition uses valuation theory - which disqualifies it as "elementary". Obviously the problem is trivial to anyone knowing valuation theory.Namely the sum has a **lone dominant term** with $v_2 < 0$ so, by the domination principle, the sum has $v_2 < 0$ so is nonintegral.
Comment: @Pete: Certainly it can be presented at an elementary level, and there is no doubt that it is instructive to do so. However, it's a lot of overhead to introduce for a single problem - as here. It's puzzling to hear that the exercise proved difficult for some students. Did you give them prior examples of employing the dominance principle? E.g. that a set of integers having precisely one odd element has odd sum (that is precisely what occurs in the sum above if one multiplies it through by a 2-least common denominator).
Comment: Hi BS, I understand your point. But I think, in this kind of forum, this type of answer have a great value. Altought Anton  asked for simple proof, the Pete's argument help the interested students to learn most power techniques in simple situation.
@Thanks Pete for the link.
Comment: By the way, the fact that each partial sum has a unique term of minimal 2-adic valuation was not so easy for my students. That's most of the exercise that I left for them to solve, and for many it was challenging, not trivial.
Comment: @BD: I introduce ord_p in the first chapter of my lecture notes so that I can make use of it throughout the course, not as a tool to solve this particular problem.  (Note that the idea of introducing ord-p as early as possible is taken from Ireland and Rosen.) @Leandro: you're welcome.
Comment: Dear Pete L. - Rereading "I&R" and revisiting this question, I very much appreciate this outstanding answer. In that the question comes in CH 1, the seemingly only applicable tool (I would not have thought of it) is the ord function. Thanks,
Comment: Could you please provide me the solution using ord(n) ? In the aforementioned text the author says that it's enough to prove that ord(Sn) is never equal to ord (1/(n+1)). But I'm having some troubles in proving this. Thanks a lot! @PeteL.Clark
Answer: This is a h.w. problem in Ch 1 of "Ireland and Rosen" - prob 30. There is a hint on p. 367. Let $s$ be the largest integer such that $2^s \le n$, and consider:
$\sum \limits_{k=1}^n \frac{2^{s - 1}}k$
Show that this sum can be written in the form $a/b$ + $1/2$ with $b$ odd.
Then apply problem 29 which is:
Suppose $a, b, c, d$ in $\mathbb{Z}$ and $gcd (a,b) = (c,d) = 1$
If $(a/b) + (c/d)$ = an integer, then $b = \pm d$. (But $b$ odd, $d$ = $2$.)
Maybe this was part and parcel of earlier answers. If so forgive me for trying.
Answer: I kind of have an elementary solution, it seems to be fine but I am not sure if everything is correct; please point out the mistake(s) I'm making, if any.
Define $$H_n:=\sum_{i=1}^n \frac{1}{i}$$
Since $0<H_n<n$, if $\exists$ some $n$ for which $H_n$ is integral then $H_n=k$ where $0<k<n$. Then $$H_n=k=1+\frac{1}{2}+\frac{1}{3}+\cdots\ +\frac{1}{k}+\cdots\ +\frac{1}{n}\\
\Rightarrow k=\frac{1}{k}+\frac{p}{q}\Rightarrow qk^2-pk-q=0$$ where $\gcd(p,q)=1$. Then we get $$k=\frac{p\pm \sqrt{p^2+4q^2}}{2q}$$ Since $k$ is integer $$p^2+4q^2=r^2$$ for some $r\in \mathbb{Z}^+$. Let $\gcd(p,2q,r)=d$ and let $\displaystyle x=\frac{p}{d},\ y=\frac{2q}{d},\ z=\frac{r}{d}$. Then $$x^2+y^2=z^2$$ Now, I make the following claim:
Claim:$p$ is odd and $q$ is even.
Proof: Let $s=2^m\le n$ be the largest power of $2$ in $\{1,2,\cdots,\ n\}$. Then, if $k\ne s$ then the numerator of $\displaystyle \frac{p}{q}$ is the sum of $n-1$ terms out of which one will be odd and hence $p$ is odd. On the other hand, $q$ will have the term $s$ as a factor. So q is even.
Now, if $k=s$, then since $n>2$(otherwise there is nothing to prove)then, there will be a factor $2^{m-1}\ge 2$ in $q$ and one of the sum terms in $p$ that corresponds to $2^{m-1}$ will be odd. Hence in this case also, $p$ is odd and $q$ is even. So the claim is proved. $\Box$
So, now we see that $d\ne 2$ and hence $2|y$. So we have a Pythgorian equation with $2|y, \  x,y,z>0$. hence the solutions will be $$x=u^2-v^2,\ y=2uv,\ z=u^2+v^2$$ with $(u,v)=1.$ So, since  $k$ is positive, $$k=\frac{d(x+z)}{dy}=\frac{u}{v}$$ But since $(u,v)=1$, $k$ is not an integer (for $n\ge 2$) which is a contradiction. So $H_n$ can not be an integer. $\Box$
Comment: I know this is a very late answer, but in the proof of your claim you said that p is the sum of n-1 terms out of which one is odd. Which one is that? And was it really intentional to write the requirement (p,q)=1?
Answer: Very similar to the Bertrand approach, except significantly more elementary.
Suppose for contradiction that a partial sum of the harmonic series is an integer $z$:
$$1 + \frac{1}{2} + \frac{1}{3}+...+\frac{1}{n}=z$$
Now consider the maximal power of $2$ below $n$ and let's call it $2^t$. (Note that all other integers between 1 and $n$ have a power of $2$ strictly less than t). Now consider the unique prime factorization of $n!$. The exponent of $2$ in this factorization will be greater than or equal to $2^t$, but instead let us define $M$ as $n!$, except with the power of $2$ in its prime factorization set to be $t-1$ (as opposed to some integer greater than $t$).
Multiply both sides of the equation by $M$:
$$M+\frac{M}{2}+\frac{M}{3}+...+\frac{M}{2^t}+...+\frac{M}{n}=Mz$$
$M$ has enough factors to make all terms on the LHS integers except for the $\frac{M}{2^t}$ term. Summing the LHS, we see that is not an integer, even though the RHS is an integer. Contradiction, QED.
This proof is essentially the same as the proof with Bertrand's postulate, except with $2^t$ instead of a prime number $p$ between $\frac{n}{2}$ and $n$.
Comment: This same approach was already described in several other answers.
Answer: Here's a short proof: Let $H_n = \displaystyle \sum_{k=1}^n\dfrac{1}{k}.$ One can show that $\displaystyle\sum_{k=1}^{n}\dfrac{(-1)^{k-1}\binom{n}{k}}{k}= H_n.$ This can be rewritten as: $$\sum_{k=0}^{n}{(-1)^k\binom{n}{k}a_k} = b_n$$
where $a_0 =0$ and $a_i = \dfrac{1}{i}$ for $i=1,\ldots n$ and $b_n = -H_n$
This answer shows that the $b_i$ are integers if and only if the $a_i$ are integers. Clearly for $i \geq 2 $ we can see that the $a_i$ are not integers, from which it follows that neither are the $b_i, i\geq 2.$
Answer: A more general approach that includes the proof using the prime 2 but is valid for any prime $<n$ (posted elsewhere with an erroneous n! instead of LCD):
Let the least common denominator of the harmonic series H(n) be LCD(n). Take any prime p in the sequence 1 to n and let q be the highest power of p so that $p^q ≤ n$.
For any k,  $1 ≤k ≤n $,  LCD(n)/k is an integer and = 0  (mod p) except $LCD(n)/p^q$ which is an integer and does not contain p, and therefore cannot be 0 (mod p). But H(n)LCD(n)=0 (mod p)  (since LCD(n) contains the factor p), a contradiction if H(n) is an integer.
(The simplicity comes from the use of a complicated LCD(n) which exists but whose prime powers I would not be able to describe in the general case).
Answer: I feel like the answers so far still aren't as basic as the one sketched by Mathologer in https://youtu.be/vQE6-PLcGwU?si=0nNu0EF6wkvGEeOA&t=1046. It is the same claim as some of the previous answers, but the following proof I feel is a little conceptually simpler, or written in more basic language (not as clever/"magical" as Bill Dubuque's highly upvoted answer, but hopefully something more down to earth, like something an intro-to-proofs student could write just after noticing the basic pattern that the partial sums are all of the form $\frac{[\text{odd}]}{[\text{even}]}$. Also has the added benefit of being a direct proof a stronger fact, instead of a proof by contradiction.):
Claim: writing as a fraction in lowest terms, the $n$th partial sum $S_n := 1+\frac 12 + \ldots + \frac 1n$ is of the form $\frac{[\text{odd}]}{[\text{even}]}$ ($n>1$).
Proof: by strong induction. Base case: $n=2$, $S_2=\frac 32$.
By the inductive hypothesis, for $n>2$, we now assume $S_{n-1}$ is of the form $\frac{[\text{odd}]}{[\text{even}]}$.

Case 1: $n$ is odd, in which case
$$S_n= S_{n-1} + \frac 1n = \frac{[\text{odd}]}{[\text{even}]} + \frac 1n = \frac{([\text{odd}] \cdot n) + (1\cdot [\text{even}])}{[\text{even}] \cdot n} = \frac{[\text{odd}]}{[\text{even}]},$$
(using that odd times odd is odd, plus even is still odd) which remains true even after reducing the fraction to lowest terms.
Case 2: $n$ is even, in which case we can split $S_n$ into a sum over even and odd numbers, $S_n = E_n + O_n$ where $E_n := \frac 12 + \frac 14 + \ldots + \frac 1n$, and $O_n = S_n - E_n = \frac 11 + \frac 13 + \ldots + \frac 1{n-1}$. Then $E_n = \frac 12 \cdot S_{n/2}$, which by our induction hypothesis, is of the form $ \frac{[\text{odd}]}{[\text{even}]}$.
And we know by Case 1 that adding things of the form $\frac{1}{[\text{odd}]}$ to things of the form $\frac{[\text{odd}]}{[\text{even}]}$ preserve that form, so indeed $S_n = E_n + O_n$ is of the form $\frac{[\text{odd}]}{[\text{even}]}$.

This proof by strong induction can also prove that any difference of partial sums,
$$\sum_{k=n_1}^{n_2} \frac 1k$$
is also of the form $\frac{[\text{odd}]}{[\text{even}]}$, and hence is not an integer either. (Bill Dubuque's slick 3 line proof can also prove this; it can also show the Claim in my answer, since using his notation, he shows that $2^K m = \frac 12 + \sum \frac{[\text{even}]}{[\text{odd}]}$, and $\frac 12 = \frac{[\text{odd}]}{[\text{even}]}$ plus any $\frac{[\text{even}]}{[\text{odd}]}$ will result in $\frac{[\text{odd}]}{[\text{even}]}$. Dividing by $2^K$ again keeps it as $m=\frac{[\text{odd}]}{[\text{even}]}$.)
Comment: Bill Dubuque's answer looks basic enought to me, anyway also the one you are proposing is very fine!
Comment: @user yes, but I feel perhaps it is a bit too clever, "too slick". Phrased as a proof by strong induction, it may feel more familiar to students just starting to learn about proofs (especially since we teach students that when asked to prove something is true for all $n$, induction is the first thing to try)
Answer: if we consider highest prime upto $n$
then given sum can be written as $1/p + a/b$ where a is some integer
$b$ is also an integer not divisible by $p$.
so $b/p$ can not be an integer
and so $b/p + a$.
so the given sum can not an integer
Comment: For that conclusion, you need to know that $2p > n$, that is, you need Bertrand's postulate.
Comment: You might want to use MathJax. The simple way to use it is to surround your math with \$. There are some commands you might need to learn.


Changing group visibility needs group content to be resaved when group content visibility field is set to "Use group defaults"

Question: Drupal Commons 7.x-3.2
Organic Groups 7.x-2.1
Content type: Mygroup
Field: Group visibility - value: Public
Content type: Mypost
Field: Group - default value: Mygroup
Field: Group content visibility - default value: Use group defaults
Now when I create a group and a post based off on these content types everything is fine. As in everything is visible for all users.
Now when I change the Group visibility to Private I would except the post to not be visible anymore (because of the Use group defaults setting.
Unfortuanetely that's not working until I resave the post content. Then it will respect it's parent's settings.
This bug is mentioned in this video (around 6 min)
Does anyone know how to solve this problem?
Comment: [Related question](http://drupal.stackexchange.com/q/136959), with details about the mechanisms involved.
Answer: Reason. I assume you see this behavior because all the node permissions are cached in Drupal, and only updated when (re-)saving a node or rebuilding the permissions.
Workaround. So instead of re-saving all nodes of your group individually, a faster workaround would be to go to admin/reports/status/rebuild and rebuild all permissions at once. This would probably also be the place to hook into for a real bugfix: rebuilding of the group nodes permissions, triggered when saving the group node with a different value in the "Group visibility" field.
(This answer is an educated guess, I didn't test myself so far.)
Redesign discussion. A still better solution would however be a larger rework of the OG permissions system, as discussed in Drupal issue #1122388. See esp. comment #10 there, discussing that the "Group content visibility: use group defaults" value is not that meaningful as it prohibits a use case where one wants the group itself publicly visible, but have its content default to private, and setting that via a fallback to the group setting so that later changes are simple. This scenario (publicly visible group node with private group content nodes) is supported by newer versions of Drupal Commons 7.x-3.x (using OG 7.x-2.7 here), but changing the setting only affects group content nodes added afterwards. So it's not the "fallback to group provided default" we want here, even though the "Group content visibility" field has "use group defaults" as its default value (which is not used though). That could be reported as a bug / improvement request to Drupal Commons.


Defining custom managed service fails

Question: We are trying to develop custom Intershop Managed Service following cookbook: https://support.intershop.com/kb/index.php/Display/2329T4
But when trying to enable service in Operations for our Organization, it is not listed there and there is a warning log message:
WARN  localhost ES1 appserver0 [Test-Site]  com.intershop.component.service.internal.service.ORMServiceConfigurationBORepositoryImpl [] [Storefront] [8ocH1vmRUp4E1qKOZQQC5FFRtQai9r4QV6dAV1yx] [oBlLAFsfl5kFMqjA-0-00] "oBlLAFsfl5kFMqjA-0-00" Can't load implementation for service definition: cartridge='service_esb', service definition id='ESBServiceDefinition'.

Here is services.compoment:
<?xml version="1.0" encoding="UTF-8"?>
<components xmlns="http://www.intershop.de/component/2010">

  <contract name="ESBService" class="com.test.service.capi.ESBService" />

  <implementation name="ESBServiceDefinitionImpl" class="com.test.service.internal.ESBServiceDefinition" implements="ServiceDefinition" />

  <instance name="ESBServiceDefinition" with="ESBServiceDefinitionImpl" />

  <fulfill requirement="serviceDefinition" of="serviceDefinitionRegistry">
    <instance with="ServiceDefinitionRegistry.Entry">
      <fulfill requirement="cartridgeID" value="service_esb" />
      <fulfill requirement="groupID" value="service.group.name.test" />
      <fulfill requirement="parameterGroupID" value="ESBParameters" />
      <fulfill requirement="serviceDefinitionID" value="esbService" />
      <fulfill requirement="localizationKeyForName" value="service.definition.name.esbService" />
      <fulfill requirement="serviceDefinition" with="ESBServiceDefinition" />
      <fulfill requirement="ChainElementID" value="LogHandler" />
      <fulfill requirement="ChainElementID" value="MonitorHandler" />
    </instance>
  </fulfill>
</components>

All required classes (AdapterInterface, Adapter, ExecutorService, ServiceDefinition - extending AbstractServiceDefinition) are implemented and compiled successfully. Does anybody knows why Intershop can't load implementation?
Also, in Intershop Studio in component editor following error is displayed when services.component is opened:
With 'Implementation - ESBServiceDefinitionImpl (unresolved)' cannot be resolved

But when clicking CTRL+left mouse button on "ESBServiceDefinitionImpl" implementation is found and
<implementation name="ESBServiceDefinitionImpl" class="com.test.service.internal.ESBServiceDefinition" implements="ServiceDefinition" />

is highlighted.
Comment: Is there anything else in the logs? Stop the server and clear the logs (error & warn) and start it up again.
Comment: No, nothing else. Just above warning when calling pipeline: ViewChannelServiceList-Dispatch to list all available service in BO
Answer: Of course it was typo :) I named folder with service.component "component", and not "components".
Thank you all for your help!
Comment: ah good to hear. Very often when nothing makes sense, it is something small like this.
Answer: This is a long shot but did you try to redeploy the server after creating the custom managed service?

Stop the server.
Run gradlew deployServer
Start the server
Comment: Yes, tried that also. Manually check that cartridge is deployed under server directory and loaded in SMC.
Answer: Maybe the ServiceDefinitionID does not match:
esbService vs. ESBServiceDefinition
Comment: Thanks, tried that. But as I understand from here: https://support.intershop.com/kb/index.php/Display/2329T4#Cookbook-ManagedServiceFramework-Recipe:CreateaServiceDefinitionHowtoCreateaServiceDefinition

serviceDefinitionID is not the same as serviceDefinition:
    serviceDefinitionID - myService - A ServiceDefinition is uniquely defined by cartridgeID and serviceDefinitionID.
    serviceDefinition - MyDefinition - Refers to the MyDefinition instance previously defined in the component configuration file
Comment: One question Nils, is service.compoment file (in custom service_esb cartridge) automatically scanned for available services by server startup? Or how discovery of available services works?
Answer: Can you try the following component settings:
<?xml version="1.0" encoding="UTF-8"?>
<components xmlns="http://www.intershop.de/component/2010" scope="global">

  <contract name="ESBService" class="com.test.service.capi.ESBService" />

  <implementation name="com.test.service.internal.ESBServiceDefinition" class="com.test.service.internal.ESBServiceDefinition" implements="ServiceDefinition" />

  <fulfill requirement="serviceDefinition" of="serviceDefinitionRegistry">
    <instance with="ServiceDefinitionRegistry.Entry">
      <fulfill requirement="cartridgeID" value="service_esb" />
      <fulfill requirement="groupID" value="service.group.name.test" />
      <fulfill requirement="parameterGroupID" value="ESBParameters" />
      <fulfill requirement="serviceDefinitionID" value="esbService" />
      <fulfill requirement="localizationKeyForName" value="service.definition.name.esbService" />
      <fulfill requirement="serviceDefinition">
        <instance with="com.test.service.internal.ESBServiceDefinition" />
      </fulfill>
      <fulfill requirement="ChainElementID" value="LogHandler" />
      <fulfill requirement="ChainElementID" value="MonitorHandler" />
    </instance>
  </fulfill>
</components>

Comment: Unfortunately it still doesn't work. I'm adding service via DBInit: https://support.intershop.com/kb/index.php/Display/2329T4#Cookbook-ManagedServiceFramework-Recipe:AddanAdapterDuringDBInitHowtoAddanAdapterDuringDBInit
Comment: Did u also try to add it manually? If u can add it manually first we can look at the dbinit preparer later.
Comment: I can't add it manually because there is no ESBService listed under services tab under Sales Organizations -> https://support.intershop.com/kb/index.php/Display/2329T4#Cookbook-ManagedServiceFramework-Recipe:EnabletheServiceEnabletheService
Comment: try using one of a standard groupid. . Should then be listed under Order Export Services. There must be a configuration bug somewhere
Comment: No, when opening Order Export Services group only "Local XML File Order Export" is displayed :(
Comment: Maybe component framework doesn't even load my services.componet? Is there any way I could check?
Comment: When debugging GetServiceDefinitions, I can see that ServiceDefinitionRegistry don't have my service registered. This is probably the issue, but why is that? I can see that my cartridge 'service_esb' that has service.component under staticfiles/cartridge/component is loaded in SMC for intershop.SLDSystem application.
Comment: yeah, your service is not loading and usually the log files at startup will give you some clue why it didn't load a component. I'm also quite puzzled. Did you look at the logs file under eserver/server/local/log/ and eserver/server/share/system/log. You can also enable the debug logging in smc to maybe give some clue. Also is it possible to publish the cartridge to github? So i can try it on my machine.
Comment: I'm currently trying to import https://support.intershop.com/kb/index.php/Deliver/DOC/2329T4/sample_service_cartridge_source.zip cartridge and see if that service is registered. Will update you with results. Thank you for your support!
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/173112/discussion-between-willem-evertse-and-goran-petanjek).

Defining custom managed service fails


How do we know that $\tan z$ or $\cos z$ don't have singularities off of the real axis?

Question: Since $\sin z$ is bounded, $\tan z = \frac{\sin z}{ \cos z}$ has singularities when $\cos z = 0$. We know $\cos z = 0$ for $z = \frac{\pi}{2} + n\pi$ for $n \in \mathbb{Z}$, but could it not also be zero for values of $z$ with a non-zero imaginary component?
Answer: As it turns out, no.
The trick is to expand $\cos z$ into its exponential form and substitute $z = x + iy$:
$\cos z = \frac{e^{iz} + e^{-iz}}{2} = 0 \Rightarrow e^{i(x + iy)} = -e^{-i(x + iy)} \Rightarrow e^{-y}e^{ix} = -e^ye^{-ix}$. For these quantities to be equal, certainly their magnitudes must be equal as well. Thus we have $|e^{-y}e^{ix}| = |-e^ye^{-ix}| \Rightarrow e^{-y} = e^y \Rightarrow \frac{1}{e^y} - e^y = \frac{1 - e^{2y}}{e^y} = 0 \Rightarrow e^{2y} = 1$ (since $e^y \neq 0$). This occurs precisely when $y = 0$. Thus the imaginary part of $z$ must be equal to zero for $\cos z = 0$.
A similar analysis may be carried out for $\sin z$ as well. As noted in the question, this also restricts zeros of other trig functions like $\tan z$ to lie on the real axis.


Ports to open in firewall in case of clients getting to a proxy

Question: I have an internal network inside my LAN. The clients are connected via router to the main LAN. In the main LAN there is a connection to internet.
I set up a proxy in the main LAN and connected the clients to that proxy (by the internet properties in Windows ) and it works fine.
The proxy is a SQUID type listening to port 3128.
The problem is that I want to block all other ports in the internal LAN except for the proxy port (3128). I want to force those clients to use the proxy in any case.
When I did that there is no Internet.  I suspect there are more port/s I should open. I played with it and found out that it always change... there are port/s above 55200... I cant find it... I think its dynamic.
network scheme :
<code>--internal lan -           -   clients
- clients     ---- router -- - primary lan   ---  internet
-----------  -              -  proxy server
</code>
Comment: You need to tell us at least your firewall type (hardware/software) and its platform (Linux, Windows) if it is software. Also, what have you tried to do?
Comment: The firewall in the internal router . This is a small simple router for home users . one can block ports in it .
When its with no blocking , everything works fine .
when i block all ports except of 3128 , there is no internet in the internal clients . i suspect there r some more port or ports i should open .
Answer: Edit
You need at least port 53 (DNS) for UDP and TCP.

If you really need to force everyone through the proxy then you might consider putting the proxy directly between the Router and the WAN access in a transparent matter. Thereby you counteract the need to set up the proxy on every client and still have the proxy function AND no easy way to curcumvent the proxy either.
Comment: Thanks , but I asked which ports should be opened for the client can "surf" by the proxy . when all ports are open , it works fine . but i don't want that .
I need to do that on particular group of clients that located in saperated lan . i can't touch in rules in the primary router that connected to internet .
Comment: Okay I will rethink it a bit after looking through your schema.


Maximum number of strict binary trees that can be made, each having exactly n leaf nodes.

Question: I am trying to evaluate(Mathematical expression) the number of strict binary trees that can be made with n leaf nodes.
I already know that a strict binary tree with n leaf nodes would have exactly 2*n-1 nodes, so I thought, maybe there is a way to determine the total number of strict binary trees possible with the same number of leaves.
Comment: If you mean unlabelled, rooted binary trees in which each non-leaf has $2$ children, there are $C_n=\frac1{n+1}\binom{2n}n$ of them. $C_n$ is the $n$-the [Catalan number](https://en.wikipedia.org/wiki/Catalan_number).
Comment: Yes that's exactly what I mean. But I would also like to know the proof of this expression, if you could provide me with that.
Answer: If you already know that the Catalan number $C_n$ is the number of valid parenthesis strings with $n$ pairs of parentheses, you can prove that the number of strict binary trees with $n$ internal nodes is $C_n$ by demonstrating that there is a bijection between the two sets. There is a bijection that is fairly easy to describe, and I'll sketch the argument for it.
Given a strict binary tree with $n$ leaves, think of each internal node as a pair of parentheses surrounding a product operator; the operands associated with that product operator are the two children of the node, and they go inside the parentheses. The leaves are simply labelled with variable names, e.g., $x_1,x_2$, etc. This procedure associates to each strict binary tree with $n$ internal nodes a fully parenthesized product with $n+1$ factors. I've illustrated this below for two strict binary trees with $3$ internal nodes, using the names $a,b,c$, and $d$ for the leaves.
           *                                 *
          / \                               / \
         a   *                             /   \
            / \                           *     *
           *   d                         / \   / \
          / \                           a   b c   d
         b   c

     (a·(b·(c·d)))                     ((a·b)·(c·d))

Now remove everything except the parentheses from the associated strings; in this case you get ((())) and (()()). It shouldn't be too hard to convince yourself of the following observations.

Each parenthesis string produced in this way is valid.
Each valid parenthesis string with $n$ pairs of parentheses can be produced in this way. (Checking this amounts to showing how to reconstruct the binary tree from the parenthesis string.)

Those two observations taken together amount to saying that this construction yields a bijection from the set of strict binary trees with $n$ internal nodes to the set of valid parenthesis strings with $n$ pairs of parentheses.

Alternatively, if you know that the Catalan numbers satisfy the recurrence
$$C_{n+1}=\sum_{k=0}^nC_kC_{n-k}\;,$$
with $C_0=1$, you can prove the result as follows. Let $a_n$ be the number of strict binary trees with $n$ internal nodes. Clearly $a_0=1$. To build a strict binary tree with $n+1$ internal nodes, we can start with the root and its two children. Each of these children must be the root of a strict binary tree. The internal nodes of our tree will be the internal nodes of these subtrees together with the root, so if the left subtree has $k$ internal nodes, then the right subtree must have $n-k$ internal nodes. Thus, there are $a_k$ possible choices for the left subtree and $a_{n-k}$ possible choices for the right subtree. Each choice on the left can be combined with any choice on the right, so there are $a_ka_{n-k}$ strict binary trees with $n+1$ internal nodes, exactly $k$ of which are in the left subtree. Now sum over $k$: $k$ can be anything from $0$ through $n$, so
$$a_{n+1}=\sum_{k=0}^na_ka_{n-k}\;.$$
Thus, the sequence $\langle a_n:n\in\Bbb N\rangle$ satisfies the same recurrence and initial condition as the sequence of Catalan numbers and therefore must be the sequence of Catalan numbers: $a_n=C_n$ for each $n\ge 0$.
Comment: This map isn't a bijection; the tree in your first example and its reverse both map to `((()))`, and there isn't any tree that maps to `()(())`.
Answer: The Catalan numbers count these, and the Catalan number $C_n$ also counts the number of ways to parenthesize $n+1$ factors. For instance, factors $a,b,c$ can be parenthesized $(ab)c$ or $a(bc)$, as $C_2 = 2$. See Bijection between valid parenthesis strings and ways to parenthesize factors for a bijection between these and parenthesis strings. Parenthesis strings and parenthesized factors sound similar but are actually very different objects.
It's easier to show a bijection between the parenthesized factors and the full binary trees. Given a string representing parenthesized factors, the factors will correspond to leaves, and the open and close parentheses will correspond to steps down and up, respectively.
To borrow an example:
           *                                 *
          / \                               / \
         a   *                             /   \
            / \                           *     *
           *   d                         / \   / \
          / \                           a   b c   d
         b   c

     (a·((b·c)·d))                    (((a·b)·(c·d)))

With this bijection, a pair of factors will be enclosed in parentheses together (like $b$ and $c$ in the first example above) if and only if the corresponding leaves are children of the same node in the corresponding binary tree.


show loading on jquery refresh

Question: I have this JQuery code that loads a php file into a div every X Seconds

Loading Dashboard...

when the loading starts it shows the Loading Dashboard text but then every X seconds it just refreshes the content in the background. how can i show some sort of loading image each time it refreshes?
Comment: Use a loading indicator as background of the container, then hide it in the `load` callback.
Answer: How about this:
1) at the very top of your setInterval function, before you execute the load, set the background of that container class to be a loading image (or however you want to display it).
2) use the callback function of .load (https://api.jquery.com/load/) to remove that loading image when the load has completed.
Answer: Here's a fiddle illustrating the direction you should take...
http://jsfiddle.net/j5sZc/
HTML

Loading Dashboard...

JS
$(document).ready(function() {

    $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh

    var $loader = $(".loader"), // cache references to loader and container
        $container = $(".container");

    setInterval(function() {
        $loader.show(); // show loader when request is initialized
        $container.empty().load('dashboard.php', function(){
            $loader.hide(); // hide loader once new content is loaded
        });
    }, 10000); // the "3000" here refers to the time to refresh the div. it is in milliseconds.
});

show loading on jquery refresh


How can one prove that a real function is closed?

Question: I am defining a closed function to be one that takes closed sets to closed sets. Given a function, domain and codomain, you could prove that it is not closed by simply providing a counter example according to what has been provided.
But in light of that, how would one actually prove that a given function is closed?
Comment: Do you mean closed intervals or closed sets? Because then the constant function is not closed by this definition.
Comment: Thank you. I had confused the two concepts.
Answer: It's the same "problem" with continuity: a counterexample to show non-continuity is easy (e.g. an open set whose inverse image is not open), but to show continuity you need to show every open set has an open inverse image.
Here you just have to show every closed set has a closed image. Sometimes you get this "for free", if $f$ is already known to be continuous and the domain is compact and the co-domain is Hausdorff, as a classic example of this. Or it's trivial, in the case of a map with finite image onto a $T_1$ space. I believe polynomials on the reals are closed functions, so this gives you a class of examples as well.
Y could also apply to other theorems: e.g. the projection $p: X \times Y \rightarrow X, p(x,y)= x$ is closed when $Y$ is compact, or a covering map with finite fibres is closed etc.
It is true that closed maps have fewer preservation properties: with continuity you have that products (both algebraic as Cartesian), restrictions, sums, quotients etc. of continuous maps are continuous. With closed maps you don't have that many that I'm aware of. Of course the restriction of a closed map to a closed set will be closed again.


O que o servidor deve retornar em uma requisição do tipo OPTIONS?

Question: Antes de enviar qualquer requisição ao servidor, os navegadores automaticamente enviam, antes, uma requisição do tipo OPTIONS para saber algumas informações do servidor
Que informações o servidor precisam enviar? Apenas os cabeçalhos CORS?
Essas informações devem ser enviadas apenas nessas requisições ou nas demais também? (por questão de compatibilidade com navegadores antigos ou algo assim)
Essas requisições precisam passar por autenticação?
Achei essa pergunta onde diz apenas uma frase não muito específica do que deve ser retornado
Answer: OPTIONS
O Método OPTIONS é um método HTTP, que é utilizado para descobrir quais as opções de requisições permitidas para determinados recursos para um servidor, por isso essa requisição é feita antes das outras, para descobrir permissões que você aceita.
Nessa requisição, o servidor retorna uma lista de cabeçalhos, contendo alguns dados, mas também pode retornar um erro, caso não tenha nenhuma requisição para os recursos.
Esse envio pode ser feito de duas formas, a primeira é especificando uma URL na requisição, para uma análise específica:
OPTIONS /index.html HTTP/1.1

A outra forma é indicar com asterisco (*), que refere-se ao recursos como um todo:
OPTIONS * HTTP/1.1

Essa requisição é feita inicialmente para descobrir as permissões oferecidas para os recursos, para assim poder utilizar as outras requisições sem retornar erro.
Para uma simples requisição, é possível utilizar o CURL, para enviar essa requisição de confirmação, por exemplo:
curl -X OPTIONS http://index.html -i

Nessa requisição, por padrão, se existir campos permitidos, o servidor irá retornar um cabeçalho do tipo Allow, que indica quais métodos você aceita e tem permissão de requisição, mas retornando os dados somente como uma informação:
HTTP/1.1 200 OK
Allow: OPTIONS, GET, HEAD, POST
Cache-Control: max-age=604800
Date: Thu, 13 Oct 2016 11:45:00 GMT
Expires: Thu, 20 Oct 2016 11:45:00 GMT
Server: EOS (lax004/2813)
x-ec-custom-error: 1
Content-Length: 0

Caso não tiver requisições permitidas, o servidor irá retornar um cabeçalho vazio, que pode ocorrer temporariamente para algum recurso.
As informações do OPTIONS, são feitas somente nessa requisição, para informar quais métodos você aceita fazer. Não é utilizada para confirmação de envio.
CORS
É uma especificação utilizada para definir trocas de recursos entre browser e servidor, de forma segura, não permitindo que scripts façam solicitações de origem cruzada.
Uma requisição, feita com CORS, é utilizada para saber se o servidor permite um tipo de requisição específica, informando os parâmetros para serem analisados, ou seja, é feita uma verificação de permissão "customizada" para o servidor.

Aqui, tem uma lista de cabeçalhos CORS que podem ser utilizados
  em uma requisição.

Um exemplo, é criada uma requisição, para saber se uma requisição específica que utiliza POST e tem cabeçalhos customizados é aceita. Utiliza-se os cabeçalhos Access-Control-Request-Method, para o POST e o Access-Control-Request-Headers, para os cabeçalhos customizados:
OPTIONS /resources/post-here/ HTTP/1.1
Host: bar.other
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Origin: http://foo.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-PINGOTHER, Content-Type

A partir dessa requisição "customizada", o servidor analisa e se permitir, retornará com os cabeçalhos, informando se os cabeçalhos dos campos específicos informados, podem ser solicitados. Essa resposta é parecida com uma resposta Allow.
HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2.0.61 (Unix)
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
Access-Control-Max-Age: 86400
Vary: Accept-Encoding, Origin
Content-Encoding: gzip
Content-Length: 0
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plain

O mecanismo CORS, suporta solicitações seguras de origem cruzada, que são as solicitações com origem (domínio, protocolo e porta) diferente da sua própria origem. Com isso, a requisição passam pela autenticação feita pelo servidor e retorna o resultado, para a partir disso solicitar uma requisição cruzada.
Em uma requisição com CORS, o navegador faz uma requisição, onde é passado cabeçalhos específicos, por exemplo, um cabeçalho Access-Control-Request-Method, que vai solicitar métodos que são permitidos e o servidor irá responder com Access-Control-Allow-Methods, ou seja, o navegador solicita uma confirmação, o servidor responde com um cabeçalho, informando o que é permitido e com o retorno, o navegador verifica os dados retornados, se compatível, o navegador irá liberar a solicitação cruzada, entre domínios diferentes.
Compatibilidade
Todos os navegadores tem suporte básico a esse tipo de requisição, tanto navegadores mobile, quanto para desktop:

Mais Leitura

https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Methods/OPTIONS
https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
https://pt.wikipedia.org/wiki/Cross-origin_resource_sharing
Comment: Me parece que sua resposta explica o que é o `OPTIONS` mas não explica exatamente o que deve ser retornado nesse tipo de requisição, pela sua resposta, entendi que nesse tipo de requisição só precisa retornar o cabeçalho `Allow`, nada mais, isso está correto?. Na prática qual a diferença entre `Allow` e `Access-Control-Allow-Methods`?
Comment: Essa pergunta _"Essas informações devem ser enviadas apenas nessas requisições ou nas demais também?"_ se refere a requisições do tipo `OPTIONS` e não ao CORS
Comment: @GuilhermeCostamilam fiz algumas alterações no texto
Comment: Nos links que passou está escrito _"Responses to the OPTIONS method are not cacheable"_, se a resposta não pode ser cacheada por que, no seu exemplo, tem cache?
Comment: @GuilhermeCostamilam realmente, ele não é "cacheável". Só que esse tipo de requisição, traz o que é liberado e o que pode ser utilizado. O exemplo, veio do próprio site do MDN. É tanto que se você utilizar no cmd o `curl -X OPTIONS https://developer.mozilla.org -i`, apontando para o site deles, também retornará um cabeçalho com informações parecidas.


jquery/ajax "like" button not working

Question: i have looked at the code but i can't seem to know where the problem is from
lemme drop all the required code so anybody could help
if($_POST['like_id']){
                $like_id = $_POST['like_id'];
                $like_id = mysql_escape_string($like_id);
                $id = $_SESSION['username'];
                $qry = mysql_query("SELECT user_id FROM user WHERE username='$id'");
                $chk = mysql_fetch_array($qry);
                $uid = $chk['id'];

                $query = mysql_query("SELECT like FROM topic WHERE id='$like_id'");
                while($out = mysql_fetch_array($query)){
                    $like = $out['like'];
                }
                 $qry = mysql_query("SELECT * FROM likes WHERE topic_id='$like_id' AND user_id='$uid'");
                 $count = mysql_num_rows($qry);
                 if($count == 0){
                    $new_like = $like+1;
                    $query = "UPDATE topic SET like='$new_like' WHERE topic_id='$like_id'";
                    $qu = mysql_query($query);

                    $query = mysql_query("INSERT INTO likes(user_id,topic_id) VALUES('$uid','$like_id')");
                    echo $like." likes";
                 }else{
                    echo "";
                    echo "$like";
                 }

            }

and the html part just the tag of the like button

 Like

and then the jquery/ajax part

jquery/ajax "like" button not working


Turing Machine Decidability

Question: I have been working on this problem for few hours, but haven't been able to come up with a solution :
Is the following problem decidable?
Given a TM M, whether there is a w such that M enters each of its states during the computation on w.
I tried to use reduction to show that it's not, but couldn't come up with anything. I also thought in the direction that it's decidable, but there wasn't any finite number of configuration from which I could give the time bound.
Any help will be appreciated.
Answer: I think you can reduce halting problem to this without using elaborate results.
Say you start from any TM $M$ with a state $q_{stop}$. The other states are $q_0,q_1,\dots,q_n$.
You can build the Turing machine $M'$ which simulates $M$, but has one more symbol $X$ in the alphabet.
When $q_{stop}$ is reached, the machine $M'$ goes to the right of the band, reaches the first blank symbol, and write its new symbol $X$. It does this with a new state $q'$. Then, $M'$ has transitions labeled by $X$ : $q'\to q_0\to q_1\to\dots\to q_n\to q_{stop}'$, where $q_{stop}'$ is a new state, and the stop state of $q'$. In total, $M'$ has the states of $M$ plus two new states: $q'$ and $q_{stop}'$, and $M'$ visits all states on $w$ iff $M$ stops on $w$. Therefore, your problem is undecidable.
Answer: No, it isn't decidable. I think that probably follows from Rice's theorem, but it's possible to build a proof without it.
Shannon proves that for every Turing machine there is a two-state Turing machine which simulates it. By adding a couple of characters to the alphabet and a couple of setup states which guarantee that they will be on the tape, we can ensure that the two "core" states are both visited before the calculation proper begins. We can then add a "Halt" state and replace halt transitions in the "core" two-state machine with transitions to the "Halt" state. Thus our constructed machine visits each of its states iff the original machine halts.
Suppose that we can decide whether there exists an input $w$ on which a TM $M$ halts. Then we can decide the halting problem: given TM $M'$ and input $w'$ and asked whether $M'$ halts on input $w'$ we can build a machine $M$ which discards its input, sets up $w'$ on the tape, and simulates $M'$.

Turing Machine Decidability


I'm making a GUI Program, but getting a weird error

Question: I made this program for my homework, I have to add one GUI choice to another.
The sum of the two choices are not appearing in the  Total charges per semester button.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**

        The Main class creates the GUI for the Dorm and
        Meal charges.
 */

public class Main extends JFrame
{
private JPanel dormPanel;
private JComboBox dormBox;
private JPanel mealPanel;
private JComboBox mealBox;
private JPanel totalChargesPanel;
private JPanel selectedMealPanel;
private JPanel buttonPanel;
private JButton calcButton;
private JLabel label1;
private JTextField totalCharges;

private String[] dorm = { "Allen Hall: $1,500 per semester",
        "Pike Hall: $1,600 per semester",
        "Farthing Hall: $1,200 per semester",
"University Suites: $1,800 pe  r semester"};

private String[] meal = { "7 meals per week: $650 per semester",
        "14 meals per week: $1,095 per semester",
"Unlimited meals: $1,500 per semester"};

/**
    Constructor
 */
public Main()
{
    super("Dormitory and Meal Plan");

    // Specify an action for the close button.
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Create a BorderLayout manager.
    setLayout(new BorderLayout());

    // Create the dorm and meal panel.
    buildDormPanel();
    buildMealPanel();
    buildSelectedTotalChargesPanel();
    buildButtonPanel();

    // Add the components to the content pane.
    add(dormPanel, BorderLayout.WEST);
    add(mealPanel, BorderLayout.EAST);
    add(totalChargesPanel, BorderLayout.SOUTH);
    add(buttonPanel, BorderLayout.NORTH);

    // Pack the contents of the window and display it.
    pack();
    setVisible(true);
}

// The buildDormPanel method builds the dorm panel.
private void buildDormPanel()
{
    // Create the dorm panel.
    dormPanel = new JPanel();
    dormBox = new JComboBox(dorm);

    // Register the action listener.
    dormBox.addActionListener(new ComboBoxListener());

    // Add the dorm panel to the panel.
    dormPanel.add(dormBox);
}

// The buildMealPanel method builds the meal panel.
private void buildMealPanel()
{
    // Create the meal panel.
    mealPanel = new JPanel();
    mealBox = new JComboBox(meal);

    // Register the action listener.
    mealBox.addActionListener(new ComboBoxListener());

    // Add the meal panel to the panel.
    mealPanel.add(mealBox);
}

// The buttonPanel method builds the bottun panel.
private void buildButtonPanel()
{
    // Create a panel.
    buttonPanel = new JPanel();

    // Create a button.
    calcButton = new JButton("Calculate");

    // Register an action listener with the button.
    calcButton.addActionListener(new ButtonListener());

    // Add the button to the panel.
    buttonPanel.add(calcButton);
}

// The buildSelectedDormPanel builds the selected totalCharges panel.
private void buildSelectedTotalChargesPanel()
{
    // Create the totalChargesPanel for the label.
    totalChargesPanel = new JPanel();
    label1 = new JLabel("Total charges per semester: ");

    // Create the totalCharges textfield.
    totalCharges = new JTextField (25);
    totalCharges.setEditable(false);

    // Add the totalChargesPanel to the panel.
    totalChargesPanel.add(label1);
    totalChargesPanel.add(totalCharges);
}

/** Private inner class that handles the event when the user
     selects the dorm and meal boxes.
 */
private class ComboBoxListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        // Variables to hold the dorm, meal, and total charges.
        String dorm = (String) dormBox.getSelectedItem();
        String meal = (String) mealBox.getSelectedItem();

        // Calculates the total.
        totalCharges.setText(meal + dorm);
    }
}

private class ButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        // Add code below
    }
}

public static void main(String[] args)
{
    new Main();
}
}

Comment: What does `one GUI choose to another` mean?
Comment: are you selecting anything from the combo box?
Comment: Please, for the love of `$DEITY`, [format your code so it's readable](http://stackoverflow.com/editing-help), especially if you're going to just dump your entire program into the question.
Comment: You're leaving us all hanging -- you say you're getting a "weird error" but never tell us what it is.  Seriously, you should post any error messages, even if Howard is smart enough to figure out what it is without one.
Comment: @Hovercraft Full Of Eels:  I don't think he understands what an error is.  "The sum of the two choices are not appearing in the Total charges per semester button." implies that it's not working as expected.
Comment: @Greg: You may be right, but the key word for me is "weird" suggesting he's seeing something more than just no correct output.  But heck we may as well be discussing next month's weather as no one can tell what he was thinking til he comes back and clarifies things.
Answer: In your action listener I find the following code:
// Variables to hold the dorm, meal, and total charges.
String dorm = (String) dormBox.getSelectedItem();
String meal = (String) mealBox.getSelectedItem();

// Calculates the total.
totalCharges.setText(meal + dorm);

You read strings from each combobox and then try to calculate the total. Unfortunately the term meal+dorm does not mean addition if applied to strings but string concatenation.
To solve this issue you may select a proper data structure which saves display text+value for each entry in the comboboxes, then calculate total of the values in your actionlistener and afterwards put this total to text format again.


Uncaught Error: [RouteWrapper] is not a  component. All component children of  must be a  or

Question: I'm using React Router v6 and am creating private routes for my application.
In file Route.js, I've the code
export default function RouteWrapper({
  element: Element,
  isPrivate,
  ...rest
}) {
  const { signed, loading } = useContext(AuthContext);

  if (loading) {
    return

;
  }

  if (!signed && isPrivate) {
    return <Navigate to="/" />;
  }

  if (signed && !isPrivate) {
    return <Navigate to="/dashboard" />;
  }

  return <Route {...rest} render={(props) => <Element {...props} />} />;
}

And in file index.js I've written as:
  return (
      <Routes>
        <Route path="/" element={SignIn} />
        <Route path="/register" element={SignUp} />

        <Route path="/dashboard" element={Dashboard} isPrivate />
        <Route path="/profile" element={Profile} isPrivate />
        <Route path="/customers" element={Customers} isPrivate />
        <Route path="/new" element={New} isPrivate />
        <Route path="/new/:id" element={New} isPrivate />
      </Routes>
  );
}

Is there something I'm missing?
Answer: Issue

RouteWrapper isn't a Route component, and fails an invariant check by react-router-dom.
RouteWrapper is directly rendering a Route component, which if the first invariant wasn't failed would trigger another invariant violation. Route components can only be rendered directly by the Routes component or another Route component in the case of building nested routing.

In short, in react-router-dom@6 custom route components are no longer supported. You should instead use wrapper components/layout routes to handle this use case.
Solution
Convert RouteWrapper to a wrapper component that renders an Outlet component for nested routed components to be rendered into.
Example:
import { Navigate, Outlet } from 'react-router-dom';

export default function RouteWrapper({ isPrivate }) {
  const { signed, loading } = useContext(AuthContext);

  if (loading) {
    return

;
  }

  if (!signed && isPrivate) {
    return <Navigate to="/" />;
  }

  if (signed && !isPrivate) {
    return <Navigate to="/dashboard" />;
  }

  return <Outlet />; // <-- nested routes render here
}

Wrap the routes you want to protect with the RouteWrapper.
return (
  <Routes>
    <Route element={<RouteWrapper />}>
      <Route path="/" element={<SignIn />} />
      <Route path="/register" element={<SignUp />} />
    </Route>

    <Route element={<RouteWrapper isPrivate />}>
      <Route path="/dashboard" element={<Dashboard />} />
      <Route path="/profile" element={<Profile />} />
      <Route path="/customers" element={<Customers />} />
      <Route path="/new" element={<New />} />
      <Route path="/new/:id" element={<New />} />
    </Route>
  </Routes>
);

See Layout Routes for further details.
Answer: You should convert
<Routes>
  <Route exact path="/" element={Dashboard} />
</Routes>

to
<Routes>
  <Route exact path="/" element={<Dashboard/>} />
</Routes>

Also if you want to keep your UI in sync with the URL use like this.
<BrowserRouter>
    <Routes>
       <Route exact path="/" element={<Dashboard/>} />
    </Routes>
</BrowserRouter>

Best.


How to play a D major chord lower than the open E major chord on guitar?

Question: I am writing a piece and I am trying to write a D major chord that is lower than the open E major chord on guitar. How should I do this?
I am relatively new to guitar and I have no idea what this chord might be.
Comment: I'm not a guitar expert, but would it be possible to create an illusory [missing fundamental](https://en.wikipedia.org/wiki/Missing_fundamental), at least with an electric guitar?
Comment: As you might surmise from some of the answers, there are quite a few pieces for guitar that require the player to retune (solfeggio pun not intended) the 6th string to a D instead of the customary E. That messes traditional chord positions, so it's mostly seen in classical guitar pieces that don't depend on fixed chord positions as much. Players in concert might tune the string before and after the piece, or keep a second pre-D-tuned guitar for that piece. This writing technique is not common, but it's not unheard of. For an example, look for "Seis Por Derecho" by Antonio Lauro.
Answer: If you are wanting to stick with standard tuning, then obviously there's no note lower than the low E in the open E chord - but as a chord, this D/F# (or 'first inversion' of D) might give some impression of being lower, partly because two of the strings (A and D) play a note that is a tone lower than in the open E chord:
<code>%2/.0/.0/.2/.3/.2/[D/F#]
</code>
Here's a video tutorial on how to play it....

...but to make it sound low you might want to just play the bottom 3 strings - in which case it's a very simple, one-finger chord:
<code>%2/.0/.0/.X/X.X/X.X/X[D/F#]
</code>
Comment: This post would be a good use for jtab rather than pictures of the chords.
Comment: @Dom good suggestion - I tried, but failed. (See my comment under question at https://music.meta.stackexchange.com/questions/3322/why-is-no-one-using-jtab-for-guitar-chords)
Comment: My fingers are too short and palms to fat to reach over with the thumb.  So I use my index finger to play the low D on the low E string and mute the high e.  Sounds even lower than if you include the high g note on the high e string.
Comment: I think the results are better with just the open A string below the standard D chord, with the E string blocked off. The F# is lower, but it is also the third of the chord, which is more "major" than "root" sounding. (Sorry about my terminology!)
Comment: This is what I was thinking. But I would add that you don't necessarily need to leave off 3 strings to sound lower; even just leaving out the top string will sound lower than the standard open E chord, as the top note will be lower (D vs. E).
Comment: This trick is done on the ACDC - Highway to Hell riff (intro) two first chords: D-G
Answer: Use a Drop-D tuning along with the traditional open D-major chord. Or alternatively try a DADGAD tuning and finger accordingly.
Comment: I use drop D often when playing songs in the key of D or when I need that low D note in the arrangement.  The song Country Road by James Taylor has a riff that requires drop D tuning for example.
Answer:
...How should I do this?

You have to re-tune the guitar strings so that they are low enough to play the notes you want.
The technical terms for this is scordatura although in common guitarist lingo it's usually called alternate tuning.

...I am writing a piece

You need to know how to indicate it in your score. There are two basic ways: tab and staff notation.
In tab the lines representing the strings should give the letters for tuning. Below are examples showing standard tuning and "drop D" tuning where the low E string is lowered a whole tone.

In staff notation you put some indicator at the head of the staff for guitar. Violin and guitar scordatura have different indications, but I thought it would be instructive to show both:

...note the re-tuned string number give in a circle along with the tone letter it should be tuned to (Bach, BWV 998.)

...violin family scordatura lists all the string tunings as whole notes on staff - with clefs - before the actual music staff (Kodaly, Op. 8.)
Comment: @DavidC.Ullrich, I changed the image to a better example, and if gives the info about the composer/composition.
Answer: Using standard tuning, it's really not going to happen. To make it sound lower, the bottom string at least is going to be tuned to D, which means that any other notes played on that string then need to be fretted two frets higher, which may/not cause other problems.
By tuning the whole guitar down a tone, but playing the rest of the song two frets higher, you can find that low chord. Or - play the whole song a tone higher in standard tuning, and instead of the 'low D chord', make that chord an open E.
Answer: Try this chord. I've heard it called an "inverted root", or in this case an "inverted D". But the reverse chord analyzers call it "A6sus".. Just try it in your song and see if it works.
Standard Tuning, fret it like the lower portion of a barre chord:
554xxx
I probably wouldn't know it, except that it's used by Weezer on the Blue Album in "The World has Turned", which is how I came to know of it and the only place I've ever encountered it.
You can hear it for yourself in this guy's guitar cover. FWIW I'm not endorsing this as a great guitar cover--I actually disagree with his 3rd chord, but he gets the second chord correct, with the fat, 'lower than E' sound you might be looking for..
Also @topomorto's suggestion (F#/D) is descent, but I usually leave-off the high-D, fretting it like..
2x023x
..which makes it sound a little lower. It works well in situations where you're walking down from a G, similar to the Weezer song but outside the context of barre chords. But since this version is open-fretted, it sounds a little bright--which of course you may prefer!
Comment: This is a good answer, and how I would probably 'fake' a low D chord in standard tuning. The only other options are tuning to D standard and transposing the chord positions, or using Drop D which might not be ideal depending on the use of first position open chords.
Answer: On electric guitar, you can play the E chord and whack down on the trem bar. The chord will go out of tune on a Strat but will stay if the trem is a Bigsby.
Comment: I've used Bigsbys for 50 yrs, and they make a chord go out of tune just like any other! Especially dropping a whole tone. Fact.
Comment: I don't think the OP wanted a bend sound.
Comment: @Tim Indeed! There is such a thing as a [transposing tremolo](http://www.edroman.com/techarticles/tremstb.htm), but Bigsby's are not it, in any way shape or form.


Impressão de um array com todos elementos na mesma linha

Question: Por que quando montamos uma array, como no seguinte código:
let x = 0
let array7 = new Array
for(x = 0; x < 50; x++){

    array7[x] = Math.floor(Math.random() * 50 - 10 + 10)

}

let array8 = array7.filter(array7 => array7 < 20)
console.log(array7)
console.log(array8)

a saída da array montada é toda cheia de quebras de linhas? Tem como corrigir isso e mostrar o resultado em uma linha? Saída atual:

Resumindo, por que a saída é assim, e como faço para os elementos do array serem impressos todos na mesma linha?
Comment: Isso quem fez é quem está dando a saída. Não tem código que resolva.
Comment: onde você fez essa saída assim?
Answer: Você está usando um recurso inadequado. Uma das coisas que poucas pessoas entendem é que há o dado e há a representação textual do dado. JS, assim como outras linguagens, possuem uma função toString() que entrega a representação textual do objeto. Quando você manda imprimir um dado ele pega essa representação textual. Já falei em detalhes sobre isto.
Acontece que a representação textual nem sempre é adequada para mostrar para o usuário da aplicação. Isso funciona bem com valores escalares, que são os dados simples muitas vezes considerados primitivos. Quando o dado é composto fica mais complicado definir como deveria ser a representação textual dele e em cada situação pode precisar representar de uma forma diferente, então para dados compostos a representação textual padrão fornecida só serve para efeitos de depuração. Não é o fim do mundo usá-la para apresentar para o usuário se for exatamente o que deseja, mas no caso não é, então a solução é montar a apresentação do jeito que deseja.
A pergunta não fala explicitamente mas me pareceu claro que queria que os valores deveriam ser apresentados um a um em uma linha, provavelmente separado por vírgula e por isso dou a solução abaixo.
Tem várias formas, uma delas é usando o join().

let array7 = new Array;
for (let x = 0; x < 50; x++) array7[x] = Math.floor(Math.random() * 50 - 10 + 10);
let array8 = array7.filter(array7 => array7 < 20)
console.log(array7.join(", "));
console.log(array8.join(", "));

Coloquei no GitHub para referência futura.
Comment: Se a pessoa que negativou me disser o que está errado eu conserto.
Comment: muito obrigado, conhecia a função join mas não pensei em usar neste caso, tu me recomendaria outra forma de gerar vários números aleatórios para um array sem ser utilizado ciclos de repetição?
Comment: @gmtlme depende da necessidade.


Liapunov functions

Question: I would really like to see some very simple worked out or with some well pointed hints on these guys. i have two textbooks that outline the idea behind them, but both give only one example that are very contribbed imho. ( Non-Linear dynamics and intro to chaos By Steven H Strogatz) and (differential equations, dynamical systems and intro to chaos by Morris W. Hirsch.) Textbook or links to instructive material on this subject much appreciated.  ( im an ungrad and not from math so please don't bludgeon me to death thx.)
Comment: [wiki article](http://en.wikipedia.org/wiki/Lyapunov_function) might be a good start.
Comment: Boyce and DiPrima is a popular undergrad diffeq textbook that has a section on this material, with a few examples.
Answer: Note: Be careful that the name is spelled two different ways "Liapunov" or "Lyapunov", so when searching, try both!
These papers might be instructive:

Lyapunov function methods
MIT Lectures on Dynamic Systems and Control
MIT - Finding Lyapunov Functions
A comparison of three methods of constructing Lyapunov functions
Stability theory for systems of dierential equations with
applications to power control in wireless networks

Books These have a handful of pages each and I like the first two most.

Modern Control Theory, W. Brogan (very nice write-up on the matter, with physical and electrical circuits)
The Qualitative Theory of Ordinary Differential Equations, An Introduction, F. Brauer and J.A. Nohel
Ordinary Differential Equations, V.I. Arnold
Dynamics and Bifurcations, J. Hale and H Kocak
Nonlinear systems, H.K. Khalil

There may be some applied materials from Physics areas that might also help.
Comment: Aren't you the helpful one! $\;1^+\;$
Comment: Ahhh, indeed, enjoy dinner, go home! Relax. Talk to you soon.

Liapunov functions


What is meant by $\lim_{x\to \infty^+}$

Question: I am familiar on how limits work and such. For example, look at the following limit: $$\lim_{x\to 5^+} \frac{-x^2+5x}{5-x} = 5$$
It is saying that, as $x$ approaches $5$ from the right, the equation approaches $5$ as well, but will never be exactly equal to $5$
However, I began experimenting different limits on a TI-89 and I decided to try  $$\lim_{x\to \infty^+} \frac{1}{x}$$
That is, the limit of $\frac{1}{x}$ as $x$  approaches $\infty$ from the right.
The calculator gave me an answer of $0$.
However, conceptually I do not see how you can approach $\infty$ from the right, as there isn't supposed to be anything bigger than $\infty$. How can this be possible? Or is this merely a calculator bug that was overlooked in its programming?
Comment: It's not infinity from the right... It's just "hey, what's does $f$ approximately look like when $x$ is big?"
Comment: Correct, as you noted, they make no sense with your natural interpretation (although they are kind of left/right handed in a sense).
Comment: Also note that people write $\lim\limits_{x\to\infty}$ and $\lim\limits_{x\to -\infty}$ to denote "left"/"right" (really negative/positive) infinity.
Comment: So left and right limits cannot apply to infinite limits?
Comment: I see now, as a positive infinite limit is sort of a right limit whereas a negative infinite limit can be considered a left limit. Makes sense. Thank you
Comment: If we used $\infty$ in the sense of the projective reals, but $\pm \infty$ in the sense of the extended reals, then it would make sense to define things so that $$\lim_{x \to \infty^+} = \lim_{x \to -\infty} \qquad \lim_{x \to \infty^-} = \lim_{x \to +\infty}$$
Answer: The comment made by YoTengoUnLCD is not exactly correct. From the definition of limits,
$$
\lim_{x \to \inf} \frac{1}{x}=0
$$
means that, for each $\epsilon >0$, there exists N such that
$$
\lvert\frac{1}{x}\rvert<\epsilon
$$
whenever $x>N$. (Although, in practical terms, it would be wise to treat infinity vaguely as a really big number in many problems.) Also, since there can be no number that is greater than infinity, the notation
$$
\lim_{x \to \inf^+} \frac{1}{x}
$$
is meaningless. So why does your calculator observe the limit as $0$? My guess is that the TI calculator takes the limit without the plus sign (i.e. the limit side) first. I think that the calculator has some sort of loop that says (1)observe the limit without the limit side sign $\to$ (2)if the limit from (1) exist, then stop and display the result from (1); if not, continue to (3) $\to$ (3)take the limit $with$ the limit side sign. I think that the loop would've been designed this way because it would simplify lots of calculations. If the calculators made a loop that (1)evaluated the limit from the left, (2)evaluated the limit from the right, and (3) check whether both limits exist, that would've been taken slightly longer time. After all, many limit notations we evaluate aren't one-sided limits (more often than not, anyway).
Comment: Why is my comment not entirely correct? It may be handwavy, but that's another thing :-p.

What is meant by $\lim_{x\to \infty^+}$


can you play dynamics on the electric keyboard?

Question: I mean on the electric keyboard, does it matter how hard you press? it seems like it will produce the same volume no matter what.
I want to play the dynamic "piano."
Comment: Some keyboards can do this, and some can't. Those that can are called "velocity sensitive". Some players might not consider that lightweight plastic keys are ideal for playing dynamics well though.
Comment: If you want the feeling of a piano, you need to try some digital piano. You can start looking for the Casio Privia line - they are quite good (for the price) and robust (so buying a used one is an option) For example https://www.amazon.com/Casio-PX-330-Digital-Tri-Sensor-Scaled/dp/B002IVI970
Answer: It depends on your equipment.
Some keyboards come with what are called "touch-sensitive" keys, where the force by which you press the key changes the resulting volume. Thus if you press the key lightly, you play a quiet volume, but more forceful pressing results in a louder volume.
Without this feature, keyboards will only play a set volume, and you have to adjust the volume manually (which can be done in various ways).
Comment: Also called "velocity sensitive"
Answer: It seems to be a matter of how much you spend.
Cheap: light plastic keys that don't feel like a piano and don't react to how hard you press.
Medium: similar keys but they react to pressure.  Better but they still don't feel like a real piano.
Expensive: some feel very much like real pianos but they may also cost as much as real pianos.
Answer: Many electric keyboards are velocity-sensitive. They keys have two contacts; one closes early during the stroke, and another when the key is full way down. The time gap between these two events depends on how strong (actually how fast) do you press, and controls the loudness.
The ability to control the dynamics also depends on how "heavy" the keys are. If the keys are too easy to press, it may be very difficult to press them faster or slower, you always just get the same. Even if you master somehow, the skill is not transferable to the acoustic piano and may even bind to some specific model of the electric keyboard.
You need a "fully weighted keyboard" to get something comparable to the piano keyboard. Not all of these keyboards are very expensive; cheaper versions cost only hundreds when any piano normally costs thousands.
Very high end models may even have part of the actual piano mechanism (while no strings), aiming for the really precise imitation, but approach a piano in price and more make sense only if you need a silent instrument.
Answer: Depends completely on the piano/keyboard at hand - this question would be more answerable if you gave us a link to the keyboard.
Many cheaper electric keyboards have no tactic sensor however most midrange electric (and upwards) pianos/keyboards have a velocity sensor and so it can be played dynamically.
Comment: Welcome to Music.SE. — Actually, only the _very cheapest_ general-purpose keyboards have no dynamic sensing at all. Most you can get today do have velo sensitivity, including the cheaper ones – it just tends to work not very accurately.
Comment: @leftaroundabout yes that is true however due to the fact it is usually very inaccurate I decided to not over-complicate the situation. I find that the cheaper ones tend to either play very quietly or very loudly and so there is little room for variation!


Have doubt in Summary function R?

Question: I have vector $x=[3, 5, 7, 8, 12, 13, 14, 18, 21]$ and  wanted to see summary
 statistics.
if I use summary(x) function in R, My anwser
 Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   3.00    7.00   12.00   11.22   14.00   21.00

But actual anwser is Q1 = 6 and Q2=16
What is the difference ?
Comment: See [this page](https://stats.stackexchange.com/q/134229/28500) among others on this site for an answer.
Answer: x is ordered and has $N = 9$.
The median is the element of position $(N + 1) / 2 = 5$, i.e. $12$.
The half samples $\{3,\, 5,\, 7,\, 8,\, 12\}$ and $\{12,\, 13,\, 14,\, 18,\, 21\}$ have $n = 5$.
The median of the half samples, i.e. $Q_1$ and $Q_3$ of x, are the elements of position $(n + 1) / 2 = 3$, i.e. $7$ and $14$, as returned by sample(x).
Comment: Please type `help(quantile)` at the `R` console and see the different approaches to that problem, that `R` has to offer. The heading "Types" is the most relevant one.
Comment: x<-c(1,2,3,4,4,5)
> summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  1.000   2.250   3.500   3.167   4.000   5.000   In this case  how it works please explain? @ocram

Have doubt in Summary function R?


Pass commands to a running external CMD

Question: Here is my problem, i have a currently running program that runs in the background and is only accessible via a cmd window in which you pass commands to control said program. What im trying to do is send a command from my c# winform to the cmd which then executes the command. Im basicly trying to code a gui for this program.
Cheers.
Comment: What exactly does "can be controlled via a cmd window" mean? How can it be controlled specifically? Whether it's possible or not would be highly dependent on that information.
Comment: I can issue program specific commands in the cmd. Lets say help would yield me a list of all commands that can be entered into the cmd window.
Comment: Is the "program which is not yours" currently running?  Or are you trying to invoke it?
Comment: Please [edit] your question to provide that information in the question itself so it can be seen, instead of burying it in the comments. As I said before, the answer to this question is *highly dependent* on this information, so make it available and easily seen.
Answer: Well, it's a little more involved, but this can be done by using the Windows Api.
Which means, you need to import some native libraries via P/Invoke.
First you need to get a handle to the console window. You can do this via FindWindow (P/Invoke signature).
Next to send some key-strokes there's multiple options. The most pretty one I guess is to use SendMessage (P/Invoke signature) with the WM_KEYDOWN and WM_KEYUP messages and the VK_ key as lParam argument.
Answer: Yes it is running --  You aren't going to be able to send commands to a running app unless it's designed to accept them somehow..   It either needs to have an open port or some way to 'send the command' to the running app.
Most apps that "you can't modify" can only be called with specific parameters at startup, unless they were designed to take input at runtime.
Comment: Well im able to input commands into the cmd manually and then execute them like normal with enter, is there no way to emulate me tipping a string into the cmd window ?
Comment: By [tipping](http://www.thefreedictionary.com/tipping) you mean "sending keystrokes"?
Comment: Well that is a different story, yes.  You can use the Process object to inject command s to the standard input stream while a process is running.  http://stackoverflow.com/questions/21291927/how-to-send-a-command-to-an-executable/21292269#21292269

Pass commands to a running external CMD


Proving $\mathbb{Z} \subseteq \mathbb{R}^{2}$ is closed, not open and not bounded metric spaces

Question: I'm working my way through the examples in Rudin on open sets, closed sets and other related material to get use to working with the definitions.
I'm trying to show that $\mathbb{Z} \subseteq \mathbb{R}^{2}$ is closed, but not open and not bounded. My attempts are below.
Closed:
We want to show that $\mathbb{Z} \subseteq \mathbb{R}^{2}$ contains all of its limit points. Suppose that $p =(p_{1}, p_{2})$ is a limit point of $\mathbb{Z}$ and that $\epsilon = \frac{1}{2}$ (say). Then $B_{\epsilon}(p) = \{(a,b): d((a,b), (p_{1},p_{2})) < \epsilon\}.$
For our given choice of $\epsilon, B_{\epsilon}(p) = p.$ Which contradicts the fact that $p$ is a limit point and therefore $\mathbb{Z}$ doesn't have any limit points. Hence it is closed (it contains all of its limit points, because it doesn't have any!).
NOT open:
Consider the point $(0,0)$, and let $\epsilon = \frac{1}{2}.$ Then $B_{\epsilon}((0,0))$ doesn't contain any other points of $\mathbb{Z}$ other than the point $(0,0)$ itself. Hence it is not open.
Question: What should the distance function actually be for $B_{\epsilon}((0,0))$? I am presuming it is the Euclidean metric in $\mathbb{R}^{2}$ i.e. we would be showing $\sqrt{(a-0)^{2} + (b-0)^{2}} < \epsilon$ for some $(a,b) \in \mathbb{Z}.$
NOT bounded:
If we have a metric space $(X,d)$ and $E \subseteq X$, Rudin defines a bounded set as follows

$E$ is bounded if there is a real number $M$ and a point $q \in X$ such that $d(p,q) < M$ for all $p$ in $E$.

Am I correct that NOT bounded is therefore defined as follows:

$E$ is not bounded is for all real numbers $M$ and all points $q \in X$, $d(p,q) \geq M$ for some $p$ in $E$

(I wasn't sure if its only the quantifiers that I swap)
I'm not too sure how to proceed. I was thinking I could maybe use the Archemedian property in someway, but because I'm in a subset of $\mathbb{R}^{2}$ I'm not sure if that approach will work. Similarly I can't use $\sup$ or $\inf$ as I'm in a subset of $\mathbb{R}^{2}$.
Thanks.
Comment: You need some sensible way of putting $\mathbb{Z}$ inside $\mathbb{R}^2$ see my answer for example. When you write $(a,b)$ this is saying that you can let $a$ and $b$ range throughout $\mathbb{Z}$. Drawing a picture will show you that this is a lattice, not "dots on a line" like $\mathbb{Z}$ would be.
Comment: @Mathlearner $\mathbb{Z}$ is a subset of $\mathbb{R}.$ When you want to talk about it as a subset of $\mathbb{R}^2,$ you identify it is $\mathbb{Z} \times \{0\}.$ Every element of $\mathbb{R}^2$ is an ordered pair. So technically if $n \in \mathbb{Z},$ then $n \notin \mathbb{R}^2.$ However $(n,0) \in \mathbb{R}^2.$
Comment: Shouldn't $B_{\epsilon}(p)=\{(a,b)\in \mathbb{R}^2:d((a,b),(p_1,p_2))<\epsilon\}.$ Why did you write $a,b \in \mathbb{Z}?$ Your solution has me confused whether you're talking about th subset $\mathbb{Z}\times \mathbb{Z}$ or $\mathbb{Z} \times \{0\}.$
Comment: @Yes I was just trying to convey that $a$ and $b$ are integers.
Comment: So your set is $\mathbb{Z} \times \mathbb{Z}?$
Comment: No. It's just $\mathbb{Z}$ as a subset of $\mathbb{R}^{2}$. I put two coordinates $(a,b)$ etc because I thought since I am dealing with a subset of $\mathbb{R}^{2}$ I need to have two coordiantes.
Comment: So your set $\mathbb{Z} \times \{0\}.$ Of course, you need an ordered pair when you talk about an element of $\mathbb{R}^2.$ In that case $B_{\epsilon}(p) \cap \mathbb{Z}=\{(a,0):d((a,0),(p_1,p_2))<\epsilon\}.$
Comment: What's the difference between having $B_{\epsilon}(p) = \{(a,b): d((a,b), (p_{1}, p_{2})) < \epsilon\}$ and $\{(a,0): d((a,0), (p_{1}, p_{2})) < \epsilon\}$? I don't understand why the second co-ordinate has to be $0$? i.e. $(a,0)$
Answer: I will assume that we are using a sensible embedding of $\mathbb{Z} \subset \mathbb{R}^2$ (say by $n \mapsto (n, 0)$).
To your question about the metric. From context I would presume that the metric is the usual euclidean one (the claim is false if we take an arbitrary metric - consider the discrete metric which makes all subsets open!).
Your proofs of closedness and non-openness seem fine.
You are right to think the set is not bounded. What you want to show is

Given any $M > 0$ and any $p \in \mathbb{R}^2$, there is some $a \in \mathbb{Z} \subset \mathbb{R}^2$ such that $d(p, a) > M$.

To do this, suppose that $p = (x, y)$. Then $d(p, (n,0)) \geq |n - x|$, so if we choose some large $n$ so that $|n - x| > M$ we are done.
Comment: thanks for the reply. Where we have $d(p, (n,0)) > |n-x|$, is this because our distance function is $\sqrt{(n-x)^{2} +y^{2}}$?
Comment: @Mathlearner yes that is one way to see it, another way is via the triangle inequality.
Answer: I identify $\mathbb{Z}\cong\mathbb{Z} \times \{0\}\subseteq \mathbb{R}^2$
Closed: Any converging sequence on $\mathbb{Z}$ must be eventually constant so this is trivial.
Not open: The ball $B_{\mathbb{R}^2}(0,\epsilon)$ always contains a non-integer.
Not bounded: A bounded subset of $\mathbb{R}^2$ lies in some ball $B_{\mathbb{R}^2}(0,r)$ with large enough radius. It is then clear that $\mathbb{Z}$ is not bounded.


How do you make an encrypted swap partition setup persistent across boots?

Question: I have a procedure which will manually create a plain dm-crypt swap volume, with a random key, which appears to work. This is a QEMU/Ubuntu 22.04 system. However, there's no swap after a reboot, so I've presumably got my /etc/crypttab and/or /etc/fstab, or something else, incorrect. Any input appreciated.
The working manual setup is:
    # swapoff -a
    # cryptsetup --type plain open /dev/mapper/vg0-swap encswap
    # mkswap /dev/mapper/encswap
    # /etc/init.d/cryptdisks start
    # swapon /dev/mapper/encswap

    # swapon -s
    Filename                Type        Size        Used    Priority
    /dev/dm-3               partition   2097148     0       -2
    # lsblk
    NAME          MAJ:MIN RM  SIZE RO TYPE  MOUNTPOINTS
    sda             8:0    0   50G  0 disk
    ├─sda1          8:1    0    1M  0 part
    ├─sda2          8:2    0    1G  0 part  /boot
    ├─sda3          8:3    0   13G  0 part
    │ ├─vg0-swap  253:0    0    2G  0 lvm
    │ │ └─encswap 253:3    0    2G  0 crypt [SWAP]
    │ ├─vg0-data  253:1    0 36.1G  0 lvm   /data
    │ └─vg0-root  253:2    0 10.9G  0 lvm   /
    └─sda4          8:4    0   36G  0 part
      └─vg0-data  253:1    0 36.1G  0 lvm   /data
    sr0            11:0    1    4M  0 rom
  # cryptsetup status /dev/mapper/encswap
  /dev/mapper/encswap is active and is in use.
  type:    PLAIN
  cipher:  aes-cbc-essiv:sha256
  keysize: 256 bits
  key location: dm-crypt
  device:  /dev/mapper/vg0-swap
  sector size:  512
  offset:  0 sectors
  size:    4194304 sectors
  mode:    read/write

So, to make this persistent, /etc/crypttab contains:
swap  /dev/mapper/encswap  /dev/urandom  plain,cipher=aes-xts-plain64,size=256,hash=sha256,swap,noearly

And /etc/fstab contains:
/dev/mapper/swap none swap sw 0 0

When the system boots up, dm-crypt or systemd runs through the default 90s timeout, so appears to be waiting for a key which never arrives. The syslog says much the same thing - timed out waiting /dev/mapper/encswap. When boot completes, swapon -s shows nothing, and lsblk doesn't show an encswap device (or any swap device). Any ideas?
Answer: Your /etc/crypttab looks wrong:
swap  /dev/mapper/encswap  /dev/urandom  plain,cipher...

The second field should be the device that contains the encrypted data, which would be /dev/mapper/vg0-swap. I don't think noearly is valid, so try
swap  /dev/mapper/vg0-swap  /dev/urandom  swap,plain,cipher=aes-xts-plain64,size=256,hash=sha256

You can debug by running /usr/lib/systemd/system-generators/systemd-cryptsetup-generator. This reads /etc/crypttab and creates a unit file in /tmp; find the file, and run the start command in there directly. This will give you much more useful logging/debug output.