Find $f(f(f(f(f(f(\cdots f(x)))))))$ $2018$ times

Question:
I was given a problem to calculate $f(f(f(\dots f(x))))$ $2018$ times if $f(x)=\frac{x}{3} + 3$ and $x=4$.

Is it even possible to be done without a computer?
Comment: Hint: $f^{(n)}(x)=\frac{x}{3^n}+\sum_{k=0}^{n-1}\frac{1}{3^{n-(k+2)}}$.
Comment: I'd first look at what happens when you iterate this several times, for small values of "several", and see if there's a pattern. Then try to prove by mathtematical induction that the pattern persists.
Comment: The second term is a geometric series.
Comment: As a worshipper of simplicity, I find that among seven answers posted so far, mine is the simplest. That's what I usually try to do. (But maybe not everyone will agree.....)
Answer: We can rewrite the problem as a first-order difference equation:
\begin{align*}
    a_{n+1} &= \frac{1}{3} a_n + 3 \\ a_0 &= 4
\end{align*}
We want to know $a_{2018}$.
There are a number of standard techniques to solve these, that are covered in discrete math courses.  One trick is temporarily ignore the $+3$ at the end and find a general solution to $a_{n+1} = \frac{1}{3} a_{n}$.  It's not too hard to see that $a_{n} = \frac{1}{3^n}$ satisfies that, and so does any multiple of it.
OK, now what about the $3$?  Let's look for a constant solution to $a_{n+1} = \frac{1}{3}a_n  + 3$.  That is, we solve $a = \frac{1}{3}a + 3 $ for $a$.  We get $a = \frac{9}{2}$.
Combining the two, we have a solution $$a_n = c \cdot \left(\frac{1}{3}\right)^n + \frac{9}{2}$$
This sequence does satisfy $a_{n+1} = \frac{1}{3}a_n + 3$ for any $c$, as you can check.  We now just need to fit the initial condition $a_0 = 4$.  Substituting $n=0$ gives
$$
    4= c \cdot 1 + \frac{9}{2} \implies c = - \frac{1}{2}
$$
So our particular solution is
$$
a_n = -\frac{1}{2} \cdot \left(\frac{1}{3}\right)^n + \frac{9}{2}
    = \frac{9}{2} - \frac{1}{2\cdot 3^n}
$$
Therefore
$$
    a_{2018} = \frac{9}{2} - \frac{1}{2\cdot 3^{2018}}
$$
This is very, very close to $\frac{9}{2} = 4.5$.
Answer: Hint: Consider the following recurrence relationship
$$a_{n+1}=\frac{a_n}{3}+3$$
for $n=0,1,\cdots$, and $a_0=4$. Now compute $a_n$ in terms of $n$.

If you are unaware of the method for solving linear recurrence relationships then consider
$b_n=a_{n}-\frac{9}{2}$ and observe that
$$b_{n+1}=\frac{b_{n}}{3} \implies b_{n}=\frac{b_0}{3^n} \implies a_n=\frac{9}{2}-\frac{1}{2}\cdot\frac{1}{3^n}.$$
Answer: You have $f(x) = \frac 1 3 x + 3.$ The numbers $f(x)$ and $f(w)$ will always be at a distance from each other that is $1/3$ the distance between $x$ and $w.$ That implies the sequence $f(x), f(f(x)), f(f(f(x))), \ldots$ converges to a point $x_0$ satisfying $f(x_0) = x_0.$ So we have
$$
\frac 1 3 x_0 + 3 = x_0
$$
and therefore
$$
x_0 = \frac 9 2.
$$
Since $f(9/2) = 9/2,$ the distance between $f(x)$ and $9/2$ is $1/3$ the distance between $x$ and $9/2.$ Then ask how many times you need to multiply by $1/3.$
Answer: Let's try to spot a pattern.
$$f(x)=3+\frac x3=\frac13(3^2+x)$$ $$f(f(x))=f\left(\frac13(9+x)\right)=3+\frac{9+x}{9}=4+\frac x9=\frac1{3^2}(3^3+3^2+x)$$ $$f(f(f(x)))=f\left(\frac19(36+x)\right)=3+\frac{36+x}{27}=\frac{13}3+\frac x{27}=\frac1{3^3}(3^4+3^3+3^2+x)$$
So iterating $2018$ times, we have $$f(f(f(\cdots f(x))))=\frac1{3^{2018}}(3^{2019}+3^{2018}+...+3^2+x)$$ or $$3^1+3^0+3^{-1}+...+3^{-2016}+\frac x{3^{2018}}\approx 4.5+\frac{2018}{3^{2018}}$$ Now since $3^{2018}$ is much bigger than $2018$, that term could be negligible so we can conclude that $$\boxed{f(f(f(\cdots f(x))))=4.5}$$
Answer: Suppose there exists an $x$ such that $f(x) = x$
$f(x) = \frac {x}{3} + 3 = x\\
x = \frac 92$
It would be a reasonable guess that we get something very close to $\frac {9}{2}$
$f(4) = 4 +\frac 13\\
f(4+ \frac 13) = 4 + \frac 13 + \frac 19\\
f(4+ \frac 13 + \frac 19) = 4 + \frac 13 + \frac 19 + \frac 1{27}$
Now we are on to something.
$f(4+ \sum_\limits{i=1}^{n} (\frac {1}{3})^i) = \frac {4}{3} + \frac{1}3\sum_\limits{i=1}^{n} (\frac {1}{3})^i + 3 =
4 + \sum_\limits{i=1}^{n+1}(\frac{1}3)^i$
$4 +\sum_\limits{i=1}^{n} \frac {1}{3}^n = 4 + \frac {(1-(\frac 13)^n)}{2}\\
4 +\sum_\limits{i=1}^{2018} \frac {1}{3}^n = 4 + \frac {(1-(\frac 13)^{2018})}{2}\\
4\frac 12 - \frac 12(\frac 13)^{2018}$
Answer: Consider that for all $x$ we have $$3f(f(x))-f(x)=\frac{x+36}{3}-\frac{x+9}{3}=9$$
From this putting $x=f(x)$ we get
$$3f(f(f(x)))-f(f(x))=9$$
I'll write $f^n(x)=\underbrace{f(f(\cdots f(x))\cdots )}_n$ from now
$$3f^3(x)-f^2(x)=9\\9f^3(x)-3f^2(x)=27$$
Also putting $x=f^2(x)$ $$3f^4(x)-f^3(x)=9\\27f^4(x)-9f^{3}(x)=81$$
And in general $$3^{n-1}f^n(x)-3^{n-2}f^{n-1}(x)=3^n$$
Now lets sum this from $n=2018$ to $n=2$
$$3^{2017}f^{2018}(x)-3^{2016}f^{2017}(x)+3^{2016}f^{2017}(x)-3^{2015}f^{2016}(x)+3^{2015}f^{2016}(x)-\cdots-f(x)=9+27+81+\cdots+3^{2018}\\$$
We can see that most of the terms cancel and we get
$$3^{2017}f^{2018}(x)-f(x)=9+27+\cdots +3^{2018}$$
You can recognize the RHS as the geometric sequence and you know what $f(x)$ is, so you can finish yourself.
Answer: Well, maybe we will be able to find that iterating the function $n$ times yields so function in terms of $n$.
Notation:  Let $f^n(x)$ be defined as $f(f(f(..... f(x)))...)$ iterated $n$ times.
$f(x) = \frac x3 + 3$
$f^2(x) = \frac x9 + 1 + 3 = \frac x9 + 4$.
$f^3(x) = \frac x{27} + 1\frac 13 + 3 = \frac x{3^3} + \frac {13}3$
$f^4(x) = \frac x{3^4} + \frac {13}{9} + 3 = \frac x{3^4} + \frac {40}{9}$
Any patterns?  Clearly the first term is $\frac x{3^n}$ but what is the pattern of the second term $3, 4, \frac {13}3, \frac {40}{9}$.  I can see how then denominator is $3^{n-2}$ (and it's pretty obvious why the happens).  And the numerators are $1,4,13,40$ which are $1, 3+1, 3(3+1) + 1, 3(3(3+1)+1)+1$ which if we expand them are $1, 3+1, 3^2 + 3 + 1, 3^3 + 3^2 + 3 + 1$.
Further more:  $x^n + x^{n-1} + ..... + 1 = \frac {x^{n+1} - 1}{x - 1}$.
So $1,4,13, 40 = \frac {3-1}2, \frac {3^2 -1} 2, \frac {3^3-1}2, \frac {3^4-1}2$.
So.
$f(x) = \frac x3 + \frac {3-1}{2*3^{-1}}$
$f^2(x) = \frac x{3^2} + \frac {3^2 -1} {2*3^0}$
$f^3(x) = \frac x{3^3} + \frac {3^3 -1} {2*3^1}$
$f^4(x) = \frac x{3^4} + \frac {3^4 -1}{2*3^2}$.
And we can claim:
$f^n(x) = \frac x{3^n} + \frac {3^n -1} {2*3^{n-2}}$.
And we can prove it via induction.
$f^{n+ 1}= \frac {f^n(x)}3 + 3 = \frac {\frac x{3^n} + \frac {3^n -1} {2*3^{n-2}}}3 + 3$
$= \frac x{3^{n+1}} +  \frac {3^n -1} {2*3^{n-1}}+ \frac {2*3^n}{2*3^{n-1}}$
$= \frac x{3^{n+1}} +  \frac {3^n+2*3^n -1} {2*3^{n-1}}$
$= \frac x{3^{n+1}} +  \frac {3*3^n -1} {2*3^{n-1}}$
$= \frac x{3^{n+1}} +  \frac {3^{n+1} -1} {2*3^{n-1}}$
So we have
$f^{2018}(4)  = \frac 4{3^{2018}} + \frac {3^{2018} -1} {2*3^{2016}}$
$\frac {4*2 + 9*3^{2018}-9}{2*3^{2018}}$
Answer: Let $x_{n+1} =f(x_n)$ that is  $x_{n+1} =\frac{x_n}{3}+3 $
Letting $$u_n =x_n -\frac{3}{2}\implies u_{n+1}=\frac13 u_n \implies u_n = \frac{u_1}{3^{n-1}} \implies x_n = \frac{3}{2}+\frac{x_1 -\frac{3}{2}}{3^{n-1}}$$
Hence, we have $$ \color{blue}{ \underbrace{f(f(f(f(f(f(\cdots f(x)))))))}_{n~~times} = x_n = \frac{3}{2}+\frac{2x -3}{2\cdot3^{n-1}}}$$
Answer: Hint: $f^{(n)}(x)=\dfrac{x}{3^n}+\displaystyle\sum_{k=0}^{n-1}\dfrac{1}{3^{n-(k+2)}}$.The second term is straightforward to compute.
Answer: if $f(x)=\frac{x}{3}+3$
Then $f^2(x)=\frac{f(x)}{3}+3=\frac{x}{9}+\frac{3}{3}+3$
and $f^3(x)=\frac{f^2(x)}{3}+4=\frac{x}{27}+\frac{3}{9}+\frac{3}{3}+3$
By induction the general form is emerging as:
$$f^n(x)=3^{-n}x+3\left(\sum_{k=1}^n3^{1-k}\right)$$
Use the formula for a geometric sum and plug in $x=4, n=2018$:
$f^{2018}(4)=4+\frac{1}{2}\left(1-3^{-2018}\right)$
Answer: Doesn't look too bad to be honest.
We have:
$$f(x)=\frac{x}3+3=\frac{x+9}{3}$$
$$f^2(x)=\frac{\frac{x+9}{3}+9}{3}=\frac{x+\overbrace{36}^{(3+1)\cdot9}}{9}$$
$$f^4(x)=\frac{\frac{x+36}{9}+36}{9}=\frac{x+\overbrace{360}^{(9+1)\cdot36}}{81}$$
$$f^8(x)=\frac{\frac{x+360}{81}+360}{81}=\frac{x+(81+1)\cdot360}{81^2}$$
Can you see the pattern? Do you think you can take it from here?
Answer: In order to solve this, let's first write something down
$f(4) = 13/3 = (4 + 9)/3 = (1 + 3 + 9)/3$
$f(f(4)) = 40/9 = (13 + 27)/9 = (4 + 9 + 27) = (1 + 3 + 9 + 27)/9$
$f(f(f(4))) = 121/27 = (40 + 81)/27 = (1 + 3 + 9 + 27 + 81)/27$
We observe a rule:
1) Denominator:
It's the previous denominator  $\times 3$ because we basically take the previous number and divide it by $3$ and add $3$ to it.
2) Numerator:
The numerator is the sum of a geometric progression, the last number being $3^{n + 1}$, where $n$ is the number of times we did: $f(f(...f(x)))$. In this case, the last number will be $3^{2019}$.
I hope this helped!
Comment: Welcome to MSE! Please format your answers using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)


