Does there exist a fraction whose repeating decimal has a period of some highest number or can the number of this period take infinitely many values?

Question: It is well known that every decimal of a fraction becomes periodic at one point or the other, e.g: 1/3 starts repeating at period 1, 27/91 at period 6 and 3923/6173 at period 3086.
Now, as there are an infinite number of non-zero values that we may place in the numerator or denominator of a fraction, the following question arises: does there exist a fraction whose repeating decimal has a period of some highest number or can the number of this period take infinitely many values?
In other words, does there exist some fraction whose repeating decimal has a period of 577291485 or even 5*10^444? And furthermore, is it true that there are an infinite number of fractions whose decimal number has the period 5?
It should be kept in mind however that the numerator/denominator of the fractions in question may contain numbers not repeating thrice/twice, e.g: 586192/247591, or 1/43817 and 1/39820, so it's not just 1/9 or 1/999.
Comment: @fleablood: You seem to have misunderstood the gist of the question. The OP is asking not whether the period is in itself infinite, he is asking whether the period can take infinitely many values, whether there may exist fractions whose repeating decimal has a period of *any* number, even 5867473710 or numbers ranging around 10^400, he illustrated this with various examples. There is nothing wrong with this and it has already been given a satisfactory answer.
Comment: Have you thought about how to write a repeating decimal fraction with period (say) one million?
Comment: "does there exist a fraction whose repeating decimal has a period of some highest number or can the number of this period take infinitely many values? "  Neither.  A period can be any finite length and there is no highest.  An infinite period however is a nonsensical  string of words that make no sense and is as logically inconsistent as "four-sided triangle".
Comment: "is it true that there are an infinite number of fractions whose decimal number has the period 5?"  There are each digit of a string of 5 characters can have any of $10$ values there are $10^5$ different possible strings.  Last time I check $10^5$ was a finite number. But we can precede the fraction by anything so .... yes.  But a reduced fraction $\frac 1 n$ there are only $10^5$ possible with period of $5$.
Comment: He/she however imposed an important restriction which would deter us from giving this an arbitrary solution by considering that 1/9, 1/99, 1/999... and so the period of these fractions will increase infinitely along with the continual addition of 9 in the denominator. Dealing with this restriction adequately, I think, would require combinatorial notions.
Comment: I understood the gist of the question perfectly.  And I answered it in my comment: " A period can be any finite length and there is no highest."   But the statement "or can the number of this period take infinitely many values" is a poorly stated and incorrect statement and needed to be shown to be incorrect.  So I did.
Comment: I think you're interpreting it as if the OP is asking whether it's possible for the period to be of an infinite length which he/she clearly didn't intend and that's why he/she later added two examples to somewhat illustrate this. When the OP refers to "infinitely many values", he/she is not meaning to say something like 111111.. continuing onto infinity, but rather the number of the period being able to be *every* positive integer.
Answer: Consider $\cfrac 19, \cfrac 1{99}, \cfrac 1{999} \dots$
For the second part, what happens to the period of the fraction when you multiply the denominator by $10$?
In general a fraction which repeats will have the form $$f=\frac p{10^r}+\frac q{10^{r}}\left(\frac 1{10^n}+\frac 1{10^{2n}}+\frac 1{10^{3n}}+\dots\right)$$ Where $p$ is an integer with up to $r$ digits ($r$ and $p$ may be zero) which represents the non-recurring part of the fraction, and $q$ is the repeating part, with up to $n$ digits. Now we see that $$10^rf-p=qs$$ where $s$ is the sum of the series. Multiply by $10^n$ and obtain $$10^{r+n}f-10^np=10^nqs=q+qs=q+10^rf-p$$ and $$f=\frac p{10^r}+\frac q{10^r(10^n-1)}$$
If we take $p=r=0$ for the moment so that $f=\cfrac q{10^n-1}$ is the form of a fraction which recurs without a non-recurring part, we see that a fraction which has a denominator which is a factor of $10^n-1$ will recur after $n$ places. It may recur after fewer places than that, but not after more.
Every odd prime $k$ is a factor of $10^n-1$ for some minimum value of $n$, and $\frac 1k$ will then recur with period $n$.
There are more answers on this site which go into more detail than this, and there is a full treatment in Number Theory book by Hardy and Wright. If you explore it a bit yourself you may find some interesting things.
The reason denominators $9, 99, 999$ etc come into it (they correspond to $q=1$) is that they are the values of $10^r-1$.
Comment: @Jasmus Chapter IX The representation of Numbers by Decimals
Comment: I have edited my question. Can you please take a look and modify your own answer if needed?
Comment: @Jasmus I have added some things. Try computing the period of the reciprocals of small primes and factoring the numbers $9, 99, 999, 9999$ etc to get a feel for what is going on.
Comment: Thank you very much for editing your answer, it answered my inquiries nicely. However, I'd greatly appreciate it if you could tell me in what chapter of Hardy & Wright's book these concepts and this topic is discussed.
Answer: $\frac{1}{10^p - 1}$ will have period $p$ for any positive integer $p$.


What semantic notions underlie the Ancient Greek 'Anacrusis' and its meaning as 'pickup note'?

Question:
 [Etymonline :]  "unstressed syllable at the beginning of a verse," 1833,
Latinized
from Greek anakrousis "a pushing back," of a ship, "backing water,"
from anakrouein "to push back, stop short, check," from ana "back" (see ana-) + krouein "to strike,"
from PIE *kreue- (2) "to push, strike"

In what sense can a pickup note be judged as pushing back or up (the definition of 'anacrusis' in Ancient Greek)?  (Nescient of poetry) I do not understand Wikipedia's explanation) of the semantic shift from poetry:

Poetry
In poetry, a set of extrametrical syllables at the beginning of a verse is said to stand in anacrusis (Ancient Greek: ἀνάκρουσις "pushing up"). The technique is seen Old English poetry,[1] and in lines of iambic pentameter, the technique applies a variation on the typical pentameter line causing it to appear at first glance as trochaic.
Music
[...] The musical term is inferred from the terminology of poetry, where it refers to one or more first but unstressed syllables of a lyrical verse. [...]
Answer: Perhaps I'm missing something, but I don't see any semantic shift at all between an anacrusis in poetry and in music: it's one and the same thing, pretty much.  Poetic speech has rhythm, perhaps not always as strict as music commonly is, but there's no place you can really draw a line between poetry and song.  And the anacrusis, or pickup, or Auftakt as we say here in Austria, is, as the wiki article says, an unaccented tone or syllable or beat or more that occur before the first accented beat of the rhythm.
Comment: & even the simplest has an anacrusis - any Limerick... "There **was** a young **wo**man from **Leeds**, which is a 6/8 or swing, just the same as [without anacrusis] "Nellie the elephant packed her trunk..."
Comment: Maybe it's the "pushing back" as these days we'd be inclined to say that was 'bringing forwards'. I think of pushing back as leaving your timing a tad late for emphasis


Unable to install the "H5P.Scorm.h5p" library: "The uploaded file was not a valid h5p package"

Question: Thanks to jackrabbithanna's help on this other question I seem to be 1/2 way to getting H5P related libraries installed in my Drupal 7.59 install. I am attempting this on macOS High Sierra under MAMP 4.5 (PHP 7.1.12) and MAMP 3.5.2 (PHP 5.6.10).
But like I said, I am 1/2 way there; not fully there. I am able to get the H5PEditor.ScormFile (1.0.8) library installed, but not H5P.Scorm (1.1.16).
The libraries in question are as follows:

H5PEditor SCORM
H5P SCORM/xAPI

To help this process, I have now devised a bit of a Bash scripting process to get the h5p packages built from the source GitHub repos. Here is what I do…
The H5PEditor.ScormFile (1.0.8) Bash dance:
cd ~/Desktop/

git clone https://github.com/pavloshevchuk/h5p-editor-scorm

cd ~/Desktop/h5p-editor-scorm

find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

mkdir H5PEditor.ScormFile && mv {scripts,styles,*.json} H5PEditor.ScormFile

echo '{
  "title": "H5PEditor.ScormFile",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5PEditor.ScormFile",
      "majorVersion": 1,
      "minorVersion": 0,
      "patchVersion": 8
    }
  ],
  "mainLibrary": "H5PEditor.ScormFile",
}' > h5p.json

zip -r ../H5PEditor.ScormFile.h5p *

The H5P.Scorm (1.1.16) Bash dance:
cd ~/Desktop/

git clone https://github.com/pavloshevchuk/h5p-scorm

cd ~/Desktop/h5p-scorm

find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

mkdir H5P.Scorm && mv {css,js,*.json} H5P.Scorm
mkdir content && mv icon.svg content

echo '{
  "title": "SCORM/xAPI",
  "language": "en",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5P.Scorm",
      "majorVersion": 1,
      "minorVersion": 1,
      "patchVersion": 16
    }
  ],
  "mainLibrary": "H5P.Scorm",
  "embedTypes": [
    "div"
  ]
}' > h5p.json

zip -r ../H5P.Scorm.h5p *

And with those two things done I now have two H5P files ready to go: H5PEditor.ScormFile.h5p and H5PEditor.ScormFile.h5p.
But while installing H5PEditor.ScormFile.h5p proceeds as expected, the same can't be said for H5PEditor.ScormFile.h5p. I get the following Drupal system information message:

For security reasons, your upload has been renamed to H5P.Scorm_.h5p.

Followed by this "great news":

The uploaded file was not a valid h5p package

Screenshot attached below. Any insight is appreciated.
Answer: Short Answer
Font Awesome (4.5.4) libraries needed to be explicitly installed for H5P so that Scorm (1.1.16) can be installed. Details on how that was done near end of answer.

Long Answer
Happily, I was able to self-solve this. Starting with a fresh, clean, 100% new install of Drupal 7.59 I went ahead with this process again. Getting H5PEditor.ScormFile (1.0.8) installed was fine—as before on a more established Drupal 7.59 install—but ran into the same exact issue with H5P.Scorm (1.1.16)… But on this clean install I did get a major clue via more details in error reporting; screenshot below but the text reads:

"Missing required library FontAwesome 4.5"

I took this error to mean that the Drupal module and related libraries for Font Awesome were not installed and that is why the "The uploaded file was not a valid h5p package." error came up.
So I went ahead and did that—and installed Font Awesome 4.7 libraries—screenshot below:

Tried installing H5P.Scorm (1.1.16) again… And again, the same message:

"Missing required library FontAwesome 4.5" message.

So I took this all to mean that H5P needed it's own library install of Font Awesome, Googled and found this H5P related Font Awesome repo.
Great! So now learning what I learned previously in this other answer, I figured out how to create my own H5P.FontAwesome.h5p library, which WORKS GREAT! Screenshot below to show the process did work and I was able to get H5P.Scorm (1.1.16) installed once the H5P specific Font Awesome library was installed as well:

And to make everyone's life easier—especially mine—I created a fairly simple Bash script that allows me to automatically create the H5PEditor.ScormFile.h5p, H5P.FontAwesome.h5p and H5P.Scorm.h5p libraries on my macOS machine; see below for source code. Just save it as a Bash file named something like build_h5p_scorm_libs.sh and give yourself execute permissions via chmod u+x build_h5p_scorm_libs.sh and you are good to go.
Library installation order should be as follows:

H5PEditor.ScormFile.h5p
H5P.FontAwesome.h5p
H5P.Scorm.h5p

Genuinely hope this helps someone in the future!
#/bin/bash

################################################################################
# Build the H5PEditor.ScormFile H5P file.
################################################################################

# Go to the Desktop.
cd ~/Desktop/

# Clone the repo.
git clone https://github.com/pavloshevchuk/h5p-editor-scorm

# Go into that cloned repo.
cd ~/Desktop/h5p-editor-scorm

# Clean up cruft that is not needed for the H5P file.
find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

# Create the library directory and copy files into it.
mkdir H5PEditor.ScormFile && mv {scripts,styles,*.json} H5PEditor.ScormFile

# Create the 'h5p.json' file.
echo '{
  "title": "H5PEditor.ScormFile",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5PEditor.ScormFile",
      "majorVersion": 1,
      "minorVersion": 0,
      "patchVersion": 8
    }
  ],
  "mainLibrary": "H5PEditor.ScormFile",
}' > h5p.json

# Now Zip that all up into a compressed `.h5p` archive like this.
zip -rq ../H5PEditor.ScormFile.h5p *

################################################################################
# Build the H5P.FontAwesome H5P file.
################################################################################

# Go to the Desktop.
cd ~/Desktop/

# Clone the repo.
git clone https://github.com/h5p/font-awesome

# Go into that cloned repo.
cd ~/Desktop/font-awesome

# Clean up cruft that is not needed for the H5P file.
find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

# Create the library directory and copy files into it.
mkdir FontAwesome && mv {*.css,*.otf,*.eot,*.svg,*.ttf,*.woff*,*.json} FontAwesome

# Create the 'h5p.json' file.
echo '{
  "title": "FontAwesome",
  "language": "en",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "FontAwesome",
      "majorVersion": 4,
      "minorVersion": 5,
      "patchVersion": 4
    }
  ],
  "mainLibrary": "FontAwesome"
}' > h5p.json

# Now Zip that all up into a compressed `.h5p` archive like this.
zip -rq ../H5P.FontAwesome.h5p *

################################################################################
# Build the H5P.Scorm H5P file.
################################################################################

# Go to the Desktop.
cd ~/Desktop/

# Clone the repo.
git clone https://github.com/pavloshevchuk/h5p-scorm

# Go into that cloned repo.
cd ~/Desktop/h5p-scorm

# Clean up cruft that is not needed for the H5P file.
find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

# Create the library directory and copy files into it.
mkdir H5P.Scorm && mv {css,js,*.json} H5P.Scorm

# Create the content directory and copy files into it.
mkdir content && mv icon.svg content

echo '{
  "title": "SCORM/xAPI",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5P.Scorm",
      "majorVersion": 1,
      "minorVersion": 1,
      "patchVersion": 16
    }
  ],
  "mainLibrary": "H5P.Scorm",
  "embedTypes": [
    "div"
  ]
}' > h5p.json

# Now Zip that all up into a compressed `.h5p` archive like this.
zip -rq ../H5P.Scorm.h5p *

Unable to install the “H5P.Scorm.h5p” library: “The uploaded file was not a valid h5p package”


prove that $[a,b)\cong [c,d)\cong (a,b]\cong(c,d] $ with a<b and c<d and a,b,c,d any real numbers

Question: $$[a,b)\cong [c,d)\cong (a,b]\cong(c,d] $$
this is my guess:
So first I'm trying to come up with an interval and a function that will be homeomorphic for each of the intervals and then I'll use the transitivity property to show that they're all homeomorphic to each other.
But i cannot think of a function that works, i have tried on the interval $[0,1)$ and $[0,1]$
and here are some functions that find interesting and close enough to give an idea
$$ h(x)= \frac{x+c}{1-x} $$ as a failed atempt to prove an homeomorphism between $[0,1)$ $\mapsto$ $[c,d)$
any help to find the interval and the function would be awesome
tks in advance
Answer: Just stretch and slide, stretch and slide.
Match the roundy bits to the to the roundy bits and the square bits to the square bits.  So $[a,b) \to [c,d)$ will be $x \mapsto \frac {x - a}{b-a}\times (d-c) + c$...
And $[c,d) \to (a,b]$ will be $x \mapsto \frac {x-c}{d-c}\times (a-b) + b$
And $(a,b] \to (c,d]$ will be $x \mapsto \frac {x-b}{a-b}\times (c-d) + d$
And $(c,d] \to [a,b)$ will be $x \mapsto \frac {x-d}{c-d}\times (b-a) + a$
Answer: For $$ f: [0,1) \to [c,d) $$ try $$ f(x) = (d-c)x+c $$
For $$ f: [0,1) \to (-1, 0] $$ try $$ f(x) = -x $$
You can find other cases easily.


Center the open layer map when in edit mode

Question: i setup a map with openlayers, geofield, addressfield and geocoder.
I added a geofield to a node, with openlayers as the widget type, and use geocoder to get the geocode from addressfield.
when editing, user press the Find using Address field button and the map display with the marker if found.
the question: how to center the marker? If i set the zoom level higher (in Center and Bounds setting of open layer), the marker will not be shown (out of the visible map area).
Comment: I still need help on this, let me know if the question is not clear.
Answer: you need to enable placeholderlayer in openlyers map with a marker of your choice. and then in behaviours you need to zoom to layer and enable placeholder layer and save.
Comment: i couldn't make it work.. Can you please elaborate more? Thanks!
Comment: I am not clear with your requirment please elaborate more.


Summation Notation for Current Index