Half, Three Quarter Sharps and Microtonality

Question:
Less often (in for instance microtonal music notation) one will encounter half, or three-quarter,... or otherwise modified, sharps. A half sharp indicates the use of quarter tones, and may be marked with various symbols including half sharp.

-Wikipedia - https://en.wikipedia.org/wiki/Sharp_(music)
What is Microtonality? When and why is it appropriate to use these symbols?  Why do they even exists?  It seems like it would be much easier to show notes with just one sharp/flat.
Comment: I believe the duplicate tag here is incorrect as it doesn't cover microtonality which is included in the question.
Comment: I've never encountered a triple-sharp or flat (and can't comment on microtonal stuff). Double sharps/flats are not uncommon. They occur in keys, where a single sharp/flat is already in the key signature, see linked question an its answers.
Answer:
What is Microtonality? When and why is it appropriate to use these symbols? Why do they even exists?

Microtonal music is music that uses microtones -- any interval that is smaller than the usual half-steps (each 1/12th of an octave) that are found in traditional western music. It can actually be rather tricky to define exactly, because many definitions exclude scales that are audibly indistinguishable (or nearly so) to western music (e.g. quarter-comma meantone uses pure/just thirds that are somewhat flat compared to 12TET, but still creates a 12-note scale that sounds very similar to 12TET, and would not be considered truly microtonal).
Another common generic term that can be used is xenharmonic, which means strange, or foreign sounding. There is a good website that deals with all manner of microtonal and xenharmonic musical topics called the xenharmonic wiki. Specifically, they have a good introduction that answers the question "what is microtonal music", including some of the difficulties in defining it, and some of the alternative names that are used.
Broadly speaking, you can think of such music as coming from either a non-western source (many of the world's musical cultures do not use the 12-note system of western music), or else coming from a western, but non-traditional source (often referred to as "experimental" music).
As an example of the first, the Arab tone system uses a 24-tone equal system, from which a 7 note scale is then chosen . This leads to notes that are a quartertone apart. Some_Guy has mentioned Blues, rooted in African-American music, which uses "blue notes" that are flatter than normal, but by less than a half step.
Since western musical notation was originally designed to handle western music, it does not necessarily have symbols to handle notes outside this system. Thus symbols such as the ones you ask about (half and three-quarter sharps) were developed to fill this need.
Answer: There are a number of different systems to notate microtones in western music, perhaps the earliest coming from Tartini in 1759, which is still favored by many. Many of these systems use common symbols in combination, such as Tartini's 3/4 sharp sign made of two #'s stuck together (approximately like this: ##). Some use backward flats, flats and sharps with arrows attached to indicate raising or lowering, etc. Other systems use arrows above small numerals, generally indicating a fractional increase like 1/3, 1/6, etc., all placed above the note affected, as opposed to the normal position of accidentals. One of the better discussions of all this is in Kurt Stone's Music Notation in the Twentieth Century. Better notation software, Sibelius for example, includes many such symbols.
Comment: The 3/4 sharp sign should probably be described in words, because the characters you wrote look like a lazy man's double-sharp. It's two parallel horizontal lines intersected by three parallel vertical lines.
Answer: Doubles are covered here.
Purpose of double-sharps and double-flats?
Essentially they occur in sheet music as a way of "spelling" notes.  For a piece of music that has a flat or sharp in the key signature already, if you want to raise or lower that now within the music you then need a double.
If G that at some point included a minor third accidental (a Bb).  To write that same piece of music in G flat major it would make sense to have a double flat (the third is normally Bb, so now it's Bbb).  Sure you could just write A natural, but then what you're really saying is this piece has a "sharp second" not a "flat third".

So that first part's a relatively "boring" answer about musical theory that doesn't change the sound, it's just about notation.  As for a half or 3/4 though.  That's a way of writing down a note that isn't on the piano.  What if I want to play a note between B and C?  It's C half flat!  (Or B half sharp)
If you don't think notes outside of the usual 12 are useful, pretty much anything influenced by the blues has to disagree with you.  For example:
Comment: The embedded video has been blocked "on copyright grounds".
Answer: The fundamental problem with microtonal symbols is that they are being added onto a simple modal (7 notes per octave) system of interval representation (like the white keys of a piano). With the development of chromatic (12 notes per octave) music, accidentals such as #/b (like the black keys of a piano) have been added to the modal system. As microtonal (>12 notes per octave) music has evolved, many more pitch-modifier symbols are being added to the modal system of notating intervals.
In this situation, not only do we end up with complex symbols like 3/4 sharp and 1/4 flat, but also with innumerable, idiosyncratic symbol sets; many of which are incompatible with other microtonal scale symbol sets.
What is needed is an updated foundational system which evolves beyond a modal (7-note scale) framework of describing musical intervals.
Without updating our conventional modal framework of intervals, another effect happens in musical terminology as well, with terms like septimal major third, just major third, grave major third, neutral third, etc. These complicated adjectives are necessary to express the increasing varieties of each modal interval that are possible within microtonal scales.
Here is an excellent article on microtonality: http://recherche.ircam.fr/equipes/repmus/moreno/AndreattaMicrotonality.pdf


McAfee Drive Encryption issues with HP Elitebook 755 G2

Question: Hi all (Sorry if this isn't the right forum to post on),
I have a slightly frustrating issue involving a small collection of HP laptops and McAfee Encryption. We can encrypt the laptops absolutely fine, and they run performance wise just as well. However, after a few days the laptops will just refuse to boot, and you have to decrypt the laptops to be able to get them to boot.
I spoke to McAfee about this and they informed me that there is a "Known" compatibility with HP laptops and Drive Encryption but informed me that this version of laptop was not on the list of those.
After a few hours of digging we decided that the TPM was most likely the cause of this issue. We removed the drivers completely off the PC, whilst also disabling the device so Windows Update couldn't put them back on. We tested this to make sure the TPM drivers wouldn't be put back on the PC and those tests were successful.
A couple of weeks had passed the drivers had not put themselves back onto the PC's and they were working fine. However they've now stopped booting again, and the only way to get back onto the PC is to decrypt it. The list below is some of the things I have tried so resolve the issue:

Removed encryption and re-encrypted the devices: This leads to the computer booting fine first time round, but will then stop booting once you turn off/restart the PC.
If the PC has Drive Encryption on but has not encrypted the hard drive, it still has the same issue in not booting as you would get with an encrypted one.
I've disabled the TPM in the BIOS and this has had no effect in fixing the issue.
Using HP Drive Encryption seems to work, however the lack of a central management system is not our preferred choice (Although this might have to suffice if McAfee doesn't work)

Could something be changing or have changed before the boot stage which the TPM isn't happy with and therefore causes the issue?
I get that this is most likely an incompatibility issue, but I'm still looking for people who have had similar issues, or may have a better knowledge of how Drive Encryption works.
Comment: What's wrong with BitLocker?
Comment: Nothing is wrong with BitLocker. But our laptops only have 1 partition, we don't have the second one for BitLocker. Equally the helpdesk and 3rd line haven't tried Bitlocker so they would be hesitant to even want to try it unless I could 100% prove that McAfee couldn't work on these laptops.
Answer: We have had the same issue.
We upgraded the BIOS to 1.08, turned off Fast Boot and set Boot Mode is set to "UEFI Hybrid (with CSM)".
This is working with normal HP SSD, when using larger 1TB SSD we encrypt before we let the user partition etc.
Most of our issues were with Win 8.1
Comment: Hi Peter, sorry for the VERY late reply (Java was being blocked at my work due to a proxy issue so I couldn't access any of the websites functionality). When you were using Win 8.1, did you use x64 or x86?


Radio-Buttons displayed as a Table

Question: Always radio-buttons have to be set vertically or horizontally, but I want to make them feeding the layout from left to right and then from top to bottom.
Example:
Instead of 5 horizontal buttons or 5 vertical buttons, I want 3 buttons on the first line and 2 buttons on the second line.
I'm looking for a solution using preferably only the xml file.
Comment: my question is for radiobutton not for checkboxes
Answer: Here you have an example, you have to put your strings in each checkbox
<code>   <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical" >

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@null"
            android:drawableLeft="@drawable/your_drawable"
            android:drawablePadding="10dp"
            android:paddingLeft="15dp" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@null"
            android:drawableLeft="@drawable/your_drawable"
            android:drawablePadding="10dp"
            android:paddingLeft="15dp" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@null"
            android:drawableLeft="@drawable/your_drawable"
            android:drawablePadding="10dp"
            android:paddingLeft="15dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical" >

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@null"
            android:drawableLeft="@drawable/your_drawable"
            android:drawablePadding="10dp"
            android:paddingLeft="15dp" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@null"
            android:drawableLeft="@drawable/your_drawable"
            android:drawablePadding="10dp"
            android:paddingLeft="15dp" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@null"
            android:drawableLeft="@drawable/your_drawable"
            android:drawablePadding="10dp"
            android:paddingLeft="15dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical" >

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@null"
            android:drawableLeft="@drawable/your_drawable"
            android:drawablePadding="10dp"
            android:paddingLeft="15dp" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@null"
            android:drawableLeft="@drawable/your_drawable"
            android:drawablePadding="10dp"
            android:paddingLeft="15dp" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@null"
            android:drawableLeft="@drawable/your_drawable"
            android:drawablePadding="10dp"
            android:paddingLeft="15dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical" >

        <CheckBox

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@null"
            android:drawableLeft="@drawable/your_drawable"
            android:drawablePadding="10dp"
            android:paddingLeft="15dp" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@null"
            android:drawableLeft="@drawable/your_drawable"
            android:drawablePadding="10dp"
            android:paddingLeft="15dp"/>
     </LinearLayout>
  </LinearLayout>
</code>
Comment: but it should unchecked the previous checked item when it is selected. Here you have many checkbox so checking one box will not uncheck another. That is why I am talking about radio-button specifically.
Comment: Check out this post http://stackoverflow.com/questions/2381560/how-to-group-a-3x3-grid-of-radio-buttons
Comment: I read this one but I'm doing this inside a fragment which means I can't extend TableLayout  as I am already extending Fragment.

Radio-Buttons displayed as a Table


Strange behaviour with border-collapse and colspan

Question: I am trying to make an organisational chart in HTML. The code is fairly simple, but I have some problems with the rendering in Chrome/Safari and Opera.
Here is what the result should look like, as it works in Firefox and IE:

Here is in Chrome and Safari

And here is in Opera:

The problem comes from the border-collapse: collapse property in CSS. If I use the old coding style cellspacing="0" cellpadding="0"it works more or less, but is not valid in HTML5.
I created a jsFiddle to show the problem: http://jsfiddle.net/aGVp4/7/
My HTML:

And my CSS:
.orgchart {
    border-spacing: 0;
    border-collapse: collapse;
}

td {
    width: 3em;
    height: 1em;
}

td.case {
    border: 1px solid black;
}

td.right {
    border-right: 1px solid black;
}

td.bottom {
    border-bottom: 1px solid black;
}

td.top {
    border-top: 1px solid black;
}

Comment: This is rather odd, even for a fairly complicated table like this. As an aside, the table has 8 columns but only 7 columns on 3rd row, so an empty cell should be appended; but this affects the symptoms of the problem only, not the problem itself. If you set `style="border-color: red"` on the second cell of the second row, you'll see that the disturbing line is part of the border of this cell. But what might be the cause of this strange phenomenon?
Comment: @JukkaK.Korpela Thanks for your remark, I edited my post. I don't get it either: the HTML is valid, I don't use CSS hacks or exotic things, so I'm baffled.
Answer: The problems seems to be caused by different interpretations of the collapsing border model in browsers. The border conflict resolution is defined in terms of cells, not slots, and when you use colspan=3, one cell spans 3 slots.
The 2nd cell of the 2nd row has a solid bottom border, and the 2nd cell of the 3rd row has no top border. When borders collapse, solid wins none. But the cells are only partially adjacent, as they span different columns. Browsers hand this differently. Chrome makes the border span all the columns of the upper cell, whereas Firefox makes the border span only one column, the one that the cells share – which is more reasonable, but CSS 2.1 seems to leave the issue open.
I tried playing with border: hidden, which helps on Chrome but causes new problems on Opera.
It seems that there are two options. You could use the HTML attributes, if they do the job. Though declared obsolete and forbidden in HTML5 CR, the same document also requires continued support to them in browsers.
But a cleaner, and perhaps more robust, approach is to avoid the problem by adding more empty cells. This means dividing two 3rd row cells into two cells so that only one of them shares a border with the cell of the 2nd row. This makes the table even more grid-like, but not essentially more complex:

Comment: Thanks for the detailed answer. It is a bit annoying to have to separate the cells, but I can live with that :)
Comment: FWIW - This is a known bug (https://bugs.webkit.org/show_bug.cgi?id=20840) for many, many years... sadly, no good solutions to this problem other than separating the cells as described above.
Answer: Add a new empty row

 under the colspan will fix this problem (not a beautiful solution but works).
Answer: I played with your jsfiddle, and found a hack to fix the issue in Chrome and Safari.
Also works on FF and IE, but didn't test on Opera.
Try this (jsfiddle):
td.bottom {
  border-top: 1px solid white; // this is the hack
  border-bottom: 1px solid black;
}
td.right.bottom {
  border-top: none; // fix for IE
}

As this is a hack, it may not work as your chart grows complex, but hope this helps in short-term.
Comment: Thanks for your answer, unfortunately the result is even stranger with Opera, so I can't use it :)
Comment: Oh, that's a bummer. Perhaps you should remove all colspans, and only use border-top and border-right to draw all the lines. (not using border-bottom and border-left). Define 3 classes: (both, top, right), and use those only.


Filter view results by day of the week instead of the date - Date Module

Question: I have a view which includes a date field, and I'd like to provide a filter for users to show only items from a certain day of the week. From what I can see, though, the date filter only allows you to select the date by which to filter. Is it possible to create a filter which will allow users to show, say, all nodes which have a date that falls on a Wednesday?
Comment: The date filter will allow you to set the filters by a particular "year" or by particular "month & year"  by changing the granularity of date filter settings
Comment: Yes I realize that, but I am looking for a way to filter by day of the week. If I select a granularity of "day", the user still has to filter by a particular date, and cannot select "Friday" or "Wednesday".
Answer: I think you have to use the Views Day of Week module to filter the result by day of week. Here is a quote from it's project page:

... Views Day of Week provides a simple filter plugin for Views 3 to enable filtering content that should be visible based on the current day of the week.
Example: With this module you can select that some content should be visible only on Mondays, some on Tuesdays and Thursdays and some only on Fridays.


Configuring Apache subdomain for Redmine

Question: I have a server called DEV01.intranet where I have installed Redmine.
I managed to configure a subdomain redmine.dev01.intranet, which is working now, but when I go to dev01.intranet alone it shows Redmine again (??!!!)
I would like to access Redmine from http://redmine.dev01.intranet and http://dev01.intranet/redmine.
I have these in sites-enabled:
GNU nano 2.2.6                             File: /etc/apache2/sites-enabled/default1
<VirtualHost *:80>
        DocumentRoot /var/www
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

GNU nano 2.2.6                             File: /etc/apache2/sites-enabled/redmine
<VirtualHost redmine.dev01.intranet.fusiondev.com.ar:80>
 ServerName redmine.dev01.intranet.fusiondev.com.ar
 DocumentRoot /usr/local/share/redmine/public
 ServerAlias redmine.dev01.intranet.fusiondev.com.ar
 ServerAdmin firstname.lastname@example.com
 LogLevel warn
 ErrorLog /var/log/apache2/redmine_error
 CustomLog /var/log/apache2/redmine_access combined
 RailsEnv production
 RailsBaseURI /redmine
 PassengerDefaultUser www-data
 PassengerResolveSymlinksInDocumentRoot on
 <Directory /var/www/redmine>
   Options Indexes FollowSymLinks MultiViews
   AllowOverride None
   Order allow,deny
   allow from all
 </Directory>
</VirtualHost>

What I am doing wrong and why is Redmine shown at root / when no one says so?
Thanks!
Answer: I finally came around the solution.
The bigges problem solved adding 000-xxx, 001-xxx (number prefix) to VirtualHosts symbolic links from sites-available to sites-enabled. That way the dev01 alone will load first, then redmine.dev01.
Last, I had no CSS in the second Redmine to load. If I go to redmine.dev01 first after Apache restart, it loads OK. But de01/redmine wont have CSS, and viceversa if I load it first.
The solution was to make a copy of the source folder and point the subdomain DocumentRoot's to the second folder. It's like a new instance. Didn't search too much for other solutions, but since the DB is the same, it's only 60mb of wasted disk space and a second instance in memory (If that's the way Ruby on Rails manages it).
My VirtualHosts, in case anyone needs a hand.
GNU nano 2.2.6                             File: /etc/apache2/sites-enabled/000-dev01
<VirtualHost *:80>
        ServerAdmin firstname.lastname@example.com
        ServerName dev01.intranet.fusiondev.com.ar
        ServerAlias www.dev01.intranet.fusiondev.com.ar
        DocumentRoot /var/www/dev01
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/dev01>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

        <Directory /var/www/dev01/redmine>
                RailsBaseURI /redmine
                PassengerResolveSymlinksInDocumentRoot on
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

GNU nano 2.2.6                          File: /etc/apache2/sites-enabled/001-redmine.dev01
<VirtualHost *:80>
 ServerName redmine.dev01.intranet.fusiondev.com.ar
 DocumentRoot /var/www/redmine.dev01/redmine
 ServerAlias www.redmine.dev01.intranet.fusiondev.com.ar
 ServerAdmin firstname.lastname@example.com
 LogLevel warn
 ErrorLog /var/log/apache2/redmine_error
 CustomLog /var/log/apache2/redmine_access combined
 RailsEnv production
 RailsBaseURI /redmine
 PassengerDefaultUser www-data
 PassengerResolveSymlinksInDocumentRoot on
 <Directory /var/www/redmine.dev01/redmine>
   Options Indexes FollowSymLinks MultiViews
   AllowOverride None
   Order allow,deny
   allow from all
 </Directory>
</VirtualHost>

Answer: try to exhange:
<VirtualHost redmine.dev01.intranet.fusiondev.com.ar:80>

with
<VirtualHost *:80>

VirtualHosts and IP addresses are somewhat tricky - look here for details.
Comment: Thanks! I've found the answer. Can you vote up my question so I can put it? Requires 10 reputation and I have 9. Thanks!
Comment: No problem - voted you up :)


Is women's tennis the only sport which is shorter than men?

Question: Women's soccer is played for 2 halves at 45 minutes with 15 minute break in between, just like men https://yoursoccerhome.com/how-long-is-a-womens-soccer-game/
Yet, men have to play best of 5 sets in tennis, whereas women play best of 3. Is this the only sport which has less stamina requirements for women?
Comment: The "why" part is covered by [this duplicate](https://sports.stackexchange.com/questions/4742/what-is-the-reason-men-play-5-sets-women-play-3-sets-in-a-grand-slam-in-tennis) so I'll remove that bit from the question.
Answer: In athletics:

The women run 100m hurdles while the men run 110m hurdles; the hurdles are also lower for women than men.

While men and women both run 400m hurdles, the hurdles are again lower for women.

The discus,  javelin and shot are all lighter for women than for men.
The women's multi-discipline event has 7 events while the men's has 10 events.
Answer: Sure, lots of sports have different rules related to timing, though I'd note that it's unclear how much this is due to stamina versus money/historical interest.  Stamina is not straightforward question between men and women (see: extreme long distance running, women hold the records, not men).
Softball is 7 innings versus baseball being 9 innings.
WNBA periods are 10 minutes, 40 minute games while NBA periods are 12 minutes, 48 minute games.
Golf could be another one here - while the "length" of the game is the same, moving the tees forward makes it a shorter game (or rather, aims to make it the same length-of-time instead of longer).
Comment: @PhilipKendall It is, nonetheless, an example of men's and women's sports being different at the same level :). Tennis in fact is not different there either - ATP is 3 sets for both, and ITF does not differentiate men/women in allowing 3 or 5 sets.
Comment: (And yes, I know baseball and softball are technically different sports, and men can play softball - player here! - but at the professional level, for historical reasons, softball is "girls baseball".)
Comment: I'd say the basketball one is more the NBA being anomalous - FIBA rules are 4x10 minutes for men as well.


Android native crash

Question: We are not using any native code, as well our app doesn't have any native transitive dependency.
After recent release (we updated couple fo dependencies and add new) we started seeing crashes like this in Google Play:
native: pc 000000000006a548  /system/lib64/libc.so (tgkill+8)
  native: pc 0000000000067cd8  /system/lib64/libc.so (pthread_kill+68)
  native: pc 0000000000024b78  /system/lib64/libc.so (raise+28)
  native: pc 000000000001f318  /system/lib64/libc.so (abort+60)
  native: pc 000000000043471c  /system/lib64/libart.so (_ZN3art7Runtime5AbortEv+324)
  native: pc 0000000000137224  /system/lib64/libart.so (_ZN3art10LogMessageD2Ev+3136)
  native: pc 000000000030d988  /system/lib64/libart.so (_ZN3art9JavaVMExt8JniAbortEPKcS2_+2080)
  native: pc 000000000030df24  /system/lib64/libart.so (_ZN3art9JavaVMExt9JniAbortFEPKcS2_z+224)
  native: pc 000000000034ec64  /system/lib64/libart.so (_ZN3art3JNI15CallVoidMethodVEP7_JNIEnvP8_jobjectP10_jmethodIDSt9__va_list+616)
  native: pc 0000000000099094  /system/lib64/libandroid_runtime.so
  native: pc 0000000002a71ac4  /system/framework/arm64/boot.oat

I think it just Android itself but what might be the reason? Any assistance is appreciated.
Is there info about what this call means? Is it virtual machine some invocation?
_ZN3art3JNI15CallVoidMethodVEP7_JNIEnvP8_jobjectP10_jmethodIDSt9__va_list

Comment: https://demangler.com converts your method name to art::JNI::CallVoidMethodV(_JNIEnv*, _jobject*, _jmethodID*, std::__va_list)
Comment: So basically it is call of some java method on some object that doesn't have to return something?
Comment: Right. Check this one out also: https://stackoverflow.com/questions/29680487/jni-detected-error-in-application
Comment: Thanks, it is much better now but still not clear what and why
Comment: I've also been seeing the same crash in the play console logs. Seems to be limited only to Android 6.0 devices. @EugenMartynov any progress on the issue?
Comment: Do you use `com.google.android.gms:play-services-ads:11.4.2` library in your project? Here is a very similar issue that seems to be caused by a bug in this library: https://stackoverflow.com/questions/47141733/android-6-0-native-tgkill-crash?rq=1
Comment: Hi @EugenMartynov, on what device(s) do you see these logs? And what Android version?
Comment: It is various devices and happens most on Android 6.0, and some amount on the Android 5.x
Comment: The problem seems to have occurred after I upgraded Google Play Services from 11.4.2 -> 11.8.0 for ads and location. Also in this timeframe firebase auth and database were added to the project.
Comment: @SergeyLebedev I have seen that too but the logs in the question seem like the same problem but the logs in the answer reference a different crash so that did not help unfortunately
Comment: These are the devices I have seen the crash happen on https://i.imgur.com/BbgC1xx.png. Seems to be a variety of cheaper devices with a common ARM Cortex-XXX CPU
Answer: To start out I think the troublesome issue was finding the root cause as the Play Console does not provide the full stack trace and the stack trace also changes slightly depending on the device/android version. I have seen this tgkill native crash with many variations like the following but I've concluded that all of these crashes can be attributed to a bug in the Support Library
_ZN3art3JNI15CallVoidMethodVEP7_JNIEnvP8_jobjectP10_jmethodIDSt9__va_list+440
_ZN3art3JNI15CallVoidMethodVEP7_JNIEnvP8_jobjectP10_jmethodIDSt9__va_list+616
art::JNI::CallVoidMethodV(_JNIEnv*, _jobject*, _jmethodID*, std::__va_list)+580
_ZN3art3JNI15CallVoidMethodVEP7_JNIEnvP8_jobjectP10_jmethodIDSt9__va_list+470
_ZN3art3JNI15CallVoidMethodVEP7_JNIEnvP8_jobjectP10_jmethodIDSt9__va_list+560
After much effort I was able to recreate this on a 6.0 Device on a screen in my application that contained an AppBarLayout + CollapsingToolbarLayout + RecyclerView. The CollapsingToolbarLayout had the following scroll flags
app:layout_scrollFlags="scroll|exitUntilCollapsed|snap"
By scrolling all the way to the bottom and then quickly back to the top I was able to recreate the crash most of the time which yielded the following stacktrace
04-18 14:06:53.814 27077-27077/com.PACKAGE.NAME.debug A/art: art/runtime/java_vm_ext.cc:410] JNI DETECTED ERROR IN APPLICATION: can't call void android.view.View.setElevation(float) on null object
art/runtime/java_vm_ext.cc:410]     in call to CallVoidMethodV
art/runtime/java_vm_ext.cc:410]     from void android.animation.PropertyValuesHolder.nCallFloatMethod(java.lang.Object, long, float)
art/runtime/java_vm_ext.cc:410] "main" prio=5 tid=1 Runnable
art/runtime/java_vm_ext.cc:410]   | group="main" sCount=0 dsCount=0 obj=0x740f26e8 self=0x558c24bf70
art/runtime/java_vm_ext.cc:410]   | sysTid=27077 nice=-6 cgrp=default sched=0/0 handle=0x7f8f6e8fc8
art/runtime/java_vm_ext.cc:410]   | state=R schedstat=( 76543056125 12869243427 123563 ) utm=6830 stm=824 core=2 HZ=100
art/runtime/java_vm_ext.cc:410]   | stack=0x7fef761000-0x7fef763000 stackSize=8MB
art/runtime/java_vm_ext.cc:410]   | held mutexes= "mutator lock"(shared held)
art/runtime/java_vm_ext.cc:410]   native: #00 pc 00000000004903d8  /system/lib64/libart.so (_ZN3art15DumpNativeStackERNSt3__113basic_ostreamIcNS0_11char_traitsIcEEEEiPKcPNS_9ArtMethodEPv+236)
art/runtime/java_vm_ext.cc:410]   native: #01 pc 000000000045f598  /system/lib64/libart.so (_ZNK3art6Thread4DumpERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEE+220)
art/runtime/java_vm_ext.cc:410]   native: #02 pc 0000000000312970  /system/lib64/libart.so (_ZN3art9JavaVMExt8JniAbortEPKcS2_+1000)
art/runtime/java_vm_ext.cc:410]   native: #03 pc 0000000000313228  /system/lib64/libart.so (_ZN3art9JavaVMExt9JniAbortVEPKcS2_St9__va_list+116)
art/runtime/java_vm_ext.cc:410]   native: #04 pc 000000000014501c  /system/lib64/libart.so (_ZN3art11ScopedCheck6AbortFEPKcz+144)
art/runtime/java_vm_ext.cc:410]   native: #05 pc 000000000014557c  /system/lib64/libart.so (_ZN3art11ScopedCheck17CheckMethodAndSigERNS_18ScopedObjectAccessEP8_jobjectP7_jclassP10_jmethodIDNS_9Primitive4TypeENS_10InvokeTypeE+1084)
art/runtime/java_vm_ext.cc:410]   native: #06 pc 000000000015eaf8  /system/lib64/libart.so (_ZN3art8CheckJNI11CallMethodVEPKcP7_JNIEnvP8_jobjectP7_jclassP10_jmethodIDSt9__va_listNS_9Primitive4TypeENS_10InvokeTypeE+724)
art/runtime/java_vm_ext.cc:410]   native: #07 pc 0000000000160d98  /system/lib64/libart.so (_ZN3art8CheckJNI15CallVoidMethodVEP7_JNIEnvP8_jobjectP10_jmethodIDSt9__va_list+68)
art/runtime/java_vm_ext.cc:410]   native: #08 pc 0000000000098fe0  /system/lib64/libandroid_runtime.so (???)
art/runtime/java_vm_ext.cc:410]   native: #09 pc 0000000000ad2cc4  /system/framework/arm64/boot.oat (Java_android_animation_PropertyValuesHolder_nCallFloatMethod__Ljava_lang_Object_2JF+168)
art/runtime/java_vm_ext.cc:410]   at android.animation.PropertyValuesHolder.nCallFloatMethod(Native method)
art/runtime/java_vm_ext.cc:410]   at android.animation.PropertyValuesHolder.access$400(PropertyValuesHolder.java:37)
art/runtime/java_vm_ext.cc:410]   at android.animation.PropertyValuesHolder$FloatPropertyValuesHolder.setAnimatedValue(PropertyValuesHolder.java:1296)
art/runtime/java_vm_ext.cc:410]   at android.animation.ObjectAnimator.animateValue(ObjectAnimator.java:981)
art/runtime/java_vm_ext.cc:410]   at android.animation.ValueAnimator.animationFrame(ValueAnimator.java:1384)
art/runtime/java_vm_ext.cc:410]   at android.animation.ValueAnimator.doAnimationFrame(ValueAnimator.java:1427)
art/runtime/java_vm_ext.cc:410]   at android.animation.ValueAnimator$AnimationHandler.doAnimationFrame(ValueAnimator.java:759)
art/runtime/java_vm_ext.cc:410]   at android.animation.ValueAnimator$AnimationHandler$1.run(ValueAnimator.java:801)
art/runtime/java_vm_ext.cc:410]   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
art/runtime/java_vm_ext.cc:410]   at android.view.Choreographer.doCallbacks(Choreographer.java:670)
art/runtime/java_vm_ext.cc:410]   at android.view.Choreographer.doFrame(Choreographer.java:603)
art/runtime/java_vm_ext.cc:410]   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
art/runtime/java_vm_ext.cc:410]   at android.os.Handler.handleCallback(Handler.java:743)
art/runtime/java_vm_ext.cc:410]   at android.os.Handler.dispatchMessage(Handler.java:95)
art/runtime/java_vm_ext.cc:410]   at android.os.Looper.loop(Looper.java:171)
art/runtime/java_vm_ext.cc:410]   at android.app.ActivityThread.main(ActivityThread.java:5417)
art/runtime/java_vm_ext.cc:410]   at java.lang.reflect.Method.invoke!(Native method)
art/runtime/java_vm_ext.cc:410]   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
art/runtime/java_vm_ext.cc:410]   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
art/runtime/java_vm_ext.cc:410]