Question: I have a question on how to properly present a summation with the use of variables. I am not so familiar with how to properly use summation notation, and am looking for some advice on how to do so properly.
Right now, I have built the following summation:$$t_\text{pal}=\sum_{i=1}^{N_R}\left(n_it_i-\sum_{j=\text{current index}}^{N_R}n_jt_j\right)$$
Within the outer summation, I have an inner summation that I want to start at the index of the current term (represented as j = current index) . How should this be represented in the inner summation, would it just be j = i?
Also, I want to also have a condition where if the value of the term is less than 0, the term takes the value of 0 (if term < 0, term = 0). How should this be properly represented in the summation?
Thank you.
Comment: So you're really asking two questions. (i) What should "current index" be? If you make it $i$,$$t_\text{pal}=-\sum_{i=1}^{N_R}\sum_{j=i+1}^{N_R}n_jt_j,$$so I wonder if the rest of your expression says what you intended, but of course there's nothing wrong with this double sum. (ii) How do you replace a term, say $x$, with $0$ if $x<0$? [You can write](https://en.wikipedia.org/wiki/Positive_and_negative_parts) $x^+$, or $(x)^+$ if $x$ is an expression comprising muiltiple symbols.
Comment: @J.G. Hi J.G., thank you for the advice. I have one question about part (i) of the answer. If I were to expand out the inner summation, how would it be represented?
Comment: I think you're asking (with the abbreviation $u_i=n_it_i$) why $u_i-\sum_{j=i}^{N_R}u_j=-\sum_{j=i+1}^{N_R}u_j$, or (multiplying by $-1$, which might make it clearer) $\sum_{j=i}^{N_R}u_j-u_i=\sum_{j=i+1}^{N_R}u_j$. The left-hand side is$$\color{red}{u_i+}\color{blue}{u_{i+1}+\cdots+u_{N_R}}\color{red}{-u_i}=\color{blue}{u_{i+1}+\cdots+u_{N_R}},$$matching the right-hand side.
Comment: @J.G. Hi J.G., gotcha. I think I understand now, so lets say if $N_R = 3$, then the equation,
$$
t_{pal} = -\Sigma^{N_R}_{i = 1}\Sigma^{N_R}_{j = i + 1}n_jt_j
$$
can be expressed as
$$
t_{pal} = -n_3t_3 - n_2t_2 ?
$$
Answer: Here is a derivation with some intermediate steps. We obtain

\begin{align*}
\color{blue}{t_{\text{pal}}}&=\sum_{i=1}^{N_R}\left(n_it_i-\sum_{j=i}^{N_R}n_jt_j\right)\tag{1}\\
&=\sum_{i=1}^{N_R}\left(n_it_i-\left(n_it_i+\sum_{j={i+1}}^{N_R}n_jt_j\right)\right)\tag{2}\\
&=\sum_{i=1}^{N_R}\left(-\sum_{j={i+1}}^{N_R}n_jt_j\right)\tag{3}\\
&\,\,\color{blue}{=-\sum_{i=1}^{N_R}\sum_{j={i+1}}^{N_R}n_jt_j}\tag{4}\\
\end{align*}
Comment:

In (1) we start with $j=i$ in the inner sum.

In (2) we separate the first summand from the inner sum.

In (3) we cancel the terms $n_it_i$.

In (4) we factor out $-1$.

Note, we can the sum (4) also write as
\begin{align*}
-\sum_{i=1}^{N_R}\sum_{j={i+1}}^{N_R}n_jt_j=\sum_{i=1}^{N_R}\sum_{j={i+1}}^{N_R}\left(-n_jt_j\right)
\end{align*}
If depending on $n_j$ and $t_j$ the innermost terms $(-n_jt_j)$ is positive or should be set to $0$ otherwise we can write for instance
\begin{align*}
\color{blue}{\sum_{i=1}^{N_R}\sum_{j={i+1}}^{N_R}\max\{-n_jt_j,0\}}\qquad\text{or}\qquad\color{blue}{\sum_{i=1}^{N_R}\sum_{j={i+1}}^{N_R}\left(-n_jt_j\right)^{+}}
\end{align*}
as already indicated in the comment section.
Comment: Thank you for the answer! It definitely cleared up the confusion I had.
Comment: @Justin: You're welcome! Good to see the answer is helpful. :-)

Summation Notation for Current Index


Proving that the following subset of $\mathbb{Z}$ is the subgroup generated by its minimum

Question: Let $F$ be a free abelian group, i.e. $F \simeq \mathbb{Z}^n$ for some $n \in \mathbb{N}$, $n \neq 0$ and let $G < F$ be a subgroup. Consider the following subset of $\mathbb{Z}$:
\begin{equation}
 S := \bigl\{\,s \in \mathbb{Z} \, \bigm| \, sy_1+k_2y_2+\dots+k_ny_n \in G \, , \, \exists \, \{y_1,\dots,y_n\} \hspace{1mm} \text{basis of $F$} \, , \, k_2,\dots,k_n \in \mathbb{Z}\,\bigr\}
\end{equation}
Let $d_1$ be the minimum of $S$, which is well defined because $S$ is a non-empty set (in fact, $0 \in S$). I need to prove that $S = \langle d_1 \rangle$, where $\langle d_1 \rangle$ denotes the subgroup generated by $d_1$, i.e. the subgroup $\{\,kd_1 \mid k \in \mathbb{Z}\,\} < \mathbb{Z}$. My idea was a proof by double inclusion. Clearly, $\langle d_1 \rangle \subseteq S$: let $kd_1 \in \langle d_1 \rangle$. Then, since $d_1 \in S$, there exist a basis $\{y_1,\dots,y_n\}$ for $F$ and elements $k_2,\dots,k_n \in \mathbb{Z}$ such that $d_1y_1 + k_2y_2 + \dots + k_ny_n \in G$. Since $G < F$ is a subgroup, $kd_1y_1 + kk_2y_2 + \dots + kk_ny_n \in G$ too and this proves that $kd_1 \in S$. I'm stuck with the inclusion $S \subseteq \langle d_1 \rangle$.
Answer: You need to choose $d_1$ to be minimal in $S$ with $d_1 \ge 0$. If $d_1=0$ then $S$ is the trivial subgroup so assume not.
So there exists $g=d_1y_1 + k_2y_2 + \cdots k_ny_n \in G$. First note that $d_1$ divides each $k_j$, because if not, then we could write $k_j = rd_1+s$ with $0 < s < d_1$, and then  writing $g$ in the free basis $y_1',y_2,\ldots,y_n$ with $y_1' = y_1 + ry_j$ gives $g= d_1y_1' + \cdots + sy_j + \cdots$, contradicting minimalty of $d_1$.
Now let $h = l_1y_1 + \cdots l_ny_n$ be an arbitrary element of $G$. We claim  that $d_1$ divides each $l_j$. Note first that $d_1$ divides $l_1$, since otherwise $l_1 = rd_1+s$ with $0 < s < d_1$, and then $h-rg = sy_1 + \cdots$ contradicts the choice of $d_1$.
So $l_1 = d_1r$ for some $r$, and then $$h-(r-1)g = d_1 y_1 + (l_2 -(r-1)k_2)y_2 + \cdots + (l_n - (r-1)k_n)y_n.$$ By the same argument as before, $d_1$ divides each $l_j - (r-1)k_j$ and, since we already know that $d_1$ divides $k_j$, we have $d_1$ divides $l_j$ as claimed.
To write $h$ as a linear combination of a different free basis of $F$, we multiply the vector $(l_1,\ldots,l_n)$ by the change of basis matrix, which is an $n \times n$ matrix with integer entries (and determinant $\pm1$). So the coeffiecients with respect to the new basis are still all divisible by $d_1$.
To avoid talking about a change of basis matrix explicitly,let $z_1,z_2,\ldots,z_n$ be an arbitrary free basis of $F$. Then each $y_i$ can be expressed as a linear combination of the $z_j$, say $y_i = \sum_{j=1}^n \alpha_{ij}z_j$. So then $$h = \sum_{i=1}^n l_i y_i =
\sum_{j=1}^n(\sum_{i=1}^n l_i\alpha_{ij})z_j,$$
and since each $l_i$ is divisible by $d_1$, it follows that the coefficients of $h$ when expressed as a linear combination of the $z_i$ are also divisible by $d_1$.
So $S \le \langle d_1 \rangle$ as required.
Comment: For your question about linear independence of the new free basis, you have already observed that $m_1=0$, so yes $m_1r+m_j=0 \Rightarrow m_j=0$.
Comment: The fact that $d_1$ divides every $l_i$ is used in the change of basis argument.
Comment: I have some questions: (1) In the second paragraph, you meant $k_j = rd_1 + s$ with $0 < s < d_1$, didn't you? In fact, if $s = 0$, then $d_1$ divides $k_j$ which is the opposite of what we're assuming (for the sake of contradiction). Same thing in the third paragraph with $l_1 = rd_1 + s$. (2) Why is $\{y_1',y_2,\dots,y_n\}$ a linearly independent set? I tried to verify this, but $m_1(y_1 + ry_j) + m_2y_2 + \dots + m_ny_n = 0$ with $m_1,\dots,m_n \in \mathbb{Z}$ implies $m_i = 0$ for all $1 \leq i \leq n$ with $i \neq j$ and $m_1r + m_j = 0$, which doesn't imply $m_j = 0$, or does it?
Comment: (3) I see what you mean with the change of basis matrix, but aren't we talking about free abelian groups? I see how such matrices are related to vector spaces in linear algebra, but my abstract-algebra professor has never defined them during the lectures, in the context of finitely generated free abelian groups, so I'd rather use an alternative method...
Comment: I have edited the answer and written the change of basis argument out explicitly. (In fact I prefer to think of the whole of the proof in my answer as a sequence of matrix operations, but I have written it out in terms of operations on  free bases.)
Comment: Yeah, you're right, I wasn't considering that $m_1 = 0$. But wait, I'm just realizing something... Isn't just the third paragraph enough to prove the statement? I don't understand why you're proving that every coefficient $l_i$ is divided by $d_1$, isn't it sufficient to prove that $l_1$ is divided by $d_1$? And we don't need to change the basis, do we?
Comment: In fact, we start with an element $s \in S$ and, by definition of $S$, we have that $sy_1 + k_2y_2 + \dots + k_ny_n \in G$ for some basis $\{y_1,\dots,y_n\}$ and for some $k_2,\dots,k_n \in \mathbb{Z}$. We only need to prove that $s \in \langle d_1 \rangle$, am I missing something?
Comment: Just realized we need the change of basis because $g$ and $h$ may be written in two different basis initially, but it's still not clear why we need to prove that every coefficient $l_i$ is divided by $d_1$.


Value of $E\left[ \frac{X_1 +\cdots + X_k}{X_1 + \cdots + X_n} \right]$ if $X_1, \ldots , X_n$ are i.i.d. random variables

Question:
Let $X_1, \ldots , X_n$ be independent and identically distributed random variables. Calculate: $$E\left[ \frac{x_1 + \cdots + x_k}{x_1 + \cdots + x_n} \right]$$

I was wondering if I went about this the right way.
$$E \left[ \frac{x_1 + \cdots + x_k}{x_1 + \cdots + x_n} \right]$$
$$= \frac{E[x_1 + \cdots + x_k]}{E[x_1 + \cdots + x_n]}, \text{ since each is i.i.d } \implies $$
$$\frac{\mu_1 + \cdots + \mu_k}{\mu_1 + \cdots + \mu_n}$$
$$= \frac{k\mu}{n\mu} = \frac{k}{n}$$
$$= 0 \text{ if $k = n$ and }\frac{k}{n} \text{ if n > k}$$
Comment: Shouldn't your first displayed equation involve $n$?
Comment: Your last line, implying $k/n=0$ if $k= n$, is a mistake.
Comment: That's right I typed that incorrectly
Comment: You wrote: "Let $X_1,\ldots,X_n$ be independent and identically distributed random variables." But then instead of $\displaystyle \operatorname E\left[ \frac{X_1+\cdots+X_k}{X_1+\cdots + X_n } \right]$ you wrote $\displaystyle \operatorname E\left[ \frac{x_1+\cdots+x_k}{x_1+\cdots + x_n }\right].$ That is not proper usage. If it is followed, how will one understand an expression like $\Pr(X\le x) \text{ ?} \qquad$
Comment: Question is incomplete; it should mention conditions for which $E\left[\frac{\sum_{i=1}^k X_i}{\sum_{i=1}^n X_i}\right]$ exists. See the discussions [here](https://math.stackexchange.com/q/852890/321264) and [here](https://math.stackexchange.com/questions/2420091/find-expectation-of-fracx-1-cdots-x-mx-1-cdots-x-n-when-x-1-l?rq=1) for example. Did you mean to ask this same question?
Answer: It is unfortunately not true that $E[X/Y]=E[X]/E[Y]$ even if $X$ and $Y$ are independent.
However, we can show that
$$\tag{*}
\mathbb E\left[\frac{X_j}{X_1+\dots+X_n}\right]=\mathbb E\left[\frac{X_1}{X_1+\dots+X_n}\right]=a.
$$
(this is due to the fact that $(X_1,\dots,X_n)$ and $(X_{\sigma(1)},\dots,X_{\sigma(n)})$, where $\sigma$ is a permutation, have the same law and $\sum_{i=1}^nX_{\sigma(i)}= \sum_{i=1}^nX_i$.
Also, note that $na=1$, by summing over $j$ in (*).
Comment: It is not instantly clear to me what distributions for $X_1$ are such that the expectations in (*)  exist.
Comment: @kimchilover The obvious ones are where $X_1 > 0$ a.s. or $X_1 < 0$ a.s.  That's not a necessary condition.  But on the other hand, if $X_1$ has a continuous density that is nonzero at some points $> 0$ and some points $< 0$, $X_1 + \ldots + X_n$ will have nonzero density at $0$ for some $n$.


Mean of $X_t = \epsilon_t\epsilon_{t-1}$

Question:
Consider the following stochastic process: $$X_t =  \epsilon_t\epsilon_{t-1},~~~~~~~~~\epsilon_t \sim N(0, \sigma^2)$$
Determine whether the process is covariance-stationary, strictly
  stationary, integrated of order one or neither of these.

I have some problems with the mean of this model:
$$E(X_t)=E(\epsilon_t\epsilon_{t-1})$$
The expectation is given by:
$$E(X_t)=\gamma(1)$$
$$\text{or}$$
$$E(X_t)=E(\epsilon_t)E(\epsilon_{t-1})=0 ~~~???$$

If $\epsilon_t$ had been distributed as a $WN(0, \sigma^2)$, there would have been some differences in the expectation of $X_t$? or would the result have been the same?
Answer: When noise is Gaussian and independent and identically distributed (i.i.d.)
$$ \mathbb{E}[\epsilon_t \epsilon_{t-1}] =  \mathbb{E}[\epsilon_t]  \mathbb{E}[\epsilon_{t-1}]= 0 $$
since $\epsilon_t$ and $\epsilon_{t-1}$ uncorrelated.
Also note that $\gamma(1)=\mathbb{E}[X_t X_{t-1}] = \mathbb{E}[\epsilon_t \epsilon_{t-1}\epsilon_{t-1} \epsilon_{t-2}] $ and that also happens to be equal to $$\mathbb{E}[\epsilon_t] \sigma^2 \mathbb{E}[\epsilon_{t-2}]=0$$


Multipart/related API request using JMeter

Question: How to copy a pdf file content into a variable and then upload it as a multipart/related API request using JMeter??
Answer: In order to read the file inline or save it into a JMeter Variable people normally use __FileToString() function however it might not work for PDF files because they're binary so you might want to additionally convert it into Base64, the __base64Encode()  can be found in Custom JMeter Functions bundle which in its turn can be installed using JMeter Plugins Manager
In general I would suggest recording your file upload request using JMeter's HTTP(S) Test Script Recorder, just remember to copy the PDF file you will be uploading to "bin" folder of your JMeter installation otherwise JMeter will fail to capture the request properly.


Is it possible to have an local instance of Azure Key Vault?

Question: I'm currently working on a solution in C# which will integrate the Azure Key Vault.
If the internet goes down -- I work in Berlin, so not entirely unlikely -- or if I want to rule out network connectivity problems when debugging a solution, is there a way I can set up a local instance?
Comment: No new logic is needed but you need to bind the certificate check this [out](https://dotnetplaybook.com/custom-local-domain-using-https-kestrel-asp-net-core/') , if you cant get the copy of certificate file from azure then use the default dev certificate use the CLIs to enforce secure http
Comment: [this](https://learn.microsoft.com/en-us/aspnet/core/security/authentication/certauth?view=aspnetcore-5.0) will help you out.
Comment: @Manti_Core, cheers for the information... this looks a lot more involved than simply spinning up a local instance of a vault and changing a Uri to look at localhost instead of azure.  If you have time to give a more detailed overview about what needs to be done and what should be expected, it will be appreciated.  :-)
Comment: What is the key vault is holding, like connection details to a DB, cache?
Comment: @Manti_Core, hypothetically, it could be anything which the Vault may store.  But for my immediate need, I'll be storing text files with RSA private keys as "Secrets" (or possibly "Certificates", but I'm finding it problematic to save them this way).
Comment: you could install certs in your local machine and host an instance give physical path to your project and bind to locally installed certificate or even running kestrel has some cli commands to run with local certs, I don't think doing this for a temporary outage of internet is good.
Comment: @Manti_Core, sometimes I also like to be able to rule out network problems as a reason for things failing.  But wouldn't I need different logic to access certificates from my local machine instead of the Key Vault if I don't have a local instance of the Key Vault?  I'd prefer a solution where I don't need alternative logic.
Answer: I had/have a similar issue, needing a local stub of Azure Key Vault. Just like you, I have found none, so decided to roll my own. It is work in progress, but Key and Secret support is already at MVP state.
As long as spinning up a Docker container is not an issue for you, it might be worth a try.
Please check it out and save it for later if you find it useful: https://github.com/nagyesta/lowkey-vault
Answer: No, the reason is in the name: Azure Key Vault.
But you can setup your code to acquire credentials via a fallback mechanism when running in development mode, e.g. via user secrets.
Comment: Is there any way to store files, certificates, or such in "user secrets"?
Comment: UserSecrets is a Json document, so yes if you encode it properly, you can store binary data there. You could also create some local config provider that can load certificates locally if Azure key vault is not available. You can also confiure using environment (Development/Production) to use different configuration sources.
Comment: Would it be possible to configure using different configuration sources with minimal or no branching code, so that the behaviour of a production instance is not substantially different from a developer instance?  What would such a configuration look like?
Answer: As others have said, there's no local standalone software Key Vault, but if you're really interested in making this happen, you have options:

Azure Key Vault is a part of the on-prem Azure Stack Hub which you could host on-prem.

Roll your-own encrypted database with a front-end REST web service.

I don't recommend either of these.
Comment: AFAIK it is not possible to isolate the Key Vault from the Stack.  There is the ASDK which can be run on a single node (https://learn.microsoft.com/en-us/azure-stack/asdk/asdk-what-is?view=azs-2102) but it recommends 256Gb RAM. This is not a simple solution.
Comment: Do we need to host the entire stack hub to host an on-prem azure key vault?  Would we be able to put this on our developer machine (possibly in a VM) without making it grind to a halt?  What might you recommend?
Comment: 256Gb RAM!?!  Wow!  Ouch!


Anyone know what the symbols on the right of the wp7 in debug are all about?

Question: Thias is a screenshot of the right hand side of the application in the emulator, these also appear when I deploy to the phone device. what are they, are they supposed to be there?
Answer: The values are stats like frame rate count, and info about cpu and memory usage.
You often keep them on during debugging but turn them off for release.
This is best done in the constructor of the App clas e.g.
<code>/// <summary>
    /// Constructor for the Application object.
    /// </summary>
    public App()
    {
        // Global handler for uncaught exceptions.
        UnhandledException += Application_UnhandledException;

        // Phone-specific initialization
        InitializePhoneApplication();

        // Standard Silverlight initialization
        InitializeComponent();

        // XNA initialization
        InitializeXnaApplication();

        DispatcherHelper.Initialize();

        // Show graphics profiling information while debugging.
        if (System.Diagnostics.Debugger.IsAttached)
        {
            // Display the current frame rate counters.
            Application.Current.Host.Settings.EnableFrameRateCounter = true;

            // Show the areas of the app that are being redrawn in each frame.
            //Application.Current.Host.Settings.EnableRedrawRegions = true;

            // Enable non-production analysis visualization mode,
            // which shows areas of a page that are handed off to GPU with a colored overlay.
            //Application.Current.Host.Settings.EnableCacheVisualization = true;

            // Disable the application idle detection by setting the UserIdleDetectionMode property of the
            // application's PhoneApplicationService object to Disabled.
            // Caution:- Use this under debug mode only. Applications that disable user idle detection will continue to run
            // and consume battery power when the user is not using the phone.
            PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
        }

        //set up the tile
        //StartSearchAgent();
        //ScheduledActionService.LaunchForTest("shottracker", TimeSpan.FromSeconds(1));
    }
</code>
So you set the EnableFrameRateCounter to false etc.
Detailed info about the values can be found here
Frame Rate Counters


couchdb as "briefcase": replication and/or database dumps?

Question: I have a need to migrate some CouchDB database data back and forth between two desktop computers at different locations. One of the computers is Windows XP, one is a Macintosh running OS X 10.5. Neither can realistically connect to the other via the internet (the PC has a firewall, the Mac doesn't have fast internet access). But I do have a USB thumb drive I take back and forth.
Is there a way to do a database dump (like mysqldump for MySQL) for CouchDB so I can export from one and import to the other? I read about database replication but it seems to be only between two live databases that can talk to each other. I can copy the raw database files but I am not sure what version of CouchDB the PC is running (it's whatever the latest native windows CouchDB installer is, it tells me 0.0.0), the Mac is running the most recent version of CouchDBX, and I'm not sure the file versions are compatible.
The replication & versioning features of CouchDB are very intriguing for my application so I am looking forward to getting this set up.
edit: it seems like you either need:

couchdb replicating directly to another (or the same) couchdb server
couchdb database files from the same version of couchdb
couchdb-python tools ("couchdb-dump" and "couchdb-load") but I can't get them to work reliably on WinXP+Python 2.6.2 for some reason (dump 'works' but load says it fails integrity check)

This is really frustrating. :/
Answer: There have been some experimental binaries released for Windows but it is very early days for Windows versions of CouchDB - expect some issues if you are doing a Windows install.
I'm guessing you have the Mac at home and maybe Windows at work behind a corporate firewall. The firewall shouldn't block port 80. If you can telnet to the Mac's IP address on port 80 from the PC, replication should be possible via port 80.
Alternatively, couchdb-python includes the couchdb-dump utility. If you are running couchdb 0.9.1, you will need couchdb-python 0.6.0 to work with couchdb.
couchdb-dump --version   will confirm your couchdb-python version
Something like:
couchdb-dump http://localhost:5984/prod > 20090724.dump
will dump a database named prod from couchdb running on the default port into a serialized file named 20090724.dump. It will list the id of each document it is outputtting and also any design documents.
With couchdb 0.9.1 and couchdb-python 0.6.0, this should all work well on OS X (I've just tried it on my Leopard machine). I'd suggest getting this setup on the Mac and confirming the steps before then looking at the windows equivalent.
Answer: One of the concepts of Couch DB is having disconnected replicas of information, just like the offline Notes databases supported distributed information management. It is therefore probably a common situation to have a disconnected dataset in one CouchDB instance replicating it then and now against other server instances.
In this configuration your application may deal with changes in either systems, it will at least detect conflicts and gives you a chance to deal with them. It is exactly this scenario i'm currently experimentig with to have a common set of information on both my mostly disconnected laptop and my "server" at home.
Comment: please tell me if you find a solution.
Answer: Couchfuse may be an option you are interested in.
"Couchfuse is a FUSE filesystem that exposes Couchdb databases as filesystem folder."


What to write in the function so that the sorting is by condition?

Question: I am writing a swiftui application using firebase. Documents are now sorted by publication date. It is necessary that documents that contain a non-empty upPostPlusDay array in the Firebase database are shown in the first place. Here is the code.
Model for writing data to the Post database:
import SwiftUI
import FirebaseFirestoreSwift

struct Post: Identifiable, Codable, Equatable, Hashable {
    @DocumentID var id: String?
    var text: String
    var postHead: String
    var postAddress: String
    var imageURL: URL?
    var imageReferenceID: String = ""
    var publishedDate: Date = Date()
    var likedIDs: [String] = []
    var dislikedIDs: [String] = []
    var plusFavorites: [String] = []
    var upPostPlusDay: [Int] = []
    var userName: String
    var userUID: String
    var userProfileURL: URL
    var userBioLink: String

    enum CodingKeys: CodingKey {
        case id
        case text
        case postHead
        case postAddress
        case imageURL
        case imageReferenceID
        case publishedDate
        case likedIDs
        case dislikedIDs
        case plusFavorites
        case upPostPlusDay
        case userName
        case userUID
        case userProfileURL
        case userBioLink
    }
}

Output code to user:
import SwiftUI
import Firebase

struct ReusablePostViewContentView: View {
    var basedOnUID: Bool = false
    var uid: String = ""
    @Binding var posts: [Post]
    @State private var isFetching: Bool = true
    @State private var paginationDoc: QueryDocumentSnapshot?
    var body: some View {
        ScrollView (.vertical, showsIndicators: false) {
            LazyVStack {
                if isFetching {
                    ProgressView()
                        .padding(.top, 30)
                } else {
                    if posts.isEmpty {
                        Text("No posts")
                            .font(.caption)
                            .foregroundColor(.gray)
                            .padding(.top, 30)
                    } else {
                        Posts()
                    }
                }

            }
            .padding(15)
        }
        .refreshable {
            guard !basedOnUID else {return}
            isFetching = true
            posts = []
            paginationDoc = nil
            await fetchPosts()
        }
        .task {
            guard posts.isEmpty else {return}
            await fetchPosts()
        }
    }
        @ViewBuilder
    func Posts() -> some View {
        ForEach (posts) { post in
            PostCardViewContentView(postDog: post) { updatedPost in
                if let index = posts.firstIndex(where: { post in
                    post.id == updatedPost.id
                }) {
                    posts[index].likedIDs = updatedPost.likedIDs
                    posts[index].dislikedIDs = updatedPost.dislikedIDs
                }
            } onDelete: {
                withAnimation(.easeInOut(duration: 0.25)) {
                    posts.removeAll {post.id == $0.id}
                }
            }
            .onAppear {
                if post.id == posts.last?.id && paginationDoc != nil {
                    Task {await fetchPosts()}
                    // print("fetch new posts")
                }
            }

            Divider()
                .padding(.horizontal, -15)

        }
    }
    func fetchPosts() async {
        do {
            var query: Query!
            if let paginationDoc {
                query = Firestore.firestore().collection("Posts")
                    .order(by: "publishedDate", descending: true)
                    .start(afterDocument: paginationDoc)
                    .limit(to: 5)
            } else {
                query = Firestore.firestore().collection("Posts")
                    .order(by: "publishedDate", descending: true)
                    .limit(to: 5)
            }

            if basedOnUID {
                query = query.whereField("userUID", isEqualTo: uid)
            }

            let docs = try await query.getDocuments()
            let fetchedPosts = docs.documents.compactMap { doc -> Post? in
                try? doc.data(as: Post.self)
            }
            await MainActor.run(body: {
                posts.append(contentsOf: fetchedPosts)

                paginationDoc = docs.documents.last

                isFetching = false
            })
        } catch {
            print(error.localizedDescription)
        }
    }
}

Help me please.
Answer:
It is necessary that documents that contain a non-empty upPostPlusDay array in the Firebase database are shown in the first place

There is no clause that you can add to a Firestore query to get documents with a specific non-empty array first, while also getting all other documents.

The solution is (as usual when working with NoSQL databases) to change/expand your data model to allow the use-case.
For example, if you add a field upPostPlusDayValueCount to each document, and keep an up-to-date count in that field, you can sort on descending upPostPlusDayValueCount to get the documents with a non-empty upPostPlusDay array at the start of the results.


SOLVED - IPTables INPUT DROP and Port Opening

Question: I'm hosting a Mail Server (PostFix, PostFix Admin, Dovecot), a Minecraft Server and a Discord bot,
I'm trying to create a firewall with INPUT and OUTPUT drop, however with this configuartion, everything stop working, example also with the port 143 open my roundcube cannot connect to the imap server, same for the minecraft server, I load the 25565 port but it stop there and the discord bot cannot connect to discord servers (should be http), while if I put OUTPUT DROP it just stop every connection also my ssh (custom port 2233).
Any help?
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:imap2
ACCEPT     udp  --  anywhere             anywhere             udp dpt:1988
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:1988
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http-alt
ACCEPT     udp  --  anywhere             anywhere             udp dpt:http-alt
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:8192
ACCEPT     udp  --  anywhere             anywhere             udp dpt:8192
f2b-sshd   tcp  --  anywhere             anywhere             multiport dports ssh
bungee     tcp  --  anywhere             anywhere             tcp dpt:25562
bungee     tcp  --  anywhere             anywhere             tcp dpt:25579
bungee     tcp  --  anywhere             anywhere             tcp dpt:25569
bungee     tcp  --  anywhere             anywhere             tcp dpt:25563
bungee     tcp  --  anywhere             anywhere             tcp dpt:25567
bungee     tcp  --  anywhere             anywhere             tcp dpt:41310
bungee     tcp  --  anywhere             anywhere             tcp dpt:41311
bungee     tcp  --  anywhere             anywhere             tcp dpt:41312
bungee     tcp  --  anywhere             anywhere             tcp dpt:25999
bungee     tcp  --  anywhere             anywhere             tcp dpt:25564
bungee     tcp  --  anywhere             anywhere             tcp dpt:30801
bungee     tcp  --  anywhere             anywhere             tcp dpt:30802
bungee     tcp  --  anywhere             anywhere             tcp dpt:30803
bungee     tcp  --  anywhere             anywhere             tcp dpt:30810
bungee     tcp  --  anywhere             anywhere             tcp dpt:25342
ACCEPT     udp  --  anywhere             anywhere             udp dpt:8183
ACCEPT     udp  --  anywhere             anywhere             udp dpt:8182
ACCEPT     udp  --  anywhere             anywhere             udp dpt:8181
ACCEPT     udp  --  anywhere             anywhere             udp dpt:8191
ACCEPT     udp  --  anywhere             anywhere             udp dpt:587
ACCEPT     udp  --  anywhere             anywhere             udp dpt:465
ACCEPT     udp  --  anywhere             anywhere             udp dpt:2233
ACCEPT     udp  --  anywhere             anywhere             udp dpt:25
ACCEPT     udp  --  anywhere             anywhere             udp dpt:143
ACCEPT     udp  --  anywhere             anywhere             udp dpt:993
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:imaps
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:imap2
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http-alt
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:25565
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:submission
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:urd
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:8191
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:8183
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:8182
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:8181
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:smtp
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:2233
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:imap2
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:8443
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http-alt
ACCEPT     tcp  --  anywhere             anywhere             state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:2233
ACCEPT     udp  --  anywhere             anywhere             udp dpt:2233
ACCEPT     udp  --  anywhere             anywhere             udp dpt:25
ACCEPT     udp  --  anywhere             anywhere             udp dpt:143
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:imap2
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:25565
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:imaps
ACCEPT     udp  --  anywhere             anywhere             udp dpt:993
ACCEPT     udp  --  anywhere             anywhere             udp dpt:25565
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:urd
ACCEPT     udp  --  anywhere             anywhere             udp dpt:465
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:smtp state NEW,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:imap2 state NEW,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:imaps state NEW,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:urd state NEW,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:submission state NEW,ESTABLISHED

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     udp  --  anywhere             anywhere             udp dpt:8183
ACCEPT     udp  --  anywhere             anywhere             udp dpt:8182
ACCEPT     udp  --  anywhere             anywhere             udp dpt:8181
ACCEPT     udp  --  anywhere             anywhere             udp dpt:8191
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:8191
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:8183
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:8182
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:8181
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:25565
ACCEPT     udp  --  anywhere             anywhere             udp dpt:25565
ACCEPT     udp  --  anywhere             anywhere             udp dpt:465
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:urd
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:imap2
ACCEPT     udp  --  anywhere             anywhere             udp dpt:143
ACCEPT     udp  --  anywhere             anywhere             udp dpt:993
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:imaps
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:2233
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http-alt
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:smtp
ACCEPT     udp  --  anywhere             anywhere             udp dpt:25
ACCEPT     udp  --  anywhere             anywhere             udp dpt:443
ACCEPT     udp  --  anywhere             anywhere             udp dpt:http-alt
ACCEPT     udp  --  anywhere             anywhere             udp dpt:80
ACCEPT     udp  --  anywhere             anywhere             udp dpt:2233
ACCEPT     tcp  --  anywhere             anywhere             tcp spt:smtp state ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp spt:imap2 state ESTABLISHED

Chain bungee (15 references)
target     prot opt source               destination
ACCEPT     all  --  vmi294204.contaboserver.net  anywhere
ACCEPT     all  --  localhost            anywhere
DROP       all  --  anywhere             anywhere

Chain f2b-sshd (1 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere

Answer: You are missing some standard firewall rules, which are almost in every ruleset:
iptables -I INPUT 1 -i lo -j ACCEPT
iptables -I INPUT 2 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

You certainly want to allow all communication over the loopback device (it is coming from the server itself) and to allow every established connection (you already accepted it once). These rules are usually the first once for performance reasons.
In your OUTPUT chain you have all ports in the wrong direction (--dport instead of --sport).
It is very unusual to set DROP as OUTPUT's policy and it requires a good knowledge of how your services and the system work.
You already noticed the missing ACCEPT rule for ssh[*] and you probably want to add similar rules to OUTPUT as the once I gave for INPUT. However you didn't think about name resolution:
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT

and DHCP (if you are using it). Moreover ICMP is almost a must:
iptables -A INPUT -p icmp -j ACCEPT
iptables -A OUTPUT -p icmp -j ACCEPT

since it isn't just used by ping, but gives important diagnostic information like "No route to host". Without them your services will wait until the timeout, every time a network error occurs.
PS: use the multiport and comment modules to make your rules more readable, e.g.:
iptables -A INPUT -m multiport --dports smtp,465,submission -m comment --comment postfix -j ACCEPT

TL;DR: Switching your OUTPUT policy to DROP is not very useful and requires a good knowledge of how every service you use works.
[*] After rereading your question, your are running ssh on another port and you thought about allowing ssh return packets, but you used --dport like in all other rules. What I don't understand is why are you running a fail2ban jail for ssh on port 22 if there is nothing listening there.


How to prove that $\mathscr{cl}(X\setminus A)\cap X\setminus\mathscr{cl}(B)\subseteq\mathscr{cl}(X\setminus A\cap X\setminus B)$?

Question: To prove the assertion I attempt two different way: but unfortunately both seem inconclusive. Below you can read the two different "demonstration".

$B\subseteq\mathscr{cl}(B)\Rightarrow X\setminus\mathscr{cl}(B)\subseteq X\setminus B\Rightarrow \mathscr{cl}(X\setminus A)\cap X\setminus\mathscr{cl}(B)\subseteq\mathscr{cl}(X\setminus A)\cap X\setminus B$ and now if $\mathscr{cl}(X\setminus A)\cap X\setminus B\subseteq\mathscr{cl}(X\setminus A\cap X\setminus B)$ the proof would be complete, but unfortunately I'm not able to demostrate this last passage.
$x\in\mathscr{cl}(X\setminus A)\cap X\setminus\mathscr{cl}(B)\Rightarrow x\in \mathscr{cl}(B)\wedge x\in X\setminus\mathscr{cl}(B)\Rightarrow x\in \mathscr{cl}(X\setminus A)\wedge x\notin\mathscr{cl}(B)\Rightarrow\{\forall V_x\in\mathcal{V}(x):V_x\cap X\setminus A\neq\varnothing\}\wedge\{\exists V_x\in\mathcal{V}(x):V_x\cap B=\varnothing\}\Rightarrow\{\nexists V_x\in\mathcal{V}(x):V_x\subseteq A\}\wedge\{\exists V_x\in\mathcal{V}:V_x\subseteq X\setminus B\}\Rightarrow\{\nexists V_x\in\mathcal{V}(x):V_x\subseteq A\}\wedge x\in X\setminus B$ and if from $\{\nexists V_x\in\mathcal{V}(x):V_x\subseteq A\}$ I could argue that $x\in X\setminus A$ the proof would be complete, but I fear that this is generally false.

Could someone help me, please?
Comment: The value of the RHS in the title is ambiguous due to a shortage of brackets.
Answer: Let $X$ be a topological space. Let $A,B\subseteq X$. We go to show
that $\overline{A^{c}}\cap(\overline{B})^{c}\subseteq\overline{A^{c}\cap B^{c}}$.
Here $A^{c}=X\setminus A$ and $\overline{A}$ denotes the closure
of $A$.
To simplify notation, we denote $C=A^{c}$. Hence, we need to show
that $\overline{C}\cap(\overline{B})^{c}\subseteq\overline{C\cap B^{c}}$.
Let $x\in\overline{C}\cap(\overline{B})^{c}$ be arbitrary. Since
$x\in\overline{C}$, there exists a net $(x_{\alpha})$ with $x_{\alpha}\in C$
such that $x_{\alpha}\rightarrow x$. Note that $(\overline{B})^{c}$
is an open neighborhood for $x$, so there exists $\alpha_{0}$ such
that $x_{\alpha}\in(\overline{B})^{c}$ whenever $\alpha\geq\alpha_{0}$.
Since $B\subseteq\overline{B}$, we have $(\overline{B})^{c}\subseteq B^{c}$.
Therefore, for any $\alpha\geq\alpha_{0}$, we have $x_{\alpha}\in C\cap B^{c}$.
Hence $(x_{\alpha})_{\alpha\geq\alpha_{0}}$ is a net in $C\cap B^{c}$
and $x_{\alpha}\rightarrow x$. It follows that $x\in\overline{C\cap B^{c}}$.
///////////////////////////////////////////////
We can also prove directly without using the notion of "net".
To prove: $\overline{C}\cap(\overline{B})^{c}\subseteq\overline{C\cap B^{c}}$.
Let $x\in\overline{C}\cap(\overline{B})^{c}$. Let $U$ be an arbitrary
open neighborhood of $x$. Note that $(\overline{B})^{c}$ is open
and contains $x$, so $U\cap(\overline{B})^{c}$ is also an open neighborhood
of $x$. Since $x\in\overline{C}$, we have $C\cap\left( U\cap(\overline{B})^{c}\right)\neq\emptyset$. Observe that $(\overline{B})^{c}\subseteq B^{c}$, so $\emptyset\neq C\cap U\cap(\overline{B})^{c}\subseteq C\cap U\cap B^{c}$.
This shows that $C\cap B^{c}$ intersects with every open neighborhood
of $x$ and hence $x\in\overline{C\cap B^{c}}$.
Answer: Direct approach to
$$\operatorname{cl}(X\setminus A)\cap (X\setminus\operatorname{cl}(B)) \subseteq \operatorname{cl}((X\setminus A)\cap (X\setminus B))\tag{1}$$
could be: Pick $x$ in the left hand side of $(1)$. So $x \notin \operatorname{cl}(B)$ so there is some open neighbourhood $U_x$ of $x$ that misses $B$. And if $O$ is open neighbourhood of $x$, so is $O \cap U_x$ and this set intersects $X \setminus A$ (because of $x \in \operatorname{cl}(X \setminus A)$) and is contained in $X \setminus B$ (as $U_x$ is), so $O \cap U_x$ (and hence $O$ too) intersects $(X\setminus A)\cap (X\setminus B)$, and as $O$ was arbitrary, $x$ is in the right hand side of $(1)$. QED.
Tip: don't lose yourself in formalism and logical fanciness and just first reason about points and their relations to subsets, closures etc. It might give you an idea why the statement holds.


Simple RoR relationship in the view

Question: I am studying Ruby on Rails and I am trying to make this simple blog system using devise to create the login part.
This question must have a very simple answer, but I cannot find it using google, so I finally gave up and decided to ask it here.
I have a Users table created by devise and a Posts table created by a scaffold command.
The Posts table has a user_id field. In the creation of a post, I use this code:
  def create
    @post = Post.new(params[:post])
    @post.user_id = current_user.id

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render json: @post, status: :created, location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

This way I get the user id and create this relationship.
This is my Post model:
class Post < ActiveRecord::Base
  attr_accessible :body, :title, :user_id

  belongs_to :user

end

Now, all I want is to show the name of the author in the list method.
I tried several things and none seem to get things done.
How do I link the user name to the post instead of the user id?
My current index method is the standard one:
  def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end
  end

I know I need to add parameters in that Post.all thing, but how?
Thanks!
Note: I use rails 3 and PostgreSQL.
Answer: You can access the user object through the relationship:
@post.user.name

If you want to eager load the relationship, you can change your @posts = Post.all statement to the following:
@posts = Post.includes(:user)

Answer: Assuming the user name is in User#name, you can display it by adding something like this to your view:
<%= post.user.name %>

Your posts/index.html.erb view probably has some code ala
<% @posts.each do |post| %>

    <%= post.name %>
    ...

<% end %>

Adding another table cell with the author name could make it look like:
<% @posts.each do |post| %>

    <%= post.name %>
    <%= post.user.name %>

<% end %>

Comment: I would also tweak the controller slightly to do `Post.includes(:user).all`, to avoid n+1 SQL queries (two SQL queries. instead of one query for each row when fetching the user name.)

Simple RoR relationship in the view


.htaccess file not working on localhost XAMPP

Question: I have PHP project on localhost using XAMPP and also .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /locations/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /test.php [L]
</IfModule>

But this is not working and I am only getting Error 404. In httpd.conf file I have uncommented this line:
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
AllowOverride All

I am using Windows 8.1. What can I do to make it work, please?
Comment: C:\xampp\htdocs\myProjectRoot
Comment: Because I wanted to redirect url - when I request localhost/myProjectRoot/locations/  I want to redirect to localhost/myProjectRoot/test.php. It is working well on production server version, but not on localhost because of this .htaccess problem, I guess.
Comment: But I dont have locations folder, I want this : when user type localhost/myProjectRoot/locations/ it will 'redirect' him to localhost/myProjectRoot/test.php. So it will instead request this php file. But I tried also create folder locations and place there this .htaccess but it did not work.
Answer: You can use this rule in root .htaccess:
RewriteEngine On
RewriteBase /

RewriteRule ^locations(/.*)?$ test.php [L,NC]

Comment: I enabled .htaccess by removing Require all denied from Apache config file. It works and I am getting error 500. But this .htaccess is still not working as I need to (redirection).
Comment: And also, what should I add, If I need to redirect everything url with every string after "localhost/myProjectRoot/locations/" to test.php. For example localhost/myProjectRoot/locations/123456 will go to localhost/myProjectRoot/test.php
Comment: And also, what should I add, If I need to redirect everything url with every string after "localhost/myProjectRoot/locations/" to test.php. For example localhost/myProjectRoot/locations/123456 will go to localhost/myProjectRoot/test.php
Answer: using XAMPP then you will find the file at:
{xampp_dir}/apache/conf/httpd.conf
Search for the following string:
LoadModule rewrite_module modules/mod_rewrite.so
and uncomment it (remove the '#' sign).
Now search for another string AllowOverride None and replace it by AllowOverride All
Comment: I did it, but unfortunatelly after restarting Apache, nothing changed.


Mascara de porcentagem com o react-input-mask no react js com typescript

Question: tenho que criar uma mascara para um input no projeto já estamos utilizando o react-input-mask https://github.com/sanniassin/react-input-mask#beforemaskedstatechange
A solução não necessariamente precisa utilizar  o React-Input-mask.
Ele adianta muita coisa.
Mas para criar uma mascara dinamica com o simbolo de % que precisa ficar ao lado do numero to levando uma pisa.
aqui tem tem o link de um code sandbox que achei de um cara que criar uma mascara para cpf e cnpj
https://codesandbox.io/s/brava-react-masked-input-8xe2p?file=/src/App.js
tbm estou utilizando o formik
Embaixo como deve ser o campo e a mascara comportamento da máscara.
O campo deve estar em branco para que eu possa inserir A
PORCENTAGEM;
O campo deve aceitar apenas NÚMERO DE acima de 1 até 100, incluindo 100;
O campo aceita somente valores inteiros;
O campo não deve aceitar LETRAS ou caracter especial;
A usuária deve visualizar o simbolo % no campo ao lado do número digitado;
O usuário deve visualizar em tela a PORCENTAGEM inserida;
<Input
        width="auto"
         value={formik.values.beneficiaries[index]["percentage"]}
         name={`beneficiaries.${index}.percentage`}
         id={"percentage" + index}
         optional={false}
         label="Porcentagem"
         mask={"999%"}
         maskPlaceholder={""}
         error={!!(errors.beneficiaries[index] && errors.beneficiaries[index}["percentage"])}
         errorDescription={errors.beneficiaries[index] ? errors.beneficiaries[index]["percentage"]: ""}
         change={formik.handlerChange}
         blur={formik.handleBlur}
         focus={handleOnFocus}
    />

o mask comentado é uma propriedade do react-Input-Mask onde fica o "9" ele especifica que vai receber numero e o % só aparece após digitar os três números, não quero utilizar o jqueryMask, pois já estamos utilizando o React-Input-mask no projeto por ele sé mais "simple".
Pode ser uma solução sem o React-Input-mask. espero ter descrito meu problema bem no aguardo :D
Comment: já tentou assim: ``
Comment: ao fazer isso o input deixa de receber entrada de valores
Answer: pessoal consegui a solução, sem utilizar uma lib apenas utilizando o toLocaleString
https://www.w3schools.com/jsref/jsref_tolocalestring_number.asp
criei uma função
//regexs para converter e mascara.

 const convertMaskPercent = (value: string) => {
  return (parseInt(value.replace(/[^0-9]/g, "")) * 0.01).toLocaleString("pt-BR", { style: "percent" });

};

const removeCharactersAndSpecialCharacter = (value: string) => {
  return value.replace(/[^0-9]/g, "");
};

// mascara campo porcentagem
const handlerChangeMaskPercent = (event: any) => {
    const { name, value } = event.target;

    if (Number.isNaN(parseInt(removeCharactersAndSpecialCharacter(value)))) {
      formik.setFieldValue(name, "");
    } else {
      var newValue = convertMaskPercent(value);
      formik.setFieldValue(name, newValue);
    }
  };

 // limitar valor até 100 é limpar valores maiores
  const onBlurMaskPercent = (event: any) => {
    let {name, value} = event.target
    let parseValue = parseInt(value)
      if(parseValue > 100 || parseValue < 0){
        formik.setFieldValue(name, "");
      }

  };

COMO FICOU O INPUT!

<Input
                                width="auto"
                                value={
                                  formik.values.beneficiaries[index][
                                    "percentage"
                                  ]
                                }
                                name={`beneficiaries.${index}.percentage`}
                                id={"percentage" + index}
                                optional={false}
                                label="Porcentagem"
                                maskPlaceholder={""}
                                error={
                                  !!(
                                    errors.beneficiaries[index] &&
                                    errors.beneficiaries[index]["percentage"]
                                  )
                                }
                                errorDescription={
                                  errors.beneficiaries[index]
                                    ? errors.beneficiaries[index]["percentage"]
                                    : ""
                                }
                                change={handlerChangeMaskPercent}
                                blur={onBlurMaskPercent}
                                focus={handleOnFocus}
                                maxCharacters={4}
                              />

```


Custom mix task not loading test environment

Question: I am attempting to put together a custom mix task that will execute the mix test task in a specialized manner. My mix task is mix test.pretty.
So far, I've written the world's most basic custom mix task:
defmodule Mix.Tasks.Test.Pretty do
  use Mix.Task

  @shortdoc "Simply runs the Hello.say/0 function"
  def run(_) do
    Mix.env(:test)

    Mix.Task.run("test", ["--formatter", "ExPrettyTest.Formatter"])
  end
end

Unfortunately, when I run the task (mix test.pretty) I get this error:

** (RuntimeError) cannot invoke sandbox operation with pool DBConnection.ConnectionPool. To use the SQL Sandbox, configure your
  repository pool as:
pool: Ecto.Adapters.SQL.Sandbox

(ecto_sql) lib/ecto/adapters/sql/sandbox.ex:491: Ecto.Adapters.SQL.Sandbox.lookup_meta!/1
(ecto_sql) lib/ecto/adapters/sql/sandbox.ex:389: Ecto.Adapters.SQL.Sandbox.mode/2
(elixir) lib/code.ex:767: Code.require_file/2
(elixir) lib/enum.ex:765: Enum."-each/2-lists^foreach/1-0-"/2
(elixir) lib/enum.ex:765: Enum.each/2
(mix) lib/mix/tasks/test.ex:369: Mix.Tasks.Test.run/1
(mix) lib/mix/task.ex:316: Mix.Task.run_task/3
(mix) lib/mix/cli.ex:79: Mix.CLI.run_task/2
(elixir) lib/code.ex:767: Code.require_file/2

It appears that the test environment isn't being loaded up--perhaps test_helper.exs hasn't been loaded?
I can run the task like so: MIX_ENV=test mix test.pretty and it works fine. I'd like to get this working w/o having to put MIX_ENV=test in there every time I run the task. In my head, the entire point of having a custom test was to avoid having to specify that environment and the formatter argument manually.
My workflow is to run mix test, if there are errors, I think run mix test.pretty which gives me sweet, awesome test output using the custom formatter mechanism in ExUnit. Once I've nailed down the errors, I can choose to run the file pretty or not, the individual test pretty or not, etc.
Thanks!
Answer: Have you tried setting preferred_cli_env in your mix.exs file?
From:
https://hexdocs.pm/mix/master/Mix.Task.html
Probably something like:
preferred_cli_env: [
  "test.pretty": :test
]

in your def project do ... end
Comment: Nailed it. Thanks a TON.
Comment: No problem :). Just adding this here in case anyone wonders why you couldn't set it from the script. From the documentation: `@preferred_cli_env is not loaded from dependencies as we need to know the environment before dependencies are loaded. `


Cyclotomic Polynomials conceptual question

Question: I was wondering why do we always get an integer coefficient for each variable and constant everytime we compute $\phi_n$ ?
Comment: Do you mean the coefficients of the cyclotomic pol. over the rationals (in fact, over the integers), or about its values? If it is the first then that's a very nice and non-trivial theorem, and if it is the second then it isn't true...
Comment: http://www.math.umn.edu/~garrett/m/algebra/notes/18.pdf;
http://www.maths.lancs.ac.uk/~jameson/cyp.pdf
Answer: Primitive $n$-th roots of unity are algebraic integers.
Hence the coefficients of $\Phi_n$ are algebraic integers.
Since they are rational numbers, they are rational integers because $\mathbb{Z}$ is integrally closed in $\mathbb{Q}$
Answer: It follows from the following formula and induction on n.
$\prod_{d\mid n}\Phi_d(X) = X^n - 1$
Let $g(X) = \prod_{d\mid n, d < n}\Phi_d(X)$.
By the induction hypothesis $g(X) ∈ \mathbb{Z}[X]$ and it is monic.
Hence $\Phi_n(X) = (X^n - 1)/g(X) ∈ \mathbb{Z}[X]$
Answer: There are several ways we can define the Cyclotomic polynomials, for example there are already three in the introduction of this wikipedia page.
Of those three, two make the integer coefficients part of the definition. For the other definition they list: $$\Phi_n(X) =\prod_\stackrel{1\le k\le n-1}{\gcd(k,n)=1}(X-e^{2i\pi\frac{k}{n}})$$
two options I can see are to either prove the formula Makoto used in his answer, or to show that the primitive roots of unity are a Galois conjugate family in the appropriate field extension, and thus the product on the right hand side is their minimal polynomial.


Integrate logarithmic derivative of a periodic function

Question: Given $f$ a $p$-periodic function over $\mathbb{C}$, how to show that :
$$\frac{1}{\mathrm{i}p}\int_a^{a+p}\frac{f'(t)}{f(t)}dt \in \mathbb{Z}$$
Is there any elegant method ?
Comment: In fact, we find $\frac{2\pi}{p}$. Or you sure that $p$ is not something like $p=k\pi$ ?
Comment: @surb : thanks, actually, the question is given with $p=2\pi$ initially and I assumed a wrong generalisation.
Answer: Let $\gamma: [0, 1] \to \Bbb C$ be a path connecting $a$ and $a+p$.
Then
$$
 \int_a^{a+p}\frac{f'(z)}{f(z)} \, dz = \int_0^1 \frac{f'(\gamma(t))\gamma'(t)}{f(\gamma(t))} \, dt
= \int_\Gamma \frac{dw}{w} = 2 \pi i \operatorname{N}(\Gamma, 0)
$$
where $\Gamma = f \circ \gamma$ is a closed path, and $\operatorname{N}(\Gamma, 0)$ is the winding number of $\Gamma$ with respect to zero.
The winding number is an integer (see below), and therefore
$$
 \frac{1}{2 \pi i} \int_a^{a+p}\frac{f'(z)}{f(z)} \in \Bbb Z \, .
$$
Why is the winding number an integer? I am pretty sure that
this has been shown before, but I could not find it anymore, therefore
I try to reproduce an elementary proof here.
For $0 \le s \le 1$, define
$$
 F(s) :=  \int_0^s \frac{\Gamma'(t)}{\Gamma(t)} \, dt \, .
$$
Then verify that the derivative of
$$
  e^{-F(s)}\Gamma(s)
$$
with respect to $s$ is zero. It follows that
$$
 \Gamma(s) = C e^{F(s)}
$$
for some constant $C$. From $\Gamma(0) = \Gamma(1)$ it follows that
$$
 e^{F(0)} = e^{F(1)}
$$
and therefore
$$
  F(1) = F(0) + 2 \pi i k = 2 \pi i k
$$
for some $k \in \Bbb Z$, which is what we wanted to show.

Re your comments: Here is a direct proof for your special case
$a, a+p \in \Bbb R$, using the same ideas, but without integration
along paths in $\Bbb C$:
For $x \in \Bbb R$, define
$$
 F(x) = \int_0^x \frac{f'(t)}{f(t)} \, dt
$$
Then verify that the derivative of
$$
  e^{-F(x)} f(x)
$$
with respect to $x$ is zero. It follows that
$$
  f(x) = C e^{F(x)}
$$
for some constant $C$. From $f(a) = f(a+p)$ it follows that
$$
 e^{F(a)} = e^{F(a+p)}
$$
and therefore
$$
  F(a+p) = F(a) + 2 \pi i k
$$
for some $k \in \Bbb Z$. So we have
$$
\int_a^{a+p} \frac{f'(t)}{f(t)} \, dt = F(a+p) - F(a) = 2 \pi i k \, .
$$
Comment: $f$ is a function with a real variable.
Comment: @servabat: I am confused now. Your question says: "Given $f$ a $p$-periodic function over $\mathbb{C}$." So where is $f$ defined, and what does it map to?
Comment: It has a complex value but a real variable. Else, I don't know how is defined the integral yet.
Comment: @servabat: Well, I have just chosen $z$ as the integration variable because I *assumed* that you consider $f$ in the plane. But everything above  remains correct if you restrict $z$ to be real.
Comment: But then $\gamma$ is just an affine function ? The problem for me is the 3rd equality, I don't understand that part. It seems pretty close to Surb answer, and I think it uses topics I haven't studied yet.
Comment: @servabat: See update. Does that help?
Comment: Indeed, it is intersting, thanks!
Answer: Hint
By periodicity, $$\int_a^{a+p}\frac{f'(t)}{f(t)}\mathrm d t\underset{z=f(t)}{=}\int_{f(a)}^{f(a+p)}\frac{1}{z}\mathrm d z\underset{periodicity}{=}\int_{\gamma }\frac{1}{z}\mathrm d z$$
where $\gamma $ is a closed curve. Using cauchy formula, you can prove the claim.
Comment: Well I don't know the Cauchy formula, is there any alternative ?
Comment: Not really... But you don't know at least that $$\int_\gamma \frac{1}{z}\mathrm d z=\begin{cases}2\pi i& 0\in \text{Int}(\gamma )\\ 0&0\notin \text{Closure}(\text{Int}(\gamma ))\end{cases},$$ where $\gamma $ is a closed (simple) curve ?
Comment: No, I never studied geometry with analysis (closed curves, etc..)
Comment: To my opinion, it's unsolvable without this... let's see if somebody else answer...
Comment: nothing complicated here. by definition of a contour integral, if $\gamma(t),t \in [A,B]$ is a parametrized curve in the complex plane : $\int_\gamma h(z) dz = \int_A^B h(\gamma(t)) \gamma'(t) dt$ so $\int_a^{a+p} \frac{f'(t)}{f(t)} dt = \int_A^B \frac{1}{\gamma(t)} \gamma'(t) dt = \int_\gamma \frac{1}{z} dz$ where $\gamma(t) = f(t), A = a, B = a+p$. $\quad$ what is complicated is that in $\int_\gamma h(z) dz$ we can stretch the contour $\gamma$ as we want, if $h(z)$ is holomorphic (analytic), but in the case of $h(z) = \frac{1}{z}$ it should be possible to show it by elementary means
Comment: @user1952009: The problem is not here ! How do you integrate $\int_\gamma \frac{1}{z}\mathrm d z$ without Cauchy formula ? The final answer is just a factor of this integral. What you say in your previous post doesn't solve the problem.
Comment: and the expected elementary answer to this exercice is that $\int_x^y \frac{f'(t)}{f(t)} dt \simeq \log(f(y))- \log(f(x))$ where all the problem is to choose the correct branch of $\log$. Hence we construct a function $F(t)$ such that $F'(t) = \frac{f'(t)}{f(t)}$ for every $t \in (a,a+p)$, and we see that $F(t) = \log(f(t)) - \log(f(a)) + 2i \pi k$ for some $k \in \mathbb{Z}$ depending on $t$
Comment: @user1952009: you can imagine that if the OP doesn't now cauchy formula, what you wrote will be not understandable for him ! ;-)
Comment: if $G(t) = \ln |f(t)|$ then $G'(t) = Re(f'(t)/f(t))$ and $G(b) - G(a) = \int_a^b Re(f'(t)/f(t)) dt$, so all the problem is to prove that $Im(\int_a^{a+p} f'(t)/f(t) dt) = 2 i \pi k$


Comparar linhas com txt Java Android

Question: Gostaria de criar um metodo que compare cada linha do meu text view com cada linha de um arquivo txt
aqui eu percorro o arquivo txt
por exemplo, no meu text view são exibidos as palavras
azul
verde
amarelo
verde
no meu txt eu tenho
preto
azul
verde
amarelo
gostaria que emitisse um alerta sobre o verde que nao esta no arquivo txt
implementei isso
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); // saida do textview
        BufferedReader entrada = new BufferedReader (new FileReader("bd.txt")); // arquivo txt
        int linha = 1;
        String line = "";
        String line1 = "";
       while ((line1 = entrada.readLine())!= null){
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
                if (line.contains(line1) == true) {

                // o que tem no textview tem no txt

                } else if (line.contains(line1) == false) {

                }

Answer: Você precisa especificar melhor como  as palavras serão escritas no seu arquivo texto e textview. Se serão todas na mesma linha ou cada uma separada por uma quebra de linha.
De qualquer forma, eu fiz uma implementação geral que funcione para os dois casos:
  BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); // saída do textview
  BufferedReader entrada = new BufferedReader(new FileReader("bd.txt")); // arquivo txt

  String line = "";

  String coresTextView = "";
  String coresArquivoTexto = "";

  while((line = reader.readLine()) != null)
    coresTextView = coresTextView + line + " ";

  while((line = entrada.readLine()) != null)
    coresArquivoTexto = coresArquivoTexto + line + " ";

  String[] cores = coresTextView.split(" ");

  for(int i = 0; i < cores.length; i++)
    if(coresArquivoTexto.replaceFirst(cores[i], "").equals(coresArquivoTexto))
      System.out.println("AVISO: " + cores[i] + " não está no arquivo texto!");
    else
      coresArquivoTexto = coresArquivoTexto.replaceFirst(cores[i], "");

  reader.close();
  entrada.close();

Para resolver esse problema você precisa pensar em duas listas: uma com as cores do textview e outra com as cores do seu arquivo texto.
Você vai pegar as cores do textview uma por uma e comparar com toda a lista das cores do seu arquivo texto. Se você encontrar a cor da sua lista do textview na lista de cores do arquivo texto, você pode remover a cor da lista do arquivo texto para não correr o risco de encontrar novamente caso você tenha a mesma cor duas vezes na lista de cores do textview.
Na minha implementação, eu utilizei Strings como as "listas" de cores que eu citei na explicação acima. A String coresTextView pega as linhas do textview e faz uma junção separada por espaços. Depois, separa todas as palavras da String por espaço e joga no vetor de Strings cores. Com isso, eu tenho cada cor do textview em uma posição do meu vetor de Strings cores.
A String coresArquivoTexto é uma String que junta todas as cores encontradas no arquivo texto, separando-as por espaço.
Logo após vem o laço para percorrer todas as cores encontradas no textview. Dentro do laço tem a condição que faz a comparação para ver se a cor está presento no arquivo texto:
if(coresArquivoTexto.replaceFirst(cores[i], "").equals(coresArquivoTexto))

Aqui é uma simples manipulação de String. Se a cor do vetor de String de cores do textview não estiver presente na String de cores do arquivo texto, então a função .replaceFirst vai retornar a String coresArquivoTexto sem nenhuma mudança. Com isso, nós sabemos que a cor não está presente no arquivo texto.
Agora, caso a cor do vetor de Strings de cores do textview estiver presente no arquivo texto, vamos atualizar a String coresArquivoTexto removendo a cor que acabamos de verificar. Fazemos isso associando a variável à função .replaceFirst que deve retornar a String sem a cor passada como parâmetro.
coresArquivoTexto = coresArquivoTexto.replaceFirst(cores[i], "");

E isso faz o trabalho que você quer!
Eu não sei com quantas cores e tamanhos de arquivos texto você pretende trabalhar, pode ser que talvez a variável do tipo String utilizada não suporte tantas palavras do arquivo texto ou textview que você venha a utilizar. Nesse caso, procure trocar o tipo para listas, por exemplo, ou até mesmo associar os nomes das cores a números de 1-9 e você pode ter uma String com milhares de caracteres de códigos que indicam cores.
Obs: Nessa implementação tome cuidado com espaços nos seus arquivos texto e textview, lembre-se que a função .split(" ") vai dividir a String exatamente em um espaço, se você tiver mais de um espaço entre as cores dos seus arquivos, isso pode ocasionar em problemas na execução do programa
Comment: no caso, o arquivo txt ficaria no diretorio assets??
Comment: Na pasta principal do projeto.

Comparar linhas com txt Java Android


Can we set hbase.rpc.protection property value as none in Cloudera Hadoop cluster? If yes then how?

Question: I am using Cloudera Hadoop cluster in which kerberos security is enabled. But in properties file I have mention the hbase.encryption as none. So I need to change the value of property hbase.rpc.protection as none in hbase-site.xml. I tried to set this property value to none but it failed because in Cloudera it shows only authentication, privacy and integrity option.  So does anyone have solution for this? Thanks in advance.
Answer: You can only choose authentication, integrity, or privacy for hbase.rpc.protection.  When it is set to none, it defaults to authentication.  This can be seen in hbase-client/src/main/java/org/apache/hadoop/hbase/security/SaslUtil.java:
  /**
   * @param rpcProtection Value of 'hbase.rpc.protection' configuration.
   * @return Map with values for SASL properties.
   */
  static Map<String, String> initSaslProperties(String rpcProtection) {
    String saslQop;
    if (rpcProtection.isEmpty()) {
      saslQop = QualityOfProtection.AUTHENTICATION.getSaslQop();
    } else {
      String[] qops = rpcProtection.split(",");
....

Configuring Encrypted HBase Data Transport Using Cloudera Manager states the following:
Search for the HBase Transport Security property and select one of the following:

authentication: Enables simple authentication using Kerberos.
integrity: Checks the integrity of data received to ensure it was not corrupted in transit. Selecting integrity also enables authentication.
privacy: Ensures privacy by encrypting the data in transit using TLS/SSL encryption. Selecting privacy also enables authentication and integrity.
Set this property to privacy to enable secure RPC transport.

So by choosing authentication or integrity you are not encrypting RPC traffic.


W3C Iframe Validation

Question: I'm using the Facebook plugin called Activity Feed.
The URL of this plugin is:
http://developers.facebook.com/docs/reference/plugins/activity
Now, I'm having a problem.
When I get the code for using this plugin it comes inside an IFrame, and has a not standard attribute for Internet Explorer browsers, or at least that what I read, it's the  allowTransparency="true" attribute.
When I validate my web site with this component it shows an error, there is no attribute "allowTransparency".
http://validator.w3.org/check?uri=http%3A%2F%2Fwww.ollivanders.co%2F&charset=%28detect+automatically%29&doctype=Inline&group=0
How can I solve it?
Thanks!!
Answer: I ran into the same thing. I deleted that attribute and the iframe worked just fine without it. Cosmetically it didn't affect any of my target browsers so I can live with it.
I suppose that attribute could be added via javascript if you really need it (don't know how to do this though)

W3C Iframe Validation


Making a contour plot with solutions from systems of differential equations with pylab

Question: So, I'm solving a system of differential equations numerically i have x,y,z each a solution. Each array is one dimensional and and for example x[0],y[0],z[0] goes with a point in space. i want to graph these in a contour like the usual x y z coordinates, it says i need z to be a 2d array, i know how to make a mesh from x and y, but how do i do this to z?
I have made a mesh out of the x,y, but for z i don't know what to do.
if someone could give me insight it would be much appreciated.
Comment: Have you tried anything yet?
Comment: Ive tried graphing and it says that i need a 2d array for z, i have no way to correlate z to a function of x and y because im solving things numerically, if i knew the explicit solution i wouldnt be doing this.
Comment: If these are ordinary differential equations, wouldn't it make more sense to plot the x, y, z as a curve in 3d space like [this example](http://matplotlib.org/1.3.1/mpl_toolkits/mplot3d/tutorial.html#line-plots)? What you are proposing makes sense if you have a partial differential equation with dz/dx and dz/dy, but then you would probably have a mesh of x and y for the solution.
Answer: It is not enough to just mesh in x and y, you need to grid your data on a regular grid to be able to do a contour plot. To do this you should look into matplotlib.mlab.griddata (http://matplotlib.org/examples/pylab_examples/griddata_demo.html).
I'll paste the example code from the link below with some extra comments:
from numpy.random import uniform, seed
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
import numpy as np

# Here the code generates some x and y coordinates and some corresponding z values.
seed(0)
npts = 200
x = uniform(-2,2,npts)
y = uniform(-2,2,npts)
z = x*np.exp(-x**2-y**2)

# Here you define a grid (of arbitrary dimensions, but equal spacing) onto which your data will be mapped
xi = np.linspace(-2.1,2.1,100)
yi = np.linspace(-2.1,2.1,200)

# Map the data to the grid to get a 2D array of remapped z values
zi = griddata(x,y,z,xi,yi,interp='linear')

# contour the gridded data, plotting dots at the nonuniform data points.
CS = plt.contour(xi,yi,zi,15,linewidths=0.5,colors='k')
CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.rainbow,
                  vmax=abs(zi).max(), vmin=-abs(zi).max())

plt.colorbar() # draw colorbar

# Plot the original sampling
plt.scatter(x,y,marker='o',c='b',s=5,zorder=10)
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.title('griddata test (%d points)' % npts)
plt.show()

Comment: Im numerically solving differential equations, the exact solution is not known, as a result i have no explicit relation for z in terms of strictly x and y
Comment: @Eigenvalue That is irrelevant to the problem at hand (which is about plotting, not solving ODEs). In your question you state that you have the data as x, y and z arrays. Just swap them in for the x,y and z arrays in the above example an you are basically done.
Answer: It looks like you are looking for line or scatter plots instead of contour.


Is it possible to atomically increment a table attribute as one of multiple operations within the DynamoDB Transactions feature?

Question: Our team has a DDB table that contains items with a 'state' attribute denoting various lifecycle states. We have another table that keeps track of the counts of these items by state (the partition key is the id of a container type a set items are grouped under, sort key is the state). Currently we use a lambda to keep the count in sync triggered by ddb stream on the table containing the items, but we've had some problems with this (latency, idempotency) and are looking into using DynamoDB transactions as a way to update the count table synchronously whenever we change the state of an item.
I was wondering if there is a way to do an atomic, incremental add using AttributeValueUpdate + 'AttributeAction.ADD' like in this example but within a DynamoDB Transaction so that the update to item state and count increment will be an ACID, all-or-nothing operation? The approach in the example uses an UpdateItemRequest with AttributeValueUpdate, while it seems like Transactions can only use the Update object, and I haven't been able to find a way to use AttributeValueUpdate with that object.
here
From my understanding of Transactions, there is no ordering to the independent operations so no operation can depend on the output of another (I can't read the value then add to it in same transaction) and if I read the value first it may be changed by the time the transaction occurs. I haven't been able to find any other example of incrementing a value within a DynamoDB transaction, hoping someone can tell me if this is possible.
Answer: This is definitely possible, you just don't have access to the fluent API that UpdateItemRequest uses to construct the update expression (via AttributeValueUpdate). Instead, you have to write the update expression by hand.
In the example you linked, the following:
UpdateItemRequest updateRequest =
    new UpdateItemRequest().withTableName("local-content")
        .withKey(key)
        .addAttributeUpdatesEntry("views", new AttributeValueUpdate()
            .withValue(new AttributeValue().withN("" + delta))
            .withAction(AttributeAction.ADD));

Is equivalent to something like this:
// Create a map of expression attribute values with the amount to increment by
Map<String, AttributeValue> values = new HashMap<String, AttributeValue>();
values.put(":one", new AttributeValue().withN("1"));

Update update =
    new Update().withTableName("local-content")
        .withKey(key)
        .withExpressionAttributeValues(values)
        .withUpdateExpression("ADD views :one");

With that said, keep in mind that DynamoDB transactions are significantly more expensive than non-transactional operations, and what you're trying to do will likely fall apart at high throughputs, as the counters will become hot keys.
Comment: Thank you!  I'm pretty sure we should be ok regarding high throughput/hot key issue- the service in question was originally tuned specifically to guard against that.  The count of states is not global across all items, items are grouped by a container type and state counts are set at that level.  Also- when items are selected for a purpose that changes their state, the service uses techniques to prevent generating hot keys.  I do understand the cost increase though and that will be noted if we choose to go with this solution.  Appreciate the heads up though!


Solving non-linear PDE with Runge-Kutta 4th order

Question: I want to solve the following non-linear PDE with Runge Kutta 4th order:
$$\partial_t y(t,x)=y(t,x)\partial_x y(t,x)- 3t^2=:f(t,y)$$
The initial conditions $y(t_0,x_j)=:y_0^j$ are given at each lattice point $x_j$. From this one can also calculate $\partial_x y$ at each lattice point at $t_0$ as follows: $(y')_0^{j}:=(\partial_x y)(t_0,x_j)$.
Next I consider the time steps at $x_j$. According to Wiki I have to calculate:
$$k_1^j:=f(t_0,y_0^j)$$
But how do I evaluate the following?
$$k_2^j:=f(t_0+\frac{\Delta t}{2},y_0^j+\frac{\Delta t}{2}k_1^j)$$
I have the spatial derivative in $f$ and therefore it is not clear to me what it means that I evaluate the function at $y=y_0^j+\frac{\Delta t}{2}k_1^j$?
Does it mean
$$f(t_0+\frac{\Delta t}{2},y_0^j+\frac{\Delta t}{2}k_1^j)=\left(\partial_xy\right)\left(t_0+\frac{\Delta t}{2},x_0^j\right)-3\left(t_0+\frac{\Delta t}{2}\right)^2$$
??
Comment: Why do you want to use RK-4 to solve this **linear** pde? This can be solved explicitly using the method of characteristics.
Comment: You are right. It was linear in the original post. I now made it non-linear. Sorry for that but I simplified my actual problem such that the main question here becomes clear. The main question is how I deal with the $\partial_x$ when I compute the time steps.
Comment: There is no specific method for taking spatial differences in the Runge-Kutta method.  If you are just starting on this, I would suggest something straightforward, like central differencing: $y^\prime_i \approx (y_{i+1} - y_{i-1})/(2 \Delta x) $.
Comment: Let me make my problem more clear. I can write $$f(t,y)=y(t,x) (\partial_x y)(t,x)-3 t^2\approx y(t,x)\frac{y(t,x+\Delta x)-y(t,x)}{\Delta x}-3t^2.$$ How do I evaluate $$f(t_0+\frac{\Delta t}{2},y_0^j+\frac{\Delta t}{2} k_1^j)~~?$$
Comment: More explicitly what do I plug in for $y(t,x+\Delta x)$ in the first equation when I evaluate $f$?
Answer: Ok. I solved it.
First write the PDE as:
$$\partial_t y(t,x)=y(t,x)\partial_x y(t,x)- 3t^2=y(t,x)\frac{y(t,x+\Delta x)-y(t,x)}{\Delta x}- 3t^2=:f(t,y) ~~(*)$$
We discretize the spatial coordinates $x_0,x_1,\cdots x_i\cdots$ and the time coordinate $t_0,t_1,\cdots t_j\cdots$.
We define the function $y_i(t)$ at each lattice point:
$$y_i(t):=y(t,x_i)$$
Then we can write equation $(*)$ as:
$$\partial_t y_i(t)=y_i(t)\frac{y_{i+1}(t)-y_i(t)}{\Delta x}-3t^2=: f_i(t)$$
In vector notation:
$$\partial_t \vec{y}(t)=\begin{pmatrix}y_0\frac{y_1-y_0}{\Delta x}-3 t^2\\y_1\frac{y_2-y_1}{\Delta x}-3 t^2\\...\\y_i\frac{y_{i+1}-y_{i}}{\Delta x}-3 t^2\\...\end{pmatrix}=:\vec{f}(t,\vec{y})$$
Based on this we can apply the Runge-Kutta scheme straight forwardly.

$\vec{y}(t_0)=:\vec{y}^{(0)}$ is given.

$\vec{k}_1:=\vec{f}(t_0,\vec{y}^{(0)})$

$\vec{k}_2:=\vec{f}(t_0+\frac{\Delta_t}{2},\vec{y}^{(0)}+\frac{\Delta t}{2}\vec{k}_1)$

$\vec{k}_3:=\vec{f}(t_0+\frac{\Delta_t}{2},\vec{y}^{(0)}+\frac{\Delta t}{2}\vec{k}_2)$

$\vec{k}_4:=\vec{f}(t_0+\Delta_t,\vec{y}^{(0)}+\Delta t\vec{k}_3)$

$\vec{y}^{(1)}=\vec{y}^{(0)}+\frac{\Delta t}{6}\left(\vec{k}_1+2\vec{k}_2+2\vec{k}_3+\vec{k}_4\right)$

Repeat steps for $\vec{y}^{(2)}$ etc.