The root cause of this seems to be related to a Support Library bug detailed here and here
SOLUTION
In my case all I had to do was remove the snap scroll flag and rollout that change. With that change I am not seeing any of these native crashes anymore in Play Console.
In other cases if you are using a StateListAnimator on the AppBarLayout you can try this
Comment: Fantastic answer. It helped us a lot reproducing and debugging the same problem. Can confirm that removing the "snap" flag is a workaround that worked for us as well.
Answer: I was so sceptical about some dependency bug as a possible cause of the crash(es).
However, we've updated next in the latest release and crash disappears:

Build tools 26.0.3 ->  27.0.3
Android Gradle Plugin to 3.0.1 -> 3.1.0-rc01 (this also brings new data binding dependencies under the hood)
DexGuard 8.0.23 -> 8.1.10
Kotlin 1.2.21 -> 1.2.30
RxJava 2.1.0 -> 2.1.10
RxAndroid 2.0.1 -> 2.0.2
Adjust 4.12.1 -> 4.12.2
Multidex support 1.0.2 -> 1.0.3

Analyzing CHANGELOGS is quite hard and cumbersome. I spent a half of hour on it doesn't point to one obvious issue.
After reviewing over and over I think it might be dependency bug. But I can not say for sure since we also did quite many changes in these two weeks.

Android native crash


Request generate two requests on api - error

Question: I have an api in which I consume through an online store but I have a problem in the requests that the site makes. I always get two requests, one with OPTION and the other with POST, it happens that the api ends up being shuffled when I perform every time I make the first request or another one different. Can someone help me?
<code>app.use(cors({ origin:true, credentials: true, preflightContinue: true }));
</code>
Answer: I had the same issue before and it's an expected behavior related with CORS
Then you will have two request on server side but just one callback response on front-end, so my recommendation is to validate the first OPTION request on server side and in the front-end you will get just one callback response.


linux servers remote managment python fabric

Question: Can anyone give me examples for the following scenarios on python fabric? I have been searching for weeks but just can not seem to get the right formula going.
I am trying to achieve the following:

rsync a folder from local server to a remote server using a specific user and ssh keys
Start a installation remotely (java app etc) as that user
Comment: my bad gentleman and yes you can laugh.. I didnt know how to accept answers.. NOW I do..
Comment: Maybe you should post what you tried unsuccessfully so someone can point you in the right direction.  And you should accept answers to your older questions if they helped you.
Comment: Did you consider accepting some of the answers to your questions? This will encourage people to answer any new questions.
Answer: Here is a snippet of what I was playing with:

def deploy():
  if os.path.exists('%s/media' % os.getcwd()):
    print(green("Install Media Found..."))
    print('rsync -vazC --force --delete --exclude-from=%s/rsync_exclude.txt -e "ssh -p%s" %s/ %s@%s:%s' % (os.getcwd(), env.port, os.getcwd(), env.user, env.host, deploy_to));
  else:
    print(red("Install Media Not Found!"))
    print('rsync -vazC --force --delete -e "ssh -p%s" %s/ %s@%s:%s' % (env.port, os.getcwd(), env.user, env.host, deploy_to));


Debian PHP 5.3 APD compile problems

Question: I've been trying to install APD on Debian using pecl install apd. However, the command fails when entering the make stage:
make
/bin/sh /src/apd-1.0.1/libtool --mode=compile cc  -I. -I/src/apd-1.0.1 -DPHP_ATOM_INC -I/src/apd-1.0.1/include -I/src/apd-1.0.1/main -I/src/apd-1.0.1 -I/usr/include/php5 -I/usr/include/php5/main -I/usr/include/php5/TSRM -I/usr/include/php5/Zend -I/usr/include/php5/ext -I/usr/include/php5/ext/date/lib  -DHAVE_CONFIG_H  -g -O2   -c /src/apd-1.0.1/php_apd.c -o php_apd.lo
mkdir .libs
 cc -I. -I/src/apd-1.0.1 -DPHP_ATOM_INC -I/src/apd-1.0.1/include -I/src/apd-1.0.1/main -I/src/apd-1.0.1 -I/usr/include/php5 -I/usr/include/php5/main -I/usr/include/php5/TSRM -I/usr/include/php5/Zend -I/usr/include/php5/ext -I/usr/include/php5/ext/date/lib -DHAVE_CONFIG_H -g -O2 -c /src/apd-1.0.1/php_apd.c  -fPIC -DPIC -o .libs/php_apd.o
/src/apd-1.0.1/php_apd.c: In function 'zif_override_function':
/src/apd-1.0.1/php_apd.c:615: warning: 'zend_get_parameters_ex' is deprecated (declared at /usr/include/php5/Zend/zend_API.h:222)
/src/apd-1.0.1/php_apd.c: In function 'zif_rename_function':
/src/apd-1.0.1/php_apd.c:669: warning: 'zend_get_parameters_ex' is deprecated (declared at /usr/include/php5/Zend/zend_API.h:222)
/src/apd-1.0.1/php_apd.c: In function 'zif_apd_set_pprof_trace':
/src/apd-1.0.1/php_apd.c:792: warning: 'zend_get_parameters_ex' is deprecated (declared at /usr/include/php5/Zend/zend_API.h:222)
/src/apd-1.0.1/php_apd.c: In function 'apd_zend_startup':
/src/apd-1.0.1/php_apd.c:967: error: 'struct _zend_compiler_globals' has no member named 'extended_info'
make: *** [php_apd.lo] Error 1

Downloading the source, phpizeing and compiling myself leads to the same thing.
And help with why this is and how to get around it would be much appreciated!
Answer: APD doesn't compile with PHP 5.3. See bug.
Try apply patch. Edit apd-1.0.1/php_apd.c, change this line:
CG(extended_info) = 1;

to
CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;

Comment: Are you sure it's "GC..." and not "CG..."? Because I downloaded apd 1.0.1 and there's just "CG..." :)

Debian PHP 5.3 APD compile problems


Re-downloading Microsoft SQL Server 2008 Standard because of license issues?

Question: I have many clients who have purchased Microsoft SQL Server 2008 Standard. Unlike other Microsoft software, there is not a serial number provided for each customer to install the software. Furthermore, Microsoft's TechNet website lists this information about SQL Server instead of providing a key:
"This product is pre-pidded."
This means that the configuration file for SQL server contains your serial number instead of manually entering it.
My question is then: does this serial change for each customer?
The reason I ask: I'd rather not download a 3.2GB disc image over and over again for each of my customers individually. But, I don't want to risk using the same image over and over again resulting in Microsoft banning the serial for over use (as opposed to each customer using their copy with THEIR serial number.)
Comment: Clients in what way? Technet software is licensed only for evaluation, not production.
Comment: Because I work in so many different places, I use my TechNet software to recreate their production environments in my office (on a smaller scale). This way I can learn how to deploy and implement new software before doing it in a production environment. This office equipment is constantly being formatted and redone to match different situations.

I would never use TechNet software for non-testing installations. However, I sometimes have used the TechNet media in conjunction with legit serial numbers (i.e. customer's laptop has a serial underneath, but they did not provide me with a disc.)
Answer: 1) The Technet version of SQL server is not meant to be used for your customer deployment (because of the pre-PIDding) - the SQL Server Small Business Edition is the same.
2) SQL Server does not require any kind of activation, and does not "phone home", so the key you are using will be valid forever, nomatter how many times it is used.
Use this information as you will, however just as long as the owns the correct licenses, I can't imagine you'll get any issues except if you're audited, and if that's the case then the discrepancy can be easilly explained.
Answer: As others have stated, TechNet software is for evaluation use only, not production use. If your clients have purchased SQL Server then they should have each received their own installation media.
Comment: Everything we order is eOpen only, which means that there is no physical media.
Comment: Gotcha. If it were me, I would download the software for each customer from their eOpen account and burn it to CD\DVD. A little inconvenient maybe, but best in the long run IMHO.


Problemas com struch e funções em c

Question: #define FICH "Dados.Dat"  /* Ficheiro  com os Dados */
#define DIM 30

FILE *fp;  /* Variavel Global pois e' util ao longo do prog. */
int cont = 0;

typedef struct
{
  char Nome[DIM+1];
  char Tipo[DIM+1];
  int Ano[DIM+1];
  int Tempo[DIM+1];
  int Duracao[DIM+1];
  char Desc[DIM+1];
  int Data[11];
  char Pais[DIM+1];
  char Lingua [DIM+1];
  char Empresa[2*DIM+1];
  char elenco[DIM+1];
  char Diretor[DIM+1];
  int ini[4];
  int fim[4];
  char Status; /* '*' Indica que o registo esta apagado */
} PRODUCAO;

void Mensagem(char *msg);

/* Le os dados de um registo introduzidos pelo utilizador */

 void Ler_Producao(PRODUCAO *p)
{
  int i;
  printf("titulo da producao    : "); gets(p->Nome);
  printf("Tipo de producao    : "); gets(p->Tipo);
  printf("ano de producao   : "); scanf("%d",&Ano);
  printf("duracao da producao em minutos : "); gets(p->Duracao);
  printf("tempo da producao em dias   : "); gets(p->Tempo);
  printf("data do lancamento    : "); gets(p->Data);
  printf("breve descrição ate 30 palavras  : "); gets(p->Desc);
  printf("pais onde foi produzido : "); gets(p->Pais);
  printf("lingua da producao    : "); gets(p->Lingua);
  printf("Empresa distribuidora    : "); gets(p->Empresa);
  printf("Diretor    : "); gets(p->Diretor);

    while (p.elenco!="s" || p.elenco!="S" || cont<=20) {
    printf("\nindique um membro do elenco ,se quiser sair escreva apenas a letra S.:");
    scanf("%29s", &p->elenco[i]);
    i++;
    if  (p->elenco[i] == 'S' && p->elenco[i] == '\0') break;
    else cont++;
}

  p->Status=' ';
  fflush(stdin);

}

/* Mostra no ecra, os dados existente no registo */

void Mostrar_Producao(PRODUCAO )
{
  printf("Titulo.:%-30s\n",Nome);
  printf("Tipo.:%-30s\n",Tipo);
  printf("Ano de producao.:%4d\n",Ano);
  printf("Duracao.:%3d\n",Duracao);
  printf("Tempo que demorou a produzir.:%3d\n",Tempo);
  printf("Data.:%-10s\n",Data);
  printf("Breve Descricao.:%-30s\n",Desc);
  printf("Pais.:%-30s\n",Pais);
  printf("Idioma.:%-30s\n",Lingua);
  printf("Empresa Distribuidora.:%-60s\n",Empresa);
  printf("Diretor.:%-30s\n",Diretor);
  for (int i = 0; i < cont; i++) printf("\nElenco: %s", elenco);
}

void Listar()
{ long int N_Linhas =0;
  PRODUCAO reg;
  rewind(fp);
  while(1)
   {
    if (fread(&reg,sizeof(reg),1,fp)!=1) break;/* Sair do Ciclo */
    if (reg.Status=='*') continue ;  /* Passa ao proximo */
    Mostrar_Producao(reg);
    N_Linhas++;
    if (N_Linhas%20==0)
      Mensagem("PRIMA <ENTER> para continuar . . . ");
   }
 Mensagem("\n\nPRIMA <ENTER> para continuar . . . "); /* No fim da Listagem             */
}

void Inic()
{
  fp=fopen(FICH,"r+b"); /* Tentar Abrir */
  if (fp==NULL)
   {
    fp =fopen(FICH,"w+b");   /* Criar o Ficheiro */
    if (fp==NULL)
      {
       fprintf(stderr,"ERRO FATAL: Impossível Criar o Ficheiro de Dados\n");
       exit(1);
      }
   }
}
main()
{
    char  Opcao;
    Inic();
    while ((Opcao=Menu(MainMenu))!=OP_SAIR)
     switch(Opcao)
    {
 while((Opcao=Menu(ProducaoMenu)) |=OP_PRODUCAO_SAIR)
                             switch (Opcao)
                             {
                                    case OP_PRODUCAO_INSERIR:         Inserir_Producao(); break;
                                    case OP_PRODUCAO_ALTERAR:     Alterar_Producao(); break;
                                    case OP_PRODUCAO_APAGAR:      Apagar_Producao();  break;
                            case OP_PRODUCAO_LISTAR: Listar(); break;
                             }

Quando eu tento listar os dados inseridos nos casos numéricos o programa nao me da o valor introduzido mas outro valor que suponho que seja a posição onde se encontra.
e a função de introdução de elenco nao consigo fazer que pare porque usei um for so que nao consigo usar o while alguem sabe uma forma de reparar isto?
Comment: while (p.elenco!="s" || p.elenco!="S" || cont<=20) como você criou um ponteiro o ideal não seria usar -> ?
Comment: usar -> em qual caso?
Comment: https://pt.stackoverflow.com/questions/51180/diferen%C3%A7a-real-entre-operador-ponto-e-operador-seta-em-c parece que não existe esta diferença em C, em C++ (Que eu tenho o costume de usar) . é para acessar um membro de uma classe ou struct e -> é usado para acessar um membro de um ponteiro
Comment: eu quero os membros nao o valor de ponteiro esse é o meu erro eu nao sei como aceder aos valores e nao aos ponteiros.

 é o q da estar distraído nas aulas xD
Answer: Sua função Mostrar_Producao está toda errada, aliás é incrível que esteja compilando:
void Mostrar_Producao(PRODUCAO) {
  printf("Titulo.:%-30s\n", Nome);
  printf("Tipo.:%-30s\n", Tipo);
  printf("Ano de producao.:%4d\n", Ano);
  printf("Duracao.:%3d\n", Duracao);
  printf("Tempo que demorou a produzir.:%3d\n", Tempo);
  printf("Data.:%-10s\n", Data);
  printf("Breve Descricao.:%-30s\n", Desc);
  printf("Pais.:%-30s\n", Pais);
  printf("Idioma.:%-30s\n", Lingua);
  printf("Empresa Distribuidora.:%-60s\n", Empresa);
  printf("Diretor.:%-30s\n", Diretor);
  for (int i = 0; i < cont; i++)
    printf("\nElenco: %s", elenco);
}

Primeiro que o parâmetro não está definido, e cada variável não está vindo do parâmetro. Forma correta:
void Mostrar_Producao(PRODUCAO *p) {
  printf("Titulo.:%-30s\n", p->Nome);
  printf("Tipo.:%-30s\n", p->Tipo);
  printf("Ano de producao.:%4d\n", p->Ano);
  printf("Duracao.:%3d\n", p->Duracao);
  printf("Tempo que demorou a produzir.:%3d\n", p->Tempo);
  printf("Data.:%-10s\n", p->Data);
  printf("Breve Descricao.:%-30s\n", p->Desc);
  printf("Pais.:%-30s\n", p->Pais);
  printf("Idioma.:%-30s\n", p->Lingua);
  printf("Empresa Distribuidora.:%-60s\n", p->Empresa);
  printf("Diretor.:%-30s\n", p->Diretor);
  for (int i = 0; i < cont; i++)
    printf("\nElenco: %s", p->elenco);
}

Outro problema com seu código é que você aparentemente quer que o elenco seja um conjunto de pessoas(visto esse for nessa função), porém você declarou o elenco apenas como um array de char. A questão é: Seu "elenco" é um conjunto de caracteres, ou uma lista de palavras? No segundo caso, você precisa declarar uma lista de array de caracteres:
  char elenco[NUMERO_DE_MEMBROS_DO_ELENCO][DIM + 1];

Existem outras formas de fazer esta lista(ex. usando char* para ter um numero dinâmico de membros do elenco ao invés de um número estático definido na compilação), e para isso sugiro estudar como funcionam ponteiros e memória dinâmica em C.
Finalmente, reveja sua função Ler_Producao() em particular o while que verifica p.elenco - tem certeza de que não quer ver p->elenco?
Quando compilar o programa, ligue as opções -Wall -Wextra, pois elas mostram mensagens servem como dicas para encontrar bugs no programa.
Comment: entao como é que posso corrigir meu mostrar_producao

Problemas com struch e funções em c


Basis of functions from N to R

Question: Show that the space of functions $f: \mathbb{N} \to \mathbb{R}$ does not have a countable basis.
This is a problem I found a few weeks ago and I'm really stuck on it... I haven't thought of a good way to do it so could someone please provide a solution?
Comment: Hint: what do you know about infinite cardinalities? Try comparing the cardinality of $\mathbb{N} \rightarrow \mathbb{R}$ with the cardinality of a real vector space with a countable basis?
Comment: @RobArthan Both cardinalities are the same as cardinality of $\mathbb{R}$.
Comment: Do you know Cantors countable argument?
Comment: I don't really understand what you're getting at with the cardinality thing...
Comment: @i707107: you are right, my error. There is a correct answer to the question on the link in Arthur's comment. I will flag it as a duplicate.
Answer: Suppose you had a countable basis $\mathcal B$ for this space. So every function $g:\mathbb N\to\mathbb R$ can be expressed as a linear combination (with real coefficients) of finitely many members of $\mathcal B$.  It follows that, for every $g:\mathbb N\to\mathbb R$, there exists a finite set $F\subseteq\mathcal B$ and there exists a natural number $N$ such that $g(n)\leq N\sum_{b\in F}b(n)$ for all $n$.  Since there are only countably many possible $F$'s and only countably many possible $N$'s, we have a countable family of functions $n\mapsto N\sum_{b\in F}b(n)$ that suffice to majorize any $g$.  But this is impossible: Re-index those countably many functions as $\{f_k:k\in\mathbb N\}$ and observe that the function $g$ defined by  $g(n)=1+\max\{f_k(n):k\leq n\}$ is not majorized by any of the $f_k$'s (in fact it eventually majorizes every $f_k$).

Basis of functions from N to R


Colapse Menu após refresh da página com localStorage

Question: Como posso fechar um menu e o manter fechado após o refresh da página utilizando jQuery apenas?
Seria algo como neste link.
Ao clicar no botão  o menu é reduzido e assim permanece mesmo após o refresh da página.
Ao clicar novamente no botão o menu volta ao estado original e se mantém da mesma forma quando a página é atualizada.
Como posso simular este efeito sem PHP? Ou teria que usar uma session ou um cookie?
Answer: Existem algumas maneiras que você pode fazer isso vou citar 2 que venho em mente e são métodos bem simples.
API HTML5 LOCAL STORAGE
Você pode acessar o objeto localStorage e trabalhar com seus metodos setItem e getItem exemplo:
localStorage.setItem("menu","visible");
localStorage.getItem("menu");

Aqui você pode ver alguns exemplos da API e compartibilidade.

Cookies
Nada como nosso bom e famoso cookie.
Percebi que você esta familiarizado com jQuery então
acredito que este plugin do jQuery irá te ajudar bastante é o
jquery.cookie
Exemplo:
$.cookie('menu', 'visible'); //setando o valor visible para o cookie menu
$.cookie('menu') // lendo o cookie menu

Aqui esta seu repositório e toda a documentação.

Caso você queira ver essas informações armazenadas no navegar abra a ferramenta do desenvolvedor no Chrome(Menu->Ferramentas->Ferramentas do desenvolvedor ou aperte F12) clique na guia Resources, lá você pode navegar em diferentes recursos de armazenamento do browser e ver as informações armazenadas daquele domínio.
Comment: Cara, muito bom, valeu d+. Esse HTML5 é show de bola.


Identities involving product pairs of the Riemann Zeta Function

Question: Is there a relatively simple proof for the following related identities (shown true in Mathematica only) involving the the analytically continued Riemann Zeta Function, $\zeta(s)$?
$$\zeta (s) \zeta (1-s)=\left(\zeta \left(s^*\right) \zeta \left(1-s^*\right)\right)^*\tag{1}$$
and
$$\zeta (s) \zeta \left(1-s^*\right)=\left(\zeta \left(s^*\right) \zeta (1-s)\right)^*\tag{2}$$
$s$ is complex and $s^*$ is the complex conjugate of $s$.
I presume any proof will involve some variation of Riemann's Functional Equation,
$$\zeta(s)=2^s \pi^{s-1}\sin(\pi s/2)\Gamma(1-s)\zeta(1-s)$$
but this does not seem straight forward and I can't see how.
If we now assume $s=\frac{1}{2}+i z$ and $s^*=\frac{1}{2}-i z$ then $\zeta(s)\zeta(1-s)=(\zeta(s^*)\zeta(1-s^*))^*$ seems to always be a real product whatever the value of $z$, but $\zeta(s)\zeta(1-s^*)=(\zeta(s^*)\zeta(1-s))^*$ seems to only have a real product when both the Zeta Functions involved are zero or $z=0$. Assuming this is correct, does this difference follow from the proof above?
Answer: This is actually much simpler than it appears: by the Schwarz reflection principle, any analytic function $f(z)$ that is real on the real axis satisfies $f(\overline z) = \overline{f(z)}$ and thus $f(z) = \overline{f(\overline z)}$.
Comment: Thanks, and related to the method of mirror charges a bonus.


Função DATE_FORMAT - Mysql

Question: Tenho esta query abaixo, que traz todas as informações que necessito. Porem o campo resolution esta com a data (yy-mm-dd), necessito que ele retorne com a data formarada como dd/mm/yy:
select *
FROM denuncia
WHERE resolution BETWEEN ('2018-01-01') AND ('2018-12-31')
ORDER BY resolution ASC;

Com esta query, traz a data formatada:
select resolution, DATE_FORMAT( `resolution` , '%d/%c/%Y' ) AS `resolution`
FROM denuncia;

Não consigo juntar estas duas queryes para que faça o primeiro select e traga as datas formatadas conforme o segundo.
Comment: Use outro alias para a data formatada, exemplo AS `resolution_label`
Answer: Você pode especificar os campos que quer trazer da tabela:
select id, DATE_FORMAT( `resolution` , '%d/%c/%Y' ) AS `resolution`/*, demais_campos*/
FROM denuncia
WHERE resolution BETWEEN ('2018-01-01') AND ('2018-12-31')
ORDER BY resolution ASC;

Comment: Boa, deu certo. Obrigado.

Função DATE_FORMAT - Mysql


Problem with conditional rendering on React-native and AXIOS

Question: I have a big problem in react native, I have this:

getreportbycode = async() => {
        this.setState({show : false})
        if(this.state.finder !== ''){
            const token = await AsyncStorage.getItem('petra-token');
            this.setState({ jwt: token, sendform: true });
            axios.post('https://petrapi.herokuapp.com/emergence/find', {
                report_id : this.state.finder
        }, {headers: {
                Authorization: `Bearer ${this.state.jwt}`
        }
            }).then(response => {
                this.setState({report: response.data.data, sendform:false})
                console.log(this.state.report)
                this.setState({mostrar : true})

        }).catch(error => {
            this.setState({finder:'', sendform:false})
            console.log(error)
        })
        }
    }

and this :

report(report){
        if(this.state.show == true){
            return(
                <Card>
                    <CardItem>
                            <Left>
                            { report.alert.image == null
                            ?
                            <Thumbnail source={{uri:
                            'https://cdn2.iconfinder.com/data/icons/user-icon-2-1/100/user_5-15-512.png' }}

                                style={{height: 50, width: 50}}/>
                            :
                            <Thumbnail source={{uri: report.alert.image}}
                            style={{height: 50, width: 50}}/>
                            }
                        </Left>

                            <Text>
                                Creador: {report.user.name}
                            </Text>
                            {this.proccesbar(report.status)}

                    </CardItem>
                    </Card>
)}

The problem is only when i tried catch "error" i have this error message :
only when i tried catch error
Is there any way to do this correctly?
Answer: Seems like you are trying to obtain an image value of an undefined object.
So, instead of only check if report.alert.image is null, you could also verify if report and alert objects has value, like:
    (...)
    {
      (report?.alert?.image) ?
         <Thumbnail source={{uri: report.alert.image}} style={{height: 50, width: 50}}/>
      :
         <Thumbnail source={{uri: 'https://cdn2.iconfinder.com/data/icons/user-icon-2-1/100/user_5-15-512.png' }} style={{height: 50, width: 50}}/>
    }
    (...)


How do I keep my throat cleared while singing?

Question: I love to sing, but for the past couple days I've had a problem where I am in constant need of throat clearing while singing. I'd never had this problem before. I know noisily clearing it is bad for you, and I found safer methods online, but it appears to be the only effective way to remove it. How can I fix this?
Comment: If I have a bit of a cold I have a menthol cough sweet before practice, works a treat.
Answer: This is a result of excess mucus in your throat.  Fly Paper recommends granny smith apples to get rid of it.  The article also has other useful tips for keeping your singing voice healthy.

An Apple a Day Keeps the Mucus Away. Wait…that's not the saying, is it? An old opera trick is to keep a baggie of cubed granny smith apples backstage. The acid effectively "burns" off excess mucus, without damaging the vocal chords, or causing acid reflux—which eating too close to bedtime and boozing without a care will do.
Answer: These may help, but you'll learn over time what works for you:

Drink lots of water (caffinated, milky or alcoholic drinks can cause
this kind of effect)
Swallow, don't cough.
Try a sharp out-breath with your throat as open as possible, don't cough, but force a lot of air through your throat.
Answer: You can also use warm water and Tom Tom. I don't know if other countries have Tom Tom but if you know it, then put two or three inside the warm water, allow it to melt and drink. Or get an okra and chew till it smooth and swallow it. it a bit hard but you won't regret it. Do this for a week and you will sing better. Avoid frying foods and cold water/food. Drink enough water.
Comment: Hmmmm, would you mind to to get more in detail about 'Tom Tom'?


Disable or remove permissions for Scald page display

Question: It appears to me that Scald does not have a permission allowing you to set who can view the "page view" of the atom /atom/ATOMID.
Is there some way to restrict access to this page or revoke permissions from roles?
Answer: This is a partial answer, simply blocks non-logged in visitors:
<code>function MYMODULE_init() {
  // Prevent public users from seeing the atom pages
  global $user;
  if(arg(0) == 'atom' && !$user->uid) {
    drupal_not_found();
    exit;
  }
}
</code>
I would really like it if there was a permission on the scald module, logged an issue on d.o for that https://www.drupal.org/node/2512692.
Edit: there is a patch on that d.o issue which adds a permission to 'access atom page view', which is a better solution to the use of  hook_init() above.


What is the exploration behavior normally used in Policy Search based Reinforcement Learning?

Question: When using Q-learning, we have different options for a behavior policy, for e.g. we can use $\epsilon-$greedy.
But I have not seen $\epsilon-$greedy prescribed for policy search/gradient methods. When sampling trajectories in "vanilla" policy gradient, it looks like we only use softmax action selection. Is this claim true? If so, why?
Answer:
When sampling trajectories in "vanilla" policy gradient, it looks like we only use softmax action selection. Is this claim true? If so, why?

It is not strictly true. However, it is a common choice for action selection for discrete actions. The important thing is that your policy function is parametric on some features of the state, and it is possible to take the derivative of the function with respect to the the parameters.
Softmax action selection meets those constraints, and it is has a straightforward gradient with respect to parameters. You cannot use $\epsilon$-greedy, because taking the greedy action is not differentiable. Something like Gibbs/Boltzmann sampling is differentiable, so you could use that - in practice this is so similar to softmax, it is not going to be worth handling the addition of the temperature parameter.
Another common choice, when faced with continuous action space, is to output the parameters of a continuous probability distribution function, such as mean and variance of a Normal distribution.
Comment: "You cannot use ϵ-greedy, because taking the greedy action is not differentiable."  - this is a good point which I hadn't considered. Thanks!


how to parse xml which contains special characters in element attribute value .how to replace that special character with space and parse it in java

Question: am trying to parse a xml file in java using DOM OR SAX. the problem is while parsing , if my xml contains atteibute values as special character like < > " then parser throws ParserException.
for example xml file:
<?xml version="1.0" encoding="UTF-8"?>
<abc>
<check name="bike" value="apache <nice model"/>
<check name="car" value="tata sumo "style" />
</abc>

in this example xml element check has attribute value and it contains < or " . the parser takes it as invalid and throws parser exception.
now my problem is ,before parsing xml file to parser , detect that special character(< or > or " ) in xml file attribute values and have to replace that symbol(< > ") with spaces.
eg: if xml contains <
<check name="bike" value="apache <nice model"/>

replace with space
<check name="bike" value="apache  nice model"/>

.please give me suggestions.in what method it can be done...can we do it using XSD...
thanks in advance.
Answer: What about replacing those symbols with entities?
' is an apostrophe: '
& is an ampersand: &
" is a quotation mark: "
< is a less-than symbol: <
> is a greater-than symbol: >

Comment: but i have no idea about how to replace only the attribute value < as <     being new to xml,i dono how to replace only the attribute value like 'apache <nice model' as 'apache < nice model' .
Answer: One could argue if it really is xml. One rule is that xml must be well-formed. That means tags must have opening and closing, certain characters are not allowed (particularly <> in attributes) in all places.
If you can't correct this from the source, that is, produce well-formed xml, then I guess you need to first do simple search and replace as @Visher suggests and then treat it as xml or come up with your own parser
Answer: This code works pretty well (replaces '<' and '>' in quotation marks):
public static void main(String[] args)
{
    char[] characters = new char[]{'<', '>'};
    String[] entities = new String[]{"<", ">"};

    String text = "<check name=\"bike\" value=\"apache <nice model\"/> ";
    StringBuilder sb = new StringBuilder();
    boolean insideQuotation = false;

    for (int i = 0; i < text.length(); i++)
    {
        char character = text.charAt(i);

        if (insideQuotation)
        {
            int index = -1;

            for (int x = 0; x < characters.length; x++)
            {
                if (characters[x] == character)
                {
                    index = x;
                    break;
                }
            }

            if (index != -1)
                sb.append(entities[index]);

            else
                sb.append(character);

            if (character == '"')
                insideQuotation = false;
        }
        else
        {
            if (character == '"')
                insideQuotation = true;

            sb.append(character);
        }
    }

    System.out.println(sb.toString());
}

There will be a problem if you will add another quotations marks inside quotation.
Comment: really i m thankfull to u:)thanks for putting such a effort:)
Comment: if we pass a xml file and convert into string.and if we follow the same method ..whether it will work ah??


Vagrant guest's /var/www freezes when doing config.vm.synced

Question: I reviewed all synced_folder configuration @ Vagrant's website...
Host OS: Windows 7
Guest OS: Ubuntu
this is my Vagrantfile config:
# -*- mode: ruby -*-
# vi: set ft=ruby :

# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
    config.vm.box = "base"
    config.vm.hostname = "daison.vagrant.me"
    config.vm.network :forwarded_port, guest: 80, host: 8080
    config.vm.network :private_network, ip: "192.168.33.10"
    config.vm.synced_folder ".", "/vagrant", disabled: true
    #config.vm.synced_folder "C:\\Users\\daison\\vagrant\\src\\www", "/var/www"
end

I also do C:\Users\daison\vagrant\> vagrant reload
I can access my the Ubuntu's apache, by running 127.0.0.1:8080 or 192.168.33.10 or daison.vagrant.me:8080 -- IN MY HOST
so by removing the commented synced_folder and reloading again the vagrant. The results of all the IP ADDRESSES AND MY VIRTUALHOST ARE NOT ACCESSIBLE -- INT MY HOST
I tried accessing vagrant ssh
vagrant@daison: cd /var/www
vagrant@daison: /var/www$ ls

and nothing showing up...
I also tried to create a folder just to see if the synced_folder really works even if it freezes the guest folder
vagrant@daison: /var/www$ mkdir thisFolderWillAlsoShareToHost

Then a folder in my C:\Users\daison\vagrant\src\www created IN MY HOST.

I also tried to change the synced_folders to "/vagrant/sample" just to test if /vagrant/sample will be freeze the same with /var/www, after reloading the vagrant.
The result is; I can access the web-server, ofcourse it is not part in /var/www, but using ls inside /vagrant/sample freezes also.
Maybe someone could help? Thank you!
Comment: Can you explain what you mean when you say "freeze"? In the host, what is the output of `dir C:\Users\daison\vagrant\src\www`?
Comment: @ the guest station, I went to /var/www/ and tried to use `ls` and nothing shows up BUT! I can create folders like `mkdir waaaa` and ,@ the host station the `waaaa` folder also shows up, I can't even refresh my host browser using `daison.vagrant.me:8080` or `127.0.0.1:8080` or `192.168.33.10`; If i'll be commenting my custom synced_folder, the LAMP server works perfectly, I can even browse it thru the HOST using the ip-addresses and my virtual-host
Answer: From the way you're describing your problem, it sounds like you created some websites on your guest, set up a synced folder, and expected vagrant to perform a bidirectional sync between the host and the guest. That's not how it works. What enabling a synced folder does is mount a folder from your host in your guest. The contents from the host mask any existing contents on the guest. Here's what I mean:
Without a synced folder
> dir C:\Users\daison\vagrant\src\www
a_file_on_the host

$ ls /var/www
a_file_on_the_guest

With those folders synced.
> dir C:\Users\daison\vagrant\src\www
a_file_on_the host

$ ls /var/www
a_file_on_the host

If you created a new file from within the guest while the folders were synced
> dir C:\Users\daison\vagrant\src\www
a_file_on_the host
file_created_while_synced

$ ls /var/www
a_file_on_the host
file_created_while_synced

Disable the synced folder, and now you'd see
> dir C:\Users\daison\vagrant\src\www
a_file_on_the host
file_created_while_synced

$ ls /var/www
a_file_on_the_guest

So if your websites were created in the guest, they're not available any more while you sync /var/www. That's why the web server "freezes".


How to make a fair comparison between average of two groups?

Question: Here's the scenario.
When users add an item in an auction listing, they can opt for an "upgrade" where more people are likely to bid.
How can I get how times more, that items in the auction listing with the "upgrade" get bids than those without?
Here is the current data. This is an example only.

There are more items with no upgrade.

Count of items w/o upgrade: 1500
Count of items w/ upgrade: 300

Total no. of all bids

Bids on items w/o upgrade: 30000
Bids on items w/ upgrade: 10500

I could simply get the number of bids per item and compare between those with and w/o upgrades

Bids per item w/o uprade: 30000 / 1500 = 20
Bids per item w/ upgrade: 10500 / 300 = 35

So it's 75% (35/20 - 1) more bids if an item has upgrade.
So my question is, how to make a more fair comparison how much bids an item gets with upgrade vs without? Since according to data, there are much more items with no upgrades and these are usually low-valued ones (say avg of 100 USD versus avg 500 USD for those w/ upgrades). Should I also put dollar value in the formula here?
Answer: Ideally, if you want to know how much upgrading helps, you would compare those items that were upgraded and those that were not amongst similar items. Otherwise, you may compare non-comparable things (perhaps users have a very good feeling for when it is worthwhile to upgrade and only do it when it is a good idea).
One type of approach that you could use is stratification by a propensity score - one builds a model based on product characteristics (e.g. product category, value - as long as it is not established by the bidding process, which would be influenced by the upgrading - and whatever else you might have). Hopefully you have the majority of characteristics that might influence the decision to upgrade (if you are missing really important things, it is very difficult to do a really good analysis). Then you get a predicted probability to upgrade for each item and stratify by this (e.g. by deciles of predicted probabilities) and compare bids within these strata. If you want an estimate across strata, then something like a stratified negative binomial model (or negative binomial model with stratum as a factor, or zero-inflated negative binomial model etc. - it depends a bit on what the data truly looks like and whether more items received no bids than predicted by a standard negative binomial model) for the number of bids could be a logical option.
Comment: For the moment, my goal here is to display something like 'Purchase this Upgrade and get x% more bids'.
Comment: So I was thinking of getting the bids per actual item value in $. Then average that for all items

And yep. The value here is not established by the bidding process and not influenced by the upgrading.


Como fazer um efeito "balão" em um menu?

Question: Preciso fazer um efeito parecido com um balão de conversa nas tags  do meu menu, assim como essa figura, quando passo o mouse( efeito hover) o balão aparece.
Tentei fazer conforme esse site ( http://www.ilikepixels.co.uk/drop/bubbler/ ), mas não deu certo

Também preciso fazer o mesmo efeito quando passo o mouse em cima de uma imagem, aparece um "balão" com uma informação sobre a imagem
Comment: posta a parte do seu código que vc está tratando isso pra poder te ajudar melhor
Comment: Tem como [edit] a pergunta e adicionar o código desta sua tentativa? Será mais fácil identificar sua dificuldade.
Comment: você vai utilizar o ToolTip="msg", pelo menos em WPF, um cara me ajudou e deu certo, você coloca no campo em que quer utilizar e vai aparecer :),
para mais informações eu achei este site: https://www.wpf-tutorial.com/control-concepts/tooltips/
Answer:

.bubble:hover
{
position: relative;
width: auto;
height: 120px;
padding: 10px;
background: #000;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
}

.bubble:after
{
content: '';
position: absolute;
border-style: solid;
border-width: 15px 15px 0;
border-color: #000 transparent;
display: block;
width: 0;
z-index: 1;
bottom: -15px;
left: 10px;
}
PASSE AQUI

Tipo assim?
Comment: exatamente!!!!! Obrigado, deu certinho


Javascript declare a global variable within AJAX response

Question: After sending an Ajax post request, I get an array as a response. I want to use this array in another function, I tried to declare the variable before setting its value without putting it in any function.
var their_Info = [];
    $.ajax({
            url: "My PHP url",
            type: "post",
            data: {username:usernames} ,
            success: function (response) {
               their_Info = JSON.parse(response);
            });

If I want to use their_Info in a separate function I am getting undefined..
Below is the php script for reference:
<?php
header('Access-Control-Allow-Origin: *');
$usernames = $_POST['username'];
//$ids = join("','",$usernames);
$link = mysqli_connect("localhost", "root", "vKukRKWZRE", "table");
$acc_Info = array();
foreach ($usernames as $value) {
    $query = "SELECT * FROM users WHERE username = '$value'";
    $show = mysqli_query($link, $query) or die("Error");
    while ($row = mysqli_fetch_array($show)) {
        array_push($acc_Info, explode(',', $row['wear']));
    }
}
echo json_encode($acc_Info);
?>

Comment: Also, ***please*** use prepared statements for this.  You wouldn't want me to try to login as `'; DROP TABLE users; -- `, would ya?
Comment: Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call)
Comment: you have a missing closing parenthesis in your first code
Comment: Where (and when) are you trying to access `their_Info`?
Comment: Ok after reading the possible duplicate I am thinking of calling the functions that uses the variable right after changing their_Info value in the response.
Answer: If you try to use their_Info before the AJAX completes, it will obviously return undefined because AJAX is async.
The possible solution
Call your function inside success with the data as an argument. By this, you will be using the response only after the AJAX completes
Answer: Despite the comment for proper way of handling callback, you can use window.their_info to set their_info variable in global scope. Not really recommended though.


change label text on file change (custom form upload button)

Question: I just want someway to add a 'state' change so users can tell if their file has been uploaded successfully; prior to customization the default browser button displayed the 'file name' (once file has uploaded) somehow this is lost since customized to meet design needs.
Upload a photo:

Select File <input name="Text1" type="file" required>

So, I've managed to create a custom file upload button with some CSS hacking (html above, CSS below)
label.filebutton {
  width: 120px;
  overflow: hidden;
  position: relative;
  background-color: #fff;
  text-align: center;
  line-height: 1.9;
  float: right;
  margin-top: -9px;
  color: #999;
}
label span input {
    z-index: 999;
    line-height: 0;
    font-size: 50px;
    position: absolute;
    top: -2px;
    left: -700px;
    opacity: 0;
    filter: alpha(opacity = 0);
    -ms-filter: "alpha(opacity=0)";
    cursor: pointer;
    _cursor: hand;
    margin: 0;
    padding:0;
}
.caption_upload {
  margin-left: -65px;
  position: absolute;
  margin-top: 139px;
  color: #3f2a27;
}

Now it resolves as my design -- with a button looking icon with some styles and a 'select file' copy within the button and along side a caption I made 'Upload a photo' the current problem is now that I've down this, I've lost how originally the 'file name' appears upon upload -- so currently there is no way to tell if it's uploaded successfully I would like to have either the background color change to GREEN or / and the 'select a file' text changes to file name? -- any ideas?
Answer: I accomplished this with the below; if anyone else comes across similar situation:
   $("#upload").change(function() {
       $("label.filebutton").html("File Selected");
       $('label.filebutton').css({
       'color' : '#fff',
       'background' : 'green'
    });
  });

It's great -- however still doesn't display the actual 'file name'.
Comment: You will have to show the file selected in a label rather than the file input, as there are security rules about setting it dynamically.  See http://stackoverflow.com/questions/1017224/dynamically-set-value-of-a-file-input
Comment: Thanks, this just helped me out a lot.
Comment: @Gordon Gekko Actually - when I do this, the HTML change wipes out the entire contents of the label, so this: "
                        Select Profile Image
" becomes this: "new content" and my file doesn't get sent.
Comment: Hey there, create a separate question with your specs and I'll see if I can solve it for you ;)


How am I supposed to approach this problem?

Question: Problem: The Cobb-Douglas production function for an automobile manufacturer is
$$f(x,y)=100x^{.6}y^{.4} $$
Where x is the number of units of labor and y is the number of units of capital. Estimate the average production level if the number of units of labor x varies between 200 and 240 and the number of units of capital y varies between 300 and 330.
Comment: Search up "average value of a function of 2 variables"
Comment: So should I set it up like this:
\int _{200}^{240}\int _{300}^{330}\:\:\:100x^{.6}y^{.4}\:dxdy ?
Answer: The average value of a function of two variables $f(x,y)$  over a region $R$ is given by:
$$
\frac{1}{A(R)}\int_R f(x,y)dA
$$
in your case the region is the rectangle defined by: $200<x<240$ and $300<y<330$; so the area is $A(R)= 1200$ and the integral becomes
$$
\frac{1}{1200}\int_{300}^{330}\int_{200}^{240}100\; x^{0.6}y^{0.4} dx dy
$$
Comment: thanks for the help! ;^^
Comment: You  are welcome! And don't forget to accept the answer if you like it ..:)


How to place subquery in SQL Server 2008

Question: I have a main SQL query which returns stock quantity in dates between and I also need to return the stock as on date along with between dates result.
Main query:
SELECT
    TT.TranRId, MAX(TT.TInQty) AS InQty, MAX(TT.TOutQty) AS OutQty
FROM
    TReg TR, TTrans TT
WHERE
    TR.TRegId = TT.TrRegId
    AND TT.Stid = 2
    AND TR.TransDate BETWEEN '2018-08-25' AND '2018-08-28'
GROUP BY
    TT.TranRId
ORDER BY
    TT.TranRId

Sub query:
(SELECT TT.TransRId, (SUM(TT.TInQty) - SUM(TT.TOutQty))
FROM TTrans TT, TReg TR
WHERE TR.TransDate <= '2018-08-24'
  AND TR.TRegId = TT.TrRegId
  AND TT.Stid = 2 GROUP BY TT.TranRId) --AS Stock

Please help where I should include my sub query in my main query
To get output as follows:
TransRId    Stock   InQty   OutQty
----------------------------------
41          700     1       1000
42          800     5       500

Comment: [Bad habits to kick : using old-style JOINs](https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins) - that old-style *comma-separated list of tables* style was replaced with the *proper* ANSI `JOIN` syntax in the ANSI-**92** SQL Standard (**more than 25 years** ago) and its use is discouraged
Comment: Hi and welcome to SO. In addition to accurate suggest above it would be helpful if we had more details to work with to help find you an answer. Here is a great place to start.http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/
Comment: What are you trying to achieve? Running total?
Answer: I am not sure I am following your question 100%, if you are just looking to join it as a sub query the below logic should work.
SELECT TT.TranRId
    ,MAX(TT.TInQty) AS InQty
    ,MAX(TT.TOutQty) AS OutQty
    ,Stock.[Sum]
FROM TReg TR
LEFT JOIN TTrans TT
    ON TR.TRegId = TT.TrRegId
LEFT JOIN (
    SELECT TT.TransRId
        ,(SUM(TT.TInQty) - SUM(TT.TOutQty)) as Sum
    FROM TTrans TT
    LEFT JOIN TReg TR
        ON TR.TRegId = TT.TrRegId
    WHERE TR.TransDate <= '2018-08-24'
        AND TT.Stid = 2
    GROUP BY TT.TranRId
    ) AS Stock
    ON Stock.TranRId = TT.TranRId
WHERE TT.Stid = 2
    AND TR.TransDate BETWEEN '2018-08-25' AND '2018-08-28'
GROUP BY TT.TranRId
ORDER BY TT.TranRId

edit:
I noticed tt.TranRId and tt.Tran***s***RId  if this is not a typo it would need to be corrected, if not my answer will not work for you.
If you need specific dates, including the date in the join logic along with the ID would give you the appropriate result...without knowing your data set I am not sure if the TranRId is unique...sorry about that!
Comment: @Rennick Thanks for your suggestion its help me a lot and sorry for delay reply


Denoising Autoencoder not training properly

Question: I've implemented a denoising autoencoder using TensorFlow. The code is here, there is also a command line script to launch it. The code seems to work, the cross-validation error is decreasing every iteration, but the autoencoder doesn't seem to be learning good features (I'm using MNIST).
This is an example of learned features:

The parameters I used are the following:
--n_components 1000 --batch_size 25 --n_iter 100 --verbose 1 --learning_rate 0.01 --weight_images 0 --corr_type masking --corr_frac 0.5 --encode_valid --enc_act_func sigmoid --dec_act_func sigmoid --loss_func cross_entropy --opt momentum --momentum 0.9 --dropout 0.5

number of hidden units: 1000
batch_size: 25
epochs: 100
learning rate: 0.01
input corruption type and frac: masking 0.5 (set 50% of the pixels to zero)
encoder activation function: sigmoid
decoder activation function: sigmoid
loss function: cross entropy
optimizer: momentum, 0.9
encoder layer dropout probability: 0.5
The question is: what is a good choice of the hyperparameters for the MNIST dataset?
Comment: Can we ask for couple of more info? How do you initialize weights? Cause it seems your weight couldn't escape the symmetry. All look similar.  What is the final loss value?
Comment: Do you know specifically what features you should get? You have 1000 units trying to represent 10 classes for mnist, yes? So what makes you expect to get 1000 distinct features? Not all cost functions and models will interpretable features. Checkout other features learned e.g. from the [dropout paper](https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf) for MNIST on page 15 with and without dropout with 256 hidden units for a regular neural network. They have a different model  but I would argue the features learned in that paper aren't super interpretable either.
Answer: Hyperparameter choice is something that can't really be answered: sure, there are some set of procedures that can be followed, but it's largely a case of hit and trial.
Single DA's can indeed extract meaningful features, however, most of the features in case of encoding dimensions 'L' (say) > input dimensions 'D' (i.e. Overcomplete learning) will end up being random noise.
The reason for your autoencoder not learning meaningful features is because given the degree of freedom the autoencoder has in the encoding layer (i.e. L > D) it becomes quite easy for the autoencoder to learn an identity mapping of the input.
So to alleviate this problem, you have to put additional constraints in order to limit this degree of freedom.
I believe you can try the following and see what the outcome is:

The first and probably the easiest step would be to try and reduce the number of encoding layer nodes from 1000 to something little closer to the dimensions of the input, ie. 784. I would say 800 would be a good start. Visualize the features then and see if some features have improved.
Apply additional regularization constraints, say l2 regularization on the weights (and if already doing that, increase the penalty term corresponding to l2) and other such penalization techniques.
Tied weights. Use tied weights on the encoding layer and the decoding layer if not doing so already. ie.
W_decoding = W_encoding.T.
When not using tied weights, many times, either of the two layers learn larger, better weights (for the lack of words) and compensate for the poor weights learned by the other. By placing this constraint we force the autoencoder to learn a balanced set of weights. Also, it often results in improvement of training time as well as a pretty good limitation on the degree of freedom (the number of free, trainable parameters is halved!).

Give this a try. Might help.
Answer: I am also just getting into DAs, however, one thing that I noticed that you might want to think about your input dimension versus the number of hidden units. The MNIST consists of 28x28 pixel images, that is an input dimension of 784 and you also have a corruption rate of 0.5 which seems quite high. 1000 hidden nodes might not be optimal in this if you want to construct relevant features without further stacking DAs?
Would have suited better as a comment but I don't have enough rep for this.
Comment: I am just getting started too. The idea is stacking DAs, but I would expect a single DA to extract meaningful features even without stacking and fine tuning. Am I wrong? However, I'll try with a lower number of hidden nodes, thanks!
Comment: Yeah, it should definitely be possible, but naturally it seems that a lower number of hidden units would easier find a lower dimensional representation of the data (abstract features). I am not sure how you initialize the weights, but this as I understand is very important to get convergence. You want them to be in the linear region of the activation function at the start to get the gradient descent going.
Comment: I initialize the weights using a uniform random distribution between `- k * sqrt(6 / (fan in + fan out))` and `k * sqrt(6 / (fan in + fan out))` where I use k = 1 with the tanh activation function and k = 4 for the sigmoid. Thanks for making me notice that I forgot to include the weights initialization function in the code :)


Trigger ajax action by url or link

Question: I currently have a page which has a block with taxonomy terms displayed.  Each link has been made to work with ajax to display information below if clicked, generated in a module callback.
What I am trying to acheive is also have this work if linked to.  So for example my page URL is currently http://localhost/events/building01
If someone was to visit http://localhost/events/building01/printer then the information for printer would be displayed under the taxonomy term as it would if someone had clicked on the term.
My ajax links are currently setup like:
function building_block_menu()
{
  $items['events/%/%/ajax'] = array(
  'title' => 'ajax call',
  'page arguments' => array(1, 2),
  'page callback' => '_event_ajax_callback',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
  );
  $items['events/%/%/nojs'] = array(
  'title' => 'nojs call',
  'page arguments' => array(1, 2),
  'page callback' => '_event_nojs_callback',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
  );
  return $items;
}
function _event_ajax_callback($building, $type)
{
  $markup = $building . ' - ' . $type;
  $ajax_commands = array();
  $ajax_commands[] = ajax_command_html('#ajax-target', $markup);
  ajax_deliver(array('#type' => 'ajax', '#commands' => $ajax_commands));
}
function _event_nojs_callback()
{
  return "no js to be built";
}

And called from links built like:
$output .= l($term->name, 'events/$building/'.$term->tid.'/nojs', array(
            'attributes' => array('id' => 'building-term-'.$term->tid, 'class' => 'use-ajax')
            ));

Answer: The easiest option would be to add an ID to each link like link_printer and then use jQuery to parse the url, get the last fragment, and click any links that match.
var splitURL = window.location.href.split('/');
var link_id = '#link_' + splitURL[splitURL.length - 1];
if ($(link_id).length > 0) document.querySelector(link_id).click();

Comment: That works for me.  Do you know if this would work for search engine crawlers as well? Or would I need to look at creating a more complicated solution using the HTML5 history API?

Trigger ajax action by url or link