Impossible identity? $ \tan{\frac{x}{2}}$

Question: $$\text{Let}\;\;t = \tan\left(\frac{x}{2}\right). \;\;\text{Show that}\;\dfrac{dx}{dt} = \dfrac{2}{1 + t^2}$$
I am saying that this is false because that identity is equal to $2\sec^2 x$ and that can't be equal. Also if I take the derivative of an integral I get the function so if I take the integral of a derivative I get the function also so the integral of that is $x + \sin x$ which evaluated at 0 is not equal to $\tan(x/2)$
Comment: Do you know what we get when we differentiate $\tan \theta$ with respect to $\theta$?
Comment: Yes, sec^2 is the differnetial
Comment: Now, the phrase "that identity is equal to $2 \sec^2$" is wrong. The identity is actually equal to $\frac{2}{\sec^2 x } $. Do you see that?
Comment: I am saying the derivative of t is that, and that is most definitely true.
Comment: @PaulthePirate, you seem to be pretty angry at some things: mathematics, rules, etc. This is not a wise attitude to try to learn stuff. About "how will you memorize all these rules": by understanding working and practicing them: there are no many short ways here. Now, about what you say "it is most definitely true": it is not, and perhaps you meant "false" instead "true". We have that $$\frac d{dx}\left(\tan\frac x2\right)=\frac12\frac1{\cos^2\frac x2}=\frac12\sec^2\frac x2$$ , so you can see it is most definitely not-true.
Answer: Note that you seemed to have attempted finding $$\dfrac{dt}{dx} = \dfrac{d}{dx}\left( \tan \left(\frac x2\right)\right)= \frac 12 \sec^2\left(\frac x2\right)$$ However, the task at hand is to differentiate $f(t)$ with respect to $t$: i.e.,  $$\bf \dfrac{dx}{dt}\neq \dfrac{dt}{dx}$$
To obtain $\bf \dfrac{dx}{dt}$, we need to express $x$ as a function of $t$:
$$\begin{align} t & = \tan\left(\frac x2\right) \\  \arctan t & = \arctan\left(\tan \left(\frac x2\right)\right) \\ \arctan t + n\pi & = \frac x2 \\ \\  2\arctan t + 2n\pi & = x\end{align}$$
NOW we can find $\dfrac{dx}{dt}$: $$\dfrac{dx}{dt} = \frac{d}{dt}(2\arctan t + \underbrace{2n\pi}_{\text{constant}}) = \dfrac{2}{1 + t^2}$$
Comment: I know, it can be a handful, Paul.  See this link: [the inverse trig functions](https://en.wikipedia.org/wiki/Inverse_tangent#Relationships_between_trigonometric_functions_and_inverse_trigonometric_functions) relate the the right triangle. You'll also get a refresher on the derivatives and integrals of the inverse trig functions.
Comment: I don't follow the difference, it never makes sense, what comes first the function or the variable in those weird fraction notations?
Comment: The "function" is on top, the "variable" is on the bottom. I put these in quotes because often (as here) you have only a relation between two quantities, and you might want to think of either one as the variable. But in the identity you are proving, $x$ is the "function".
Comment: What you found was the derivative of $t$ with respect to $x$. That's $\dfrac{dt}{dx}$. You're asked to find the derivative of $x$ with respect to $t$: that's what's meant by $\dfrac{dx}{dt}$. So we need to find express $x = f(t)$, which we have as $x = \tan^{-1}(t) +...$. Recall the derivative of arctan t= ($\tan^{-1} t$)
Comment: That is absurd, how can I memorize all these little rules?
Comment: @PaulthePirate: Or, if you need a way to do this that doesn't directly involve the arctangent, see my answer.
Comment: That is just stupid I think, there are 111 identities in the back of my book and another 40 in the front, I am not going to waste my time and memorize all of them. I would rather pursue something that challenges your intelligence, not your ability to memorize formulas.
Comment: I agree about seeking challenge for the intelligence, and not the ability to memorize!  This identity, though, turns out to be extremely useful for **lots** of integrals.
Comment: I don't follow that magic you did to get x. n seems pretty random as well.
Comment: (@PaulthePirate: you might find it helpful to latch onto a particular example. One I found helpful: suppose you're driving in your car, and you are at position $x$ at time $t$, then your velocity is $dx/dt$ ("the change in $x$ with respect to $t$"). Of course, $x$ varies with $t$, not vice-versa (you may revisit the same position at many different times, but not vice-versa). (If you drew a graph, you'd probably draw $t$ on the horizontal axis and $x$ on the vertical axis, showing that $t$ is somehow varying of its own accord and $x$ depends on $t$, right?))
Comment: Paul: would you have written $\frac{x}{2} = \tan^{-1}(t)$? If so, you're almost there. Look at the graph of $\tan$, and notice that adding $\pi$ doesn't change anything (i.e. $\tan(x/2) = \tan(x/2 + \pi)$ - so we can't quite work out which $x/2$ this $t$ came from, but we can work it out up to adding or subtracting a few $\pi$s.
Comment: Forget the $n\pi$ or $2n\pi$: that's just showing the periodicity. It's a constant (n denoting a multiple of $\pi$) so it's lost when differentiating. The rest is just using $tan \theta = t \implies \theta = \tan^{-1} t$, except in this case, $\theta = \frac x2$.
Comment: I don't follow at all, if I have f(x) = x^2 then they both depend on eachother.
Comment: Yes, but when we differentiate $y = f(x)$ to obtain $\dfrac{dy}{dx}$, we differentiate with respect to $x$. Here we need $x = f(t) = 2\tan^{-1}t$, so we need to differentiate with respect to $t$ to find $\dfrac{dx}{dt}$. The variable appearing in the denominator of $\dfrac{dx}{dt}$ is the one we differentiate the function with respect to: here, that's $t$.
Comment: With respect to means the variable?
Comment: Yes. That's right. As you see, we can write the given equation in terms of $x$, or in terms of $t$. In this particular case, since we're asked to find $\dfrac{dx}{d\bf t}$ we need to write x = "function of $t$". And then differentiate the function "with respect to $t$."
Comment: @amWhy: Needs another TU!!! +1
Comment: TU Amy :-) $++$
Answer: Your confusion is that you're asked to find $\frac{dx}{dt}$, not $\frac{dt}{dx}$. Start with
$$
t=\tan\frac{x}{2}
$$
Differentiate both sides with respect to $t$. Using the chain rule twice you'll have
$$
\begin{align}
\frac{dt}{dt}=1&=\sec^2\frac{x}{2}\cdot\frac{d}{dt}\left(\frac{x}{2}\right)\\
&=\sec^2\frac{x}{2}\cdot\frac{1}{2}\cdot\frac{dx}{dt}
\end{align}
$$
so, multiplying both sides by 2 and dividing by $\sec^2(x/2)$ we get
$$
2\cos^2\frac{x}{2}=\frac{dx}{dt}
$$
and when $\tan\alpha= t$ we have $\cos\alpha = 1/\sqrt{t^2+1}$ (draw a triangle), so
$$
\cos\frac{x}{2}=\frac{1}{\sqrt{t^2+1}}
$$
so we have, from the above displayed equation,
$$
\frac{dx}{dt}=\frac{2}{t^2+1}
$$
as required.
This technique is known as implicit differentiation and is very useful in cases like this where you don't have a function defined in terms of the variable with which you want to differentiate.
Answer: Let us rewrite what you have with some added notation. You are given
$$
t(x)=\tan(x/2),
$$
a function of $x$. You are asked to find the derivative of the function $x$ with respect to the variable $t$. You must first express $x$ as a function of $t$. As other have mentionned, taking $\tan^{-1}$ on both sides yields
$$
\frac{x}{2}=\tan^{-1}(t)+n\pi.
$$
Note that the $n\pi$ is there because of the periodicity of $\tan$, but won't change a thing when we differentiate with respect to $t$.
Now we have
$$
x(t)=\tan^{-1}(t)+2n\pi
$$
and we can find
$$
\frac{dx}{dt}=\frac{2}{1+t^2}
$$
provided you know the derivative of $\tan^{-1}(t)$.
Comment: I don't and I also don't follow how to convert t into x and such.
Answer: You're wrong, the identity is correct.  Note that $t = \tan(x/2)$ implies
$x = 2 \arctan(t) + 2 n \pi$.
Comment: I don't follow that implication.
Comment: What properties of arctan do you know?
Answer: Paul. You've asked a couple of nice questions here, if I understand you right:

1) Given that $t$ can be expressed as a function of $x$ (specifically, you asked about the case where $t = \tan(\frac{x}{2})$), how can we find $\frac{dx}{dt}$, if it exists?
2) If we know that $\tan(\frac{x}{2}) = t$, then why does $x = 2\arctan(t) + 2n\pi$?

The answer to the first question comes from the chain rule. By the chain rule, we can write
$$\frac{dx}{dx} = \frac{dx}{dt} \frac{dt}{dx};$$
since we know that $\frac{dx}{dx} = 1$, this tells us that
$$ 1 = \frac{dx}{dt} \frac{dt}{dx} \implies \frac{dx}{dt} = \frac{1}{\frac{dt}{dx}}.$$
(This proof assumes that $x$ can be expressed as a differentiable function of $t$, but that assumption is valid here, so all is well.)
In your case, we see that
$$ t = \tan(\frac{x}{2}) \implies \frac{dt}{dx} = \sec^2(\frac{x}{2}) \cdot \frac{1}{2} $$
by the chain rule, and so
$$\frac{dx}{dt} = \frac{1}{\frac{dt}{dx}} = \frac{2}{\sec^2(\frac{x}{2})}$$
But $\sec^2(x) = 1 + \tan^2(x)$, and so
$$\frac{dx}{dt} = \frac{2}{\sec^2(\frac{x}{2})} = \frac{2}{1 + \tan^2(\frac{x}{2})} = \frac{2}{1 + t^2} $$
where to get the last equality I just plugged in $\tan(\frac{x}{2}) = t$.
Your second question has a fairly simple answer: the $\arctan(t)$ function as mathematicians usually define it outputs an angle $\theta$ between $-\frac{\pi}{2}$ and $\frac{\pi}{2}$, such that $\tan(\theta)$ = $t$. We have to bear in mind that, when we take $\arctan(\tan(\frac{x}{2}))$, we may not get back $\frac{x}{2}$ - just $\theta$. However, we know for certain that $\frac{x}{2} = \theta + n\pi$ for some integer $n$ and some $\theta$ between $-\frac{\pi}{2}$ and $\frac{\pi}{2}$ (ponder this if it is not clear). This $\theta$ will be precisely the one which $\arctan$ returns for the argument $t = \tan(\frac{x}{2})$, and so this $\theta$ is $\arctan(t)$. Thus,
$$\frac{x}{2} = \arctan(t) + n\pi$$
which is the second thing you were having trouble with.
Hope this helps!


Why does RAID5 with an odd number of data disks have poor write performance

Question: According to the comments on my other question, it's more than possible that the reason my MD RAID array is performing poorly is because my RAID5 array has 5 data disks. I've tried searching for information on why this is, but haven't found anything, so I'm looking for more information about why this is, and what sort of impact it can have versus having 4 data disks.
Comment: I disagree that the original question has garnered an answer that demonstrates that the problem isn't with Samba.  A *comment* on that question has intimated that the problem *may* be RAID-related, and now a separate question has been asked about RAID performance issues.  Think of it this way -- if the original question was rewritten to be this question, wouldn't it make the comments on that question (and any answers that the original question may have gotten) look like complete nonsense?  If so, the question shouldn't be rewritten.
Comment: @MDMarra: I disagree; this is a separate question that can standalone, with a reference to a previous question for background if anyone wants more context.
Comment: possible duplicate of [Samba running slowly when writing files](http://serverfault.com/questions/363784/samba-running-slowly-when-writing-files)
Comment: Seriously, this should be addressed in your original question. No need to keep posting dupes with links to the original.
Comment: @MDMarra: Then close the old question. Rewriting the entire question isn't productive either. The issue is nothing to do with Samba, and everything to do with the hardware.
Comment: You should edit your original question to be relevant. As you uncover more details to a problem, it's appropriate to refine your question to be more specific rather than discarding it and opening a new one. If you have a problem, you can open a question on [meta] about it.
Comment: @womble the initial question was about a performance issue that the OP initially attributed to Samba, but is actually possibly a problem with his disk geometry. This is the same exact problem as the original just without the (wrongful?) attribution to Samba.
Comment: http://meta.serverfault.com/questions/3073/how-much-should-you-refine-a-question-before-opening-a-new-question
Answer: I have never heard of any sort of "odd/even" performance impact of a RAID5/6 array, and like you, I can't find anything useful from a quick web search.
There are potential issues with the number of disks and write performance in a RAID5/6 array, but they're related to "more disks == slower writes", because (depending on the implementation) the RAID system may want to read off all the data disks in the stripe in order to recalculate parity (so for a 6-disk RAID5, it would involve 4 reads -- one for each of the unchanged data blocks in the stripe -- and two writes -- one for the changed block, and one for the parity block).  A good implementation will instead read the changed data block and the parity block, recalculate the parity, and write to the changed data block and the parity block, meaning two reads and two writes, regardless of the number of disks in the set.
Answer: It's the reverse. The issue is when the number of drives is even with RAID 5. With RAID 5, the ideal number of drives is one more than a power of 2, so 5 drives is one of the optimum sizes. This allows the implementation to make both the block size and the stripe size powers of two.
With five drives, the stripe size (amount of user data that must be written to the RAID array as a unit) will be four times the block size (amount of user data that must be written to a drive as a unit). The block size must be multiple of 512 bytes (or 4KB on newer drives), frequently it must be a power of two equal to or greater than the drive's native block size. So with five drives, the stripe size must be 2KB or more (16KB or more on 4KB drives).
As a general rule, the performance boost of adding an additional spinddle will exceed the performance cost of having a sub-optimal drive count. So an array with six drives will still typically outperform an array with five drives. On typical RAID 5 performance graphs, 3 drives and 4 drives will be right near each other, with 4 slightly on top. Then a bit up will be 5 drives and 6 drives right near each other with 6 slightly on top.
Comment: this is nonsense, any layer above the controller treats disks as a continuous range of sectors.  there's no need to make the stripe size a power of two.  besides, a simple big file transfer would be mostly linearly writing whole stripes.  the write amplification factor (two reads and two writes per write command) applies only for small writes.  long writes just overwrite the whole stripe, so the factor is just (N+1)/N writes instead of 2N reads+2N writes
Comment: The final scheduling is done at the drive level, so neither 2MB nor 2.5 MB multiples matter at all.  The individual drives just see requests that are as large as possible, given the original request, the readahead length, and how the request is split across the drives.  As long as the original request + readahead is larger than the stripe size, the drives will all get a sufficiently large request for optimal throughput.  So if the application asks for 1 MB and the readahead and stripe width are 2.5 MB, then all drives get requests for 512k+.
Comment: For partial stripe writes, md has to read the parity block, correct it for the new data, then write the new data plus the new parity  block.  Neither reading nor writing whole stripes is required, and even if it did, there still would be no reason to keep stripes an even power of two.
Comment: I'm a bit confused. Isn't the stripe size independent of the number of disks (edit: and user-specifiable)? What do you mean by "block"? Disk sector size, which is 512B or 4KB?
Comment: No, the stripe size is not independent of the number of disks. If there are five disks, the stripe size must be four times the block size. That's how RAID 5 works and how it tolerates the loss of a disk. (It's `n-1` for RAID 5, `n-2` for RAID 6.) [See Wikipedia.](http://en.wikipedia.org/wiki/Standard_RAID_levels#RAID_5) I explained what I meant by block size, "amount of user data that must be written to a drive as a unit". It can be any multiple of the disk's native size.
Comment: You are confusing the block size with the stripe size. You can specify the block size, and it's independent of the number of disks (but must be a multiple of the drive's native block size). But then the stripe size will be, for RAID 5, the block size times the number of disks minus one. That's how RAID 5 works.
Comment: Blocks have nothing to do with it.  Typical stripe factors are 64-512KB.  Recent versions of `mdadm` default to 512KB so a 4 disk array will have a stripe size of 2 MB, and a 5 disk will be 2.5 MB.  Whether it is 2 or 2.5 MB makes no difference; there is no reason it should be an even power of two.
Comment: How can a 4 disk RAID 5 array have a stripe size of 2MB? That would be 2/3MB per disk. If it writes, say 512KB per disk, that's 512KB*3 of data and 512KB of parity for each stripe.
Comment: @psusi: Whether it is 2MB or 2.5MB makes a reasonably significant difference. Requests from higher levels tend to be for aligned blocks. With 2.5MB blocks having to go out to the RAID, a higher fraction of writes won't be complete blocks and more writes will require a preceding read. Let me put it to you this way -- if we did a survey of write sizes from major applications, do you think more write clusters (sequential writes from the same source) would be multiples of 2MB in size or multiples of 2.5MB in size? Even if you use, say, a 1MB buffer, two buffers will fit perfectly.
Comment: So you're saying that bulk writes with sizes that are even multiples of 2.5MB are just as common as bulk writes that are multiples of 2MB? That seems a bit implausible to me.
Comment: it doesn't matter a bit.  the IO schedulers split and join operations as needed.  long (whole file size) writes are the perfect opportunity for that.
Comment: Oops, yes, I was off by one, yes, it's 5 disks for 2 MB.  The buffer size the application uses doesn't matter since it just goes to/from the kernel cache and is transfered to/from the disks from there.  As long as the read-ahead size is set appropriately, the disks will be kept saturated no matter what the stripe width is.
Comment: After they split and join operations, do you think they wind up with more 2MB operations or 2.5MB operations?
Comment: the final scheduling is per device, written sequentially and aligned.
Comment: Right, and when that final scheduling is done, do you think there are more operations that align on multiples of 2MB or operations that align (start or end) on multiples of 2.5MB? That is, which underlying stripe size do you think will require the greatest number of reads-before-writes? Stripe sizes that are powers of two better adapt to buffers that are powers of two and most software uses buffer sizes that are powers of two.
Comment: @psusi: That's nonsense. Whether an operation is sent to the drive as a pure write or a "read-then-write" depends on whether it can be aggregated to a multiple of the stripe size. So that aggregation has to be done before drive level, at the RAID level.
Comment: @psusi: The reason would be that fewer reads are required to write because fewer partial stripe writes are necessary. Fewer partial stripe writes are necessary because after aggregation, at the RAID layer, more writes will be even multiples of 2MB than of 2.5MB.
Comment: Aggregation does not care about even powers of two.  It aggregates as much data as it can.  If your load tends to be small random IO, then the more disks you add, the more partial writes you will get, but for sequential IO, the application can write one byte at a time if it wants to, and the kernel will aggregate it into whole stripes.  In either case, whether the stripe size is an even power of two does not matter.
Comment: @psusi: I don't understand why you keep taking us in circles. Yes, there's aggregation. But **after aggregation**, if the write is an even multiple of the stripe size, no read before write is needed. Otherwise, a read is needed before the write. Do you think more writes will be even multiples of 2MB or will be even multiple of 2.5MB? If more writes are even multiples of 2MB than 2.5MB, then a RAID with a stripe size of 2MB will perform better since less data will need to be read in order to write.
Comment: If you are writing a continuous stream of data, the aggregated writes will be on the order of 100mb, so whether the underlying stripe size is 2 or 2.5 mb doesn't matter; each stripe will be completely written as a whole until the cache size is reduced enough, then writes will stop for a bit to allow more to be aggregated into several additional whole stripes.  It's not like the kernel stops aggregating at 2 mb then tries to write a partial stripe every time.
Comment: @psusi: You're taking us in circles. Right, we all agree on that. Again, the question is: After this aggregation, do you think more writes will be an even multiple of 2MB or more writes will be an even multiple of 2.5MB?
Comment: Neither.  As I said before, the smaller size will be more prevalent for random IO, simply because it is smaller, not because it is an even power of two.  For sequential IO, you will end up with full stripe writes whether the stripe size is 1, 2, 2.5, or 3 MB.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/2716/discussion-between-david-schwartz-and-psusi)


Saving Canvas image to mysql

Question: Every 5 seconds I have my javascript running to call the update.php file (which will hopefully add the base64 code to the mysql - although yet to figure out).
Currently, I just have the base64 code writing out to a text area called debugConsole.
I just don't get how I'm supposed to pass the javascript variable to my php update file.
HTML:

        <canvas id="testCanvas" width="300" height="300"></canvas>

    <textarea id="debugConsole" rows="10" cols="60">Data</textarea>

PHP:
<?php

$random =  rand();
$game = $_GET["game"];

mysql_query("UPDATE paint_s SET paint_points='$random' WHERE id ='$game'") or die(mysql_error());
echo "Updated";
?>

Sorry for my lack of knowledge, I have been doing a few tutorials and was just trying to expand on the tutorial.
Answer: First thing you want to do is open your request
ajax.open("POST",'testSave.php',true);

then want to send your data as application/x-www-url-form-encoded so set it in the content type
ajax.setRequestHeader('Content-Type', 'application/x-www-url-form-encoded');

To make sure your data is properly encoded use encodeURIComponent
var postData = "canvasData="+encodeURIComponent(canvasData);

You should also check the status to see if the request actually suceeded
if (ajax.readyState == 4)
{
    if (ajax.status == 200){
    //success
    }
    else{
    //failure
    }
}

I don't know if saving a base64 encoded image every 5 seconds is a good idea though.

Saving Canvas image to mysql


Aplicações GUI - Agilizando! Como?

Question: Olá, pessoal!
Minha missão é dar agilidade e fluidez a um software... deixar ele sem aquelas travadas constantes em cada For...
Para isso eu criei um problema e gostaria de saber se alguém consegue resolver. A solução será aplicada em grande parte do meu sistema
A função abaixo é responsável por realizar diversos cálculos complexos e ao ser chamada trava o formulário por completo. O desafio é rodar isso aí em segundo plano e ainda receber a resposta: (true/false)
Public Function MinhaFuncao() As Boolean

    Try
        'Realiza os cálculos'

        Return True
    Catch ex As Exception

        Return False
    End Try

End Function

Já tentei utilizar Threads... Ficou algo assim:
Dim minhaThread As Threading.Thread
minhaThread = New Threading.Thread(AddressOf MinhaFuncao)
minhaThread.IsBackground = True
minhaThread.Start()

De fato funcionou! Mas não me retornou nenhuma resposta...
Bom, de toda forma, agradeço desde já!
Answer: A utilização de threads directamente é desaconselhada.
O ideal é usar uma abstracção de alto nível, como Task ou Task<T>. Estas encapsulam lógica que deve ser executada assincronamente, e propagam os valores de retorno.
Além disso, também propagam excepções - se alguma excepção ocorrer na background thread, será re-lançada na thread principal com o uso de await, Wait, ou Result.
Nao estou familiarizado com a sintaxe de VB.NET, mas eis como o fazer em C# usando Task.Run (que defere o trabalho para uma thread da thread pool):
bool result = await Task.Run(MinhaFuncao);

(Nota: se isto for um projecto pessoal, aconselho a usar C# em vez de VB.NET. É muito mais fácil encontrar recursos online e materiais de ajuda para C#)

Após um pouco de investigação, julgo que a sintaxe em vb.net seja:
Await Task.Run(AddressOf MinhaFuncao);

Comment: Entendi dcastro!

Essa é uma ótimo solução cara. Funcionou aqui!! Heheheh

Sobre migrar para C#... eu até já considerei, mas nasci no VB, não dá para abandonar agora kkkkk E no fundo os dois compartilham das mesmas ferramentas ^^
Comment: Solução: Dim resposta As Boolean = Await Task.Run(Of Boolean)(Function() (MinhaFuncao))

Aplicações GUI - Agilizando! Como?


Changing the capstyle of ticks in matplotlib

Question: I want to use a round capstyle for ticks. I tried the following, but it does not work.
import matplotlib.pyplot as plt
# better tick visiblity to check the capstyle
plt.rcParams.update({
           'figure.dpi': 150,
          u'xtick.major.size': 5.0,
          u'xtick.major.width': 2,
          })

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4])

tl = ax.xaxis.get_ticklines()
for i in tl:
    i.set_solid_capstyle('round')
plt.show()

Answer: So, The reason that this does not work is that the tick marks are implemented single point lines with the ticks drawn as markers.
In [127]: [i.get_linestyle() for i in ax.xaxis.get_ticklines()]
Out[127]:
['None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None',
 'None']

and
In [128]: [i.get_marker() for i in ax.xaxis.get_ticklines()]
Out[128]: [2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3]

see docs for mapping between ints -> shape, this is alternating 'tickup' and 'tickdown'.
This does let you do semi-cute things like
[i.set_marker('o') for i in ax.xaxis.get_ticklines()]

which gives

If you use this, when upstream breaks it will be your problem
To get what you want you can do reach well into the guts and set the capstyle on the tick marks:
for i in ax.xaxis.get_ticklines():
    # reach in and poke the guts
    # USE AT YOUR OWN RISK
    i._marker._capstyle = 'round'
    # this is not officially supported

note this uses not 1, but 2 private attributes and will be broken by the traitlet refactor that is coming in the next year (targeted for v2.1).  This will also be re-set to the hard-coded value of 'butt' on _recache calls (which I don't remember off the top of my head exactly when that gets called).
I do not think you really want do to this:

as it rounds both end of the ticks, not just the side pointed in (but then maybe an smaller tick sizes the rounded 'out' side will be hidden by the spine)
Comment: @tillsten I can't stress enough though that you **should not actually do this** as there is a mid-term plan to break it!  I looked into using a `Path` to draw marker a half-rounded marker. I think it is possible, it will just require some finagling, and sorting out what 'width' and 'length' means in that case.
Comment: Thanks! Nice rounded one sided rounded markers would make another nice feature
Comment: I will have a look at a possible path solution also. Btw is there a mpl setting to disable ticks when their location is exactly at the spine position?
Comment: Not that I know of, but I don't know the spine/tick/marker code super well.  Most of that code is very old and for the most part 'just works'.  I tend to know the code people report bugs against ;)
Comment: Unfortunately, this method doesn't work any more with the new `matplotlib` version. Is there another workaround?


Normal Distribution with $95\%$ confidence interval

Question: n <- 10
nsims <- 10000
true_ci_cov <- vector(length=nsims)
est_ci_cov <- vector(length=nsims)
for(i in 1:nsims){
    data<-rnorm(n, mean=1, sd=2)
    mean_dat<-mean(data)
    sd_dat<-sd(data)
    ci_true_low <- mean_dat - 1.96*2/sqrt(n)
    ci_true_high <- mean_dat + 1.96*2/sqrt(n)
    ci_est_low <- mean_dat - 1.96*sd_dat/sqrt(n)
    ci_est_high <- mean_dat + 1.96*sd_dat/sqrt(n)
    true_ci_cov[i] <- (ci_true_high >=1)*(ci_true_low <=1)
    est_ci_cov[i] <- (ci_est_high >=1)*(ci_est_low <=1)
}
mean(true_ci_cov)
mean(est_ci_cov)

Here I understood in the code that it is storing the values in an array and returning the mean of that array but I want to understand what is the significance or what does that mean (true_ci_cov) and mean(est_ci_cov) value represent?
Comment: [This](https://stackoverflow.com/questions/53854234/rnorm1-mu-sigma-in-r-to-matlab/53854322) explains what rnorm is doing. Can you decypher that code now line by line?
Comment: I know that bit i can't wrap my head around why we are multiplying both ends of confidence intervals?
Answer: In each loop over $i$ this code draws $n$ independent normally distributed rvs $X_1,...,X_n$ with mean $1$ and standard deviation $2\,.$ Then it calculates
$$
\text{mean_dat} = \frac{1}{n}\sum_{i=1}^nX_i\,,\quad\text{sd_dat}=\frac{1}{\sqrt{n}}\sqrt{\sum_{i=1}^n(X_i-\text{mean_dat})^2}\,.
$$
Due to random noise, mean_dat will fluctuate around its theoretical value $1\,.$ To know by how much, observe first that the variance of each $X_i$ is $4$ so that
$$
\mathbb E[X_i^2]=5\,.
$$
Therefore,
$$
\mathbb E\Big[\text{mean_dat}\Big]=1\,,
$$
and
$$
\mathbb E\Big[\,\text{mean_dat}^2\,\Big]=\frac{1}{n^2}\sum_{i=1}^n\underbrace{\mathbb E[X_i^2]}_{5}+\frac{1}{n^2}\sum_{i\not=j}\underbrace{\mathbb E[X_i]\mathbb E[X_j]}_{1}=\frac{1}{n^2}\sum_{i=1}^n5+\frac{n^2-n}{n^2}=\frac{4}{n}+1\,.
$$
Therefore, in theory, the fluctuations of mean_dat have a standard deviation of
\begin{align}\tag{1}
&\sqrt{\mathbb E\Big[\text{mean_dat}^2\Big]-\mathbb E\Big[\text{mean_dat}\Big]^2}=\frac{2}{\sqrt{n}}\,.
\end{align}
Likewise, sd_dat fluctuates around its theoretical value $2\,.$ Alternatively to the theoretical standard deviation (1) the code also calculates the standard deviation using the estimated sd_dat instead of 2:
$$\tag{2}
\frac{\text{sd_dat}}{\sqrt{n}}\,.
$$
The code now checks if the drawn mean_dat is within a confidence interval around its theoretical value $1$ where the interval is
$$
\left[1-1.96\frac{2}{\sqrt{n}},1+1.96\frac{2}{\sqrt{n}}\right]\text{ resp. }
\left[1-1.96\frac{\text{sd_dat}}{\sqrt{n}},1+1.96\frac{\text{sd_dat}}{\sqrt{n}}\right]\,.
$$
Because mean_dat is normally distributed, the first interval corresponds to 95% probability. In theory, the last two lines mean(true_ci_cov) mean(est_ci_cov)
should produce something close to 0.95.
Comment: thanks. What if we make the value of n as 100 from 10. How will that mean(true_ci_ov) and mean(est_ci_cov) change?
Comment: It should converge to its theoretical value 0.95 with a rate of $1/\sqrt{n}$ describing the error. This little piece of code is nothing else than a simple experiment that verifies if -as we know- a Monte carlo simulation has that rate of convergence. You could also view it as a test how independent and normal your random numbers are.


'pick rest' tecnique for improved alternate picking?

Question: I am a beginner (perhaps intermediate) guitar player and a year ago, when I was at the very beginning, I came across a technique called 'pick rest' as demonstrated in
this video:
The technique sounded to me very reasonable back then and I kept on minding it for some time. Though, over time, I forgot about it and was not applying it at all on my play.
These days while playing the lick below from AC/DC back in black

I noticed that something was missing, then I realised that I was missing the open (up) stroke on the second (B) string so was doing

3-0 (down up - like in the tab)
3 (down - I was missing the open up stroke)
2^(4)`2p0 (normal, like in the tab)

I then noticed that my pick was drifting away too much from the B string when hitting the first down stroke (3rd fret), so that I was missing the next open up stroke on the same string. Finally I realised that the 'pick rest' technique helped a lot in saving movement: by the first downstroke on the B string, I was resting the pick on the high E string, so that the pick was way closer to the B string, such that I was no longer missing the up stroke on this same string.
Even though the 'pick rest' technique sounded very reasonable to me at the beginning, I neglected it mainly for two reasons:

it was not all that natural to me
I had the impression that this was just theory, that no  good/ professional guitar player employed such a technique in his play.

But today I learned the usefulness of it in my own playing.
My question is: for the experienced guitar players out there, is it worthwhile to 'stick' to this technique in order to develop a 'good picking habit' from now forward? Or this technique does not apply for playing solos and stuff like that (as I pointed out above, I don't think I have ever seen a professional player using this technique, though I might be wrong, or the professionals have other techniques of 'economy of movement').
Comment: Sounds very similar to 'apoyando' or rest stroke.
Answer: Answering your question in the last para: among top tier pros, the pick rest technique is not universally used, but there are definitely some who use it a lot.
I'm thinking for example of Joscho Stephan, an absolute virtuoso, who uses it as a matter of course, and even talks about it in places like this video:

And if you want to see it in action, for example, here it's all over the place:
Answer: I teach this very same technique to beginners because I find that sometimes they pull the pick away from the top of the guitar which causes even more problems.  The purpose of such exercises is to help the student develop a felling of connectedness to the guitar (or instrument in general).  There are several valid picking styles and techniques and no one of then is "better" than the others.  But I would say that for all of them it is critical to not pull your hand away form the guitar after plucking.  The method shown in the video helps prevent that.
Also, I'd say that for consecutive picking this is a critical move.  You need to be able to "plant" the pick on the next string when needed.  For that reason I'd say you should continue to develop this.
Moving on to alternate picking you would be wise to practice another type of planting or resting.  I borrow the term "planting" from classical guitar.  The idea is to PLANT the finger on the string it is going to pluck a moment before plucking.  This is advocated for arpeggios by players like Christopher Parkening but it also works for scales and tremolo.  I develop the ides for alternate picking some years ago and teach it to my students, but never published anything on it.  The idea is as follows.  If you are going to alternate pick on a single string then you want to plant your pick on that string NOT on the next string.  That may seem counter intuitive but it's simple.  When you down stroke rather than letting your pick rest on the next string you immediately reverse direction and rest it on the same string you just plucked.  Resting from below the string (don't cross over and start another down stroke).  Now, this may seem like you're just alternate picking but really you're not.  What you are doing is stopping the note you just plucked which (1) trains your hand to reverse direction quickly, (2) trains your hand to stay as close as possible to the string.  Both of these skills are critical for developing speed picking.
As you may have guessed this only helps you get fast on one string.  Well the trick to getting fast on two strings is in the video you posted, resting on the next string.  One movement is NOT more important than the other, they are both important and should both be practiced.  And, there are more movements related to string skipping etc.  If you rely heavily on the technique in the video then you alternate picking on one string will get sloppy but if you exercise both then you will be clean on most any riff.  Again, this guy's "trick" is very useful for helping beginners overcome bad habits but I would say that no matter how advanced you are this is still a basic movement that should be drilled.


RestServer in Codeigniter: 401 Unauthorized response when loading in view

Question: I'm using the restserver in Codeigniter from Chris Kacerguis and I setup rest_auth with session.
When I'm logged in, I access the page whose view.php get the response through file_get_contents and it's returning 401 Unauthorized.
When I access the API's direct page in a new tab, it returns the json correctly.
the view.php is loading the API content in this way:
json_decode(file_get_contents('https://example.com/api/proces/'), true);

the response:

A PHP Error was encountered
Severity: Warning
Message: file_get_contents( I needed to remove the link ): failed to open >stream: HTTP request failed! HTTP/1.1 401 Unauthorized

What's happening?
Comment: Does the api require any kind of authentication?
Answer: I see your example url is using "https" and it is possible that your Apache / Nginx server is not configured correctly to handle the SSL in this way, but it would work fine with the certificate in the browser.
I would suggest you use curl as an alternative instead.
json_decode(curl_get_contents('https://example.com/api/process/'));

from here https://github.com/zg/curl_get_contents
Or of course you could use curl directly.
$url = 'https://example.com/api/process/';
$request = curl_init();
curl_setopt($request, CURLOPT_URL, $url);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($request, CURLOPT_HEADER, false);
$data = curl_exec($request);
curl_close($request);

Comment: I tried you sugestion but it didnt work. I tried others I found on the web but none worked. So I will setup off authentication for a while, and if I eventually find a solution, I will post it here.


Arrays/Lists and computing hashvalues (VB, C#)

Question: I feel bad asking this question but I am currently not able to program and test this as I'm writing this on my cell-phone and not on my dev machine :P (Easy rep points if someone answers! XD )
Anyway, I've had experience with using hashvalues from String objects.  E.g., if I have StringA and StringB both equal to "foo", they'll both compute out the same hashvalue, because they're set to equal values.
Now what if I have a List, with T being a native data type.  If I tried to compute the hashvalue of ListA and ListB, assuming that they'd both be the same size and contain the same information, wouldn't they have equal hashvalues as well?
Assuming as sample dataset of 'byte' with a length of 5
{5,2,0,1,3}
Comment: what do you mean by "compute the hashvalue of ListA and ListB"? Do you mean hash value for the each item in the list be the same - if so then yes. Otherwise I don't think they will be the same..
Comment: E.g., ListA.Hashvalue = ListB.Hashvalue?  Not sure if .Net does this even
Answer: It depends on how you calculate the hash value and how you define equality.  For example, two different instances of an array which happen to contain the same values may not be considered equal depending on your application.  In this case you may include the address or some other unique value per array as part of the hash function.
However, if you want to consider to distinct arrays which contain the same values equal you would calculate the list hash using only the values in the array.  Of course, then you have to consider if ordering matters to you or not in determining equality (and thus influencing your hash function).
Comment: Yes, order would be important.  Didn't think of that, but yes it would be critical
Comment: +1, regarding equality: you can overload the equality operator, no?
Answer: If the order of items is important then you could generate a sequence hashcode like this.
public static int GetOrderedHashCode<T>(this IEnumerable<T> source)
{
    unchecked
    {
        int hash = 269;
        foreach (T item in source)
        {
            hash = (hash * 17) + item.GetHashCode;
        }
        return hash;
    }
}

If the order of items isn't important, then you could do something like this instead:
public static int GetUnorderedHashCode<T>(this IEnumerable<T> source)
{
    unchecked
    {
        int sum = 907;
        int count = 953;
        foreach (T item in source)
        {
            sum = sum + item.GetHashCode();
            count++
        }
        return 991 * sum * count;
    }
}

(Note that both of these methods will have poor performance for larger collections, in which case you might want to implement some sort of cache and only recalculate the hashcode when the collection changes.)
Answer: If your talking about the built-in list types, then no, they will not be equal.  Why?  Because List<T> is a reference type, so equality will do a comparison to see if the references are the same.  If you are creating a custom list type, then you could override the Equals and GetHashCode methods to support this behavior, but it isn't going to happen on the built in types.


VBA copy column from sheet 1 and transpose paste into row in sheet 2

Question: I am trying to write a macro to copy data from column C (to the last full row) and transpose paste that data into row 1 on sheet 2. I cannot get my code to work. I am getting a Run-time error 1004 for the Paste line of code.
Option Explicit
Sub ColumnRow()

    Dim lRow As Long

        lRow = Cells(Rows.Count, 1).End(xlUp).Row
        Worksheets("Sheet1").Range("C1" & lRow).Copy
        Worksheets("Sheet2").Range("A1").PasteSpecial Transpose:=True

End Sub

Comment: Check here https://stackoverflow.com/questions/13174916/transpose-a-range-in-vba
Answer: Couple of things.
(1) Specify the sheet for lRow
(2) Syntax for range Range("C1" & lRow) was off - see below
Sub ColumnRow()

Dim lRow As Long

lRow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row 'add sheet ref
Worksheets("Sheet1").Range("C1:C" & lRow).Copy 'specify full range
Worksheets("Sheet2").Range("A1").PasteSpecial Transpose:=True

End Sub

Comment: Got it thanks, just need to put the 1 in Cells(Rows.Count, 1) as a 3 for column C
Comment: One thing I omitted to mention is that this code will overwite as it always pastes to A1.


Adicionar separador de Mil em um numero animado por jquery

Question: Gostaria de saber se tem alguma forma diferente de acrescentar o separador de numero na formulá do Jquery?
Exemplo: Atual: 2000  Correto 2.000
https://jsfiddle.net/ymxdq980/3/
Answer: Troque sua função numberToReal por esta abaixo.
Veja funcionando aqui inserir a descrição do link aqui
function addDots(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2;
}

Comment: eu cheguei a fazer uma formula semelhante a essa, porem quando você mexe o scroll mais de uma vez  ao invés do numero fixar, ele zera não sei que causa isso
Answer: Consegui resolver o problema com a pontuação, o conflito começou foi por conta do scroll, mas para as pessoas que tiveram o mesmo problema em achar um Cronometro ou "count number animation" que ativa com o movimento do scroll, segue os comandos de java script e jquery.

var jarodou = 0;  //controla se já rodou o counter 0=não 1=sim

$(document).ready(function() {

  function visibleHideme() {
    $('.seucomandodonumero').each(function() {

      var top_of_object = $(this).offset().top;
      var bottom_of_object = $(this).offset().top + $(this).outerHeight();
      var half_of_object = $(this).offset().top + ($(this).outerHeight() / 2);
      var top_of_window = $(window).scrollTop();
      var bottom_of_window = $(window).scrollTop() + $(window).height();

      if (half_of_object < top_of_window) {
        $(this).css({
          'opacity': '0',
          'top': '-50px'
        });
      }
      if (half_of_object > bottom_of_window) {
        $(this).css({
          'opacity': '0',
          'top': '50px'
        });
      } else if (half_of_object > top_of_window && half_of_object < bottom_of_window) {
        $(this).css({
          'opacity': '1',
          'top': '0px'
        });
      }

    });
  }
  visibleHideme();

  $(window).scroll(function() {
    visibleHideme();
  });

});

function ativaContador(e) {
  $('.seucomandodonumero').each(function() {
    $(this).prop('.seucomandodonumero', 0).animate({
      Counter: $(this).text()
    }, {
      duration: 1000,
      easing: 'swing',
      separator: ',ddd',
      step: function(now) {
       if (now > 0)
          $(this).text(addDots(Math.ceil(now)));

      },
      complete: function() {
        $(this).stop(true, true)

      },
    });

  });
}

$(window).scroll(function(e) {

  var alturaBody = $(window).height();
  var distanciaElemento = $('.seucomandodonumero').offset().top;
  var posicaoScroll = $(this).scrollTop();
  var alturaElemento = $('.seucomandodonumero').outerHeight();

  if (posicaoScroll > (distanciaElemento + alturaElemento - alturaBody)) {

      //testa se counter já rodou
      if (jarodou == 0) {
          ativaContador();
      }
      jarodou = 1; //inibe rodar counter de novo

  }
    });

function addDots(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2;
}
body {
  padding: 10px;
  font-family: Helvetica;
  background-color: white;
}

.col_fifth {
  width: 95%;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(158px, 2fr));
  grid-gap: 8px;
  margin: auto;
}

.quadrado {
  text-align: center;
  margin-bottom: 0px;
  color: #2d2d2d;
  width: 198px;
  display: table;
  float: left;
  padding: 10px;
  position: relative;
  transition: opacity 0.6s ease, top 0.6s ease;
  margin: 5px;
  justify-content: center;
}

.counter-cronometro {
  padding: 10px;
  border-radius: 10px;
  display: table;
  justify-content: center;
  width: 190px;
  margin: 0px;
  height: 190px;
  background-color: #f9f9f9;
}

.count-title {
  font-size: 28px;
  margin-top: 5px;
  margin-bottom: 0;
  text-align: center;
  font-weight: bold;
  display: inline;
}

.count-text {
  color: #898989;
  font-size: 18px;
  font-weight: bold;
  margin-top: 5px;
  margin-bottom: 0;
  text-align: center;
}

.count-number {
  font-weight: bold;
  font-size: 20px;
  display: inline;
}

@media only screen and (max-width: 320px) {
  .col_fifth {
    width: 40%;
    display: table;
    float: left;
    margin: auto;
  }
  .counter-cronometro {
    padding: 5px;
    border-radius: 10px;
    justify-content: center;
    width: 140px;
    margin: 0 0px;
    height: 160px;
    background-color: #f9f9f9;
  }
  div.quadrado {
    text-align: center;
    margin-bottom: 0px;
    color: #2d2d2d;
    width: 30%;
    padding: 5px;
    position: relative;
    transition: opacity 0.6s ease, top 0.6s ease;
  }
  div.count-title {
    font-size: 20px;
    margin-top: 5px;
    margin-bottom: 0;
    text-align: center;
    font-weight: bold;
    display: inline;
  }
  div.count-text {
    color: #898989;
    font-size: 13px;
    font-weight: bold;
    margin-top: 5px;
    margin-bottom: 0;
    text-align: center;
  }

+

59

Anos de Liderança

      +
2000000

m² Vendidos

+
4000

Municípios Atendidos

+
500

Colaboradores

+
160

Patentes

 +
300000

 Clientes Satisfeitos

Comment: `` não existe, não é uma tag que se abre e fecha, de uma olhada [nessa pergunta](https://pt.stackoverflow.com/questions/46370)
Comment: era só um teste, mas obrigada por responder


Using wildcards when accessing a multi-dimensional object in Javascript

Question: I'm working with a GeoJSON dataset that is formatted like this:
{
  "type": "Feature",
  "properties": {
    "startcong": "109",
    "district": "7",
    "statename": "Pennsylvania",
    "member": {
      "112": {
        "21168": {
          "party": "Republican",
          "name": "Meehan, Pat",
          "district": "7"
        }
      },
      "109": {
        "15447": {
          "party": "Republican",
          "name": "Weldon, Curt", "district": "7"}
        },
      "110": {
        "20744": {
          "party": "Democrat",
          "name": "Sestak, Joe",
          "district": "7"
        }
      },
      "111": {
        "20744": {
          "party": "Democrat",
          "name": "Sestak, Joe",
          "district": "7"
        }
      }
    },
    "endcong":
    "112",
    "id": "042109112007"
  }
}

I'm struggling with how to access these nested objects. For instance, I can use feature.properties.member[112][21168] to access the party attribute. However:

That second numbered object ("21168") is not always consistently numbered.
That second numbered object is always the only nested object.

Is there a way to access that same party attribute using something like a wildcard? Ideally, something akin to feature.properties.member[112][*].party.
Answer: If the second number is the only nested object, you can find what the number is using the builtin Object.keys(obj), something like:
var obj = feature.properties.member[112],
    key = Object.keys(obj)[0],
    party = obj[key].party

Sadly there is no wildcards for property accessing, but you can find what the property names are fairly simply.


Best block size for fio when reading a file

Question: To pre-warm an ext4 EBS volume I'm using fio as follows:
fio --name <filename> --filename <filename> --rw read --direct 1 --ioengine libaio --bs <X>k

and I'm trying to understand what the optimal block size should be.
I know that I can 'stat' and get the block size of a file but when using that in fio, it will throw an error if the file size is less than its block size.
An option could be to use the block size given by stat by default and if the file size is less than that, get the closest 'standard' number: i.e. if size is less than 4k set block size to 1024.
What's the best way of setting the right block size?
EDIT: I'm restoring a 10TB gp2 volume from a snapshot. There are a few million files - most of them are small files, but another good part is made of 50MB-30GB files and all these files need to be "ready" to be read as fast as possible. I've got a script that runs fio against each file and I'm trying to understand how I can best dynamically adjust the block size for each.
Comment: Why aren't you using the block size they gave in the linked document? Though, I don't really expect it to matter all that much.
Comment: The document suggests to prewarm the whole volume, but that's unnecessary as you only want to prewarm the blocks that are actually in use (so files vs block devices). Using a block size bigger than the file will make fio throw an error.
Comment: It also says you only need to prewarm when you have restored an EBS volume from a snapshot. That said, if you only want to prewarm a single file, then you'd probably have to use the minimum block size as you've already proposed.
Answer: In order to mask network latency, you want to use a reasonably large block size. The Amazon-suggested 1 MB block size seems good to me.
I suspect dd would be as fast, or faster, than fio for this particular workload. However, you simply had to experiment and use whatever method is faster for reading (and re-hydrating) the volume.
Finally, consider that stat returns two I/O size values:

minimum, which is the minimum IO size the device will read/write;
optimal, which is the minimum IO size to get good performance by avoiding r/m/w behavior

This does not means that IO bigger than optimal size will be slower; rather, bigger size can actually slightly increase IO performance.
Comment: The documentation linked to says fio is faster as it's multi-threaded. It also suggests 128k as the block size, though it doesn't say why. I agree moving to 1MB is probably a good plan. I'd probably use fio and 1MB.
Comment: @Tim The documentation uses `fio` with 128K blocksize *and* iodepth at 32, which means a ~4MB data chunk is in flight in each moment. Anyway, due to its sheer simplicity, I sometime see `dd` to be slightly faster than `fio` for raw data read/write. As always - your mileage may vary; the OP should try by himself.
Comment: If the block size is 1MByte or larger there's a [chance that the kernel will split it](https://unix.stackexchange.com/a/533845/109111) creating a bit more device parallelism at the cost of more kernel overhead (you would need to check the size of I/Os actually being submitted down to disk to know for sure). A tiny block size on fio won't help your throughput on big files (as you just force more work to be done per I/O) but if the file is tiny you'll have no choice but as @shodanshok stated its key to set the iodepth too (fio is multithreaded but in this case its just being asynchronous ;-).
Comment: @shodanshok does stat really report the sizes size that avoid all rmw? I thought that the values it gave back were only in reference to the block level but not necessarily at the meta level (think software RAID stripe size) but perhaps that's exactly what you meant ;-)
Comment: @Anon `iostat` optimal block size is the IO size at which the storage layer is expected to work optimally - mainly avoiding r/m/w. Anyway, for the optimal block size to report realistic values, *any* storage layer had to pass-up the underlying information about chunk/stripe size (and Linux software RAID does exactly that, by the way).
Comment: @shodanshok Aren't you referring to [`stat(1)`](https://linux.die.net/man/1/stat) in your main answer? Now I think about it, `stat(1)`'s life is more complicated because it can end up reflecting what the filesystem says it needs which need not be what the device has said. e.g. if I do `modprobe scsi_debug opt_blks=256 physblk_exp=4 && mke2fs /dev/$scsidebugdev && mkdir /tmp/scsi_debug; mount /dev/$scsidebugdev /tmp/scsi_debug && grep . /sys/block//queue/{logical_block_size,physical_block_size,optimal_io_size}; stat -c "%S %s %o" /dev/$scsidebugdev` the numbers don't match.
Comment: ...and then doing `stat -c "%S %s %o" /tmp/scsi_debug/` will give us different results (`? 1024 1024`) again! While the filesystem part is a massive aside I don't believe `stat` is the right command when you trying to find block size/transfer information from a block device (as opposed to when you're atop a filesystem).
Comment: @Anon for a block devices you should use `lsblk -t`. Regarding `stat`, the value returned *should* be the correct one, but no strong guarantee exists.


Verificar aba fechada

Question: Eu achei na internet o seguinte código:

Ele se encaixa bem no sistema que eu quero fazer, o qual verifica se a aba aberta ainda está aberta, porém necessita de um ajuste que eu não sei fazer.
Esse código está em loop, quando ele dá a mensagem que a janela foi fechada, ele abre ela novamente. Teria como ele somente mandar a mensagem? E mandar só uma vez não ficar mandando toda hora? Ou seja, fazer com que o timer rode somente até ele detectar que a janela foi fechada, assim ele emite o alerta e para de executar a função novamente.
Atualização: Consegui montar o seguinte código, o que acham?

Comment: Você quer usar o `setTimeout` mesmo? ele vai executar o código uma vez somente após 2 *segs*, será que não é o `setInterval` que você quer usar?
Comment: o `SetTimeout` no caso é para executar a verificação até o momento em que o usuário fechar o popup, já que eu não consegui trabalhar com o `onbeforeunload`
Comment: Na verdade eu não vi muita diferença rsrs
Answer: Você pode usar a função setInterval para estar verificando se o popup ainda está aberto, quando ele for fechado, você cancela a ação com a função clearInterval.
function aoFecharJanela(){
  alert("A janela foi fechada pelo usuário");
}
function abrirPopup(url, windowName, opts, callback) {
    var popup = window.open(url, windowName, opts);
    var intervalo = setInterval(function() {
        try {
            if (popup == null || popup.closed) {
                window.clearInterval(intervalo);
                callback(popup);
            }
        }
        catch (e) { }
    }, 2000);
    return popup;
}

abrirPopup("http://www.google.com","Jan","height=350,width=200", aoFecharJanela);

Exemplo
Comment: @Guilherme Você está certo, eu não tinha reparado no teu *2º* código, lá você chama *duas* vezes o `setTimeout´ e verifica o status da variável `popup` duas vezes também. Percebeu alguma diferença entre o teu *2º* código e este da resposta?
Comment: para te falar a verdade eu nem testei o seu ja que vi que faz a mesma coisa hehe. Mas vou introduzir ele no código e ver como se comporta. Se for igual marco como a resposta para a pergunta :) Caso contrário eu informo o problema aqui rsrs
Comment: Opa, tinha esquecido de atualziar rsrs desculpe! Testei sim e faz a mesma função que o meu :) Marcado como melhor resposta muito obrigado.
Comment: mas estea função `setInterval` não estaria fazendo praticamente a mesma coisa do que a `setTimer` só que de uma maneira diferente?
Comment: @Guilherme Sim. Mas tem um porém, o [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) vai executar o código a cada *2 segs* num *loop* até que você cancele com o [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval), já o [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout) vai executar o código **uma vez** somente após os *2 segs*.
Comment: @Guilherme Deu certo usando desta forma?
Comment: Na verdade o setTimeout não vai executar somente uma vez, ele vai entrar em loop também! Pois passados dois segundos ele vai chamar a função `Verifica()`, e se caso o popup esteja aberto (`if (popup!=null && !popup.closed)`) ele vai executar a verifica novamente, até que o popup esteja fechado. Por isso não entendi a diferença entre as duas.
Comment: @Guilherme Conseguiu testar o código?
Answer: Seu script está ok!
onbeforeunload vai ser somente disparado no momento em que a janela aberta estiver prestes a carregar a página interna. Se neste momento você clicar no botão de fechar, o alert vai ser acionado normalmente.
Chrome e Firefox tem esse comportamento.
IE, nega ação e nada acontece.
Comment: Não entendi. A moral não seria ele (script) executar o alerta assim que a página fecha?
Comment: Caro Guilherme, o comando onbeforeunload executa uma ação quando um documento está prestes a ser descarregado.
Comment: E tu sabe como fazer para ele executar o comando ao fechar a página?
Comment: Infelizmente não conheço uma função javascript para seu propósito.

Verificar aba fechada


Calculate percentage between two entity fields in Drupal using Computed Field Module

Question: I am trying to calculate a <code>%</code> of two entity fields in Drupal 7 using Computed Field module.
<code>$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_accounts_payable_bs'))) /
$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_customer_deposits_bs')));
</code>
Display:
<code>$display_output = number_format($entity_field_item['value'] , 1 , '.' , ',');
</code>
Current the value I get is ".20" But I want it "20.0"
Comment: Simply like this: $display_output = 100 * number_format($entity_field_item['value'], 1, '.', ',');
Comment: Your number_format parameters would produce 20.0 but that's hundred times of what you're now getting. So are you referring to the math or the format or both? Obvious answer would be multiplying by 100.
Comment: Hi Kari, well both, I know that I need to calculate it by multiplying by "100", just don't know how to do it with PHP and the Computed Field module.
Comment: Hold on, the calculation code has a division slash at the end of the first row, and he is displaying a value that is not in the calculation. Maybe there is more to it than arithmetic operators. John, print() function is very helpful when trying to get Computed Field working.
Comment: Oops, don't try to multiply the result of number_format, that won't work, sorry. See my answer instead.
Answer: First print_r($data) in your Output code text area so you can see what you can work with. Depending on what you have, your Output code is going to look something like this:
<code>$percent = 100 * $data->field_accounts_payable_bs['0']['raw']['value'] / $data->field_customer_deposits_bs['0']['raw']['value'];

print(number_format($percent, 1, '.', ','));
</code>
Comment: Kari,

I tried this code but no results field is NULL.

I tried the output of **$display_output = (number_format($percent, 1, '.', ','));** and it displayed **0.0**

But the calculation should result in 8.3 using my previous method, it would display .083.

Doe sit make a difference that I am using the entity module?
Comment: Try printing those fields individually.
Comment: Sorry Kari, I don't understand. I am just a novice.
Answer: OK, I figured it out! In order to calculate a percentage from two Entity fields with the Computed Fields Module you have to do the following;
<code>$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_accounts_payable_bs'))) /
array_pop(array_pop(field_get_items($entity_type, $entity, 'field_customer_deposits_bs'))) * 100;
</code>
For the display use:
<code>$display_output = number_format($entity_field_item['value'] , 1 , '.' , ',');
</code>
Thank you all for your help!


How to create & run .net Core Console App in docker

Question: I have a .NET Core 2.1 console app. I want to run this console app in a Docker image. I'm new to Docker and just trying to figure it out.
At this time, I have a Dockerfile, which was inspired from Microsoft's Example. My file actually looks like this:
FROM microsoft/dotnet:2.1-runtime-nanoserver-1709 AS base
WORKDIR /app

FROM microsoft/dotnet:2.1-sdk-nanoserver-1709 AS build
WORKDIR /src
COPY MyConsoleApp/MyConsoleApp.csproj MyConsoleApp/
RUN dotnet restore MyConsoleApp/MyConsoleApp.csproj
COPY . .
WORKDIR /src/MyConsoleApp
RUN dotnet build MyConsoleApp.csproj -c Release -o /app

FROM build AS publish
RUN dotnet publish MyConsoleApp.csproj -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "MyConsoleApp.exe"]

My question is, what is the difference between: microsoft/dotnet:2.1-runtime-nanoserver-1709, microsoft/dotnet:2.1-sdk, and microsoft/dotnet:2.1-runtime? Which one should I use for my .NET 2.1 console app? I'm confused as to if I a) build my console app then deploy it to a docker image or b) build a docker image, get the code, and build the console app on the image itself. Any help is appreciated.
Answer: For anyone interested in actual Dockerfile reference:
FROM microsoft/dotnet:2.2-sdk AS build
WORKDIR /app

COPY <your app>.csproj .
RUN dotnet restore <your app>.csproj

COPY . .
RUN dotnet publish -c Release -o out

FROM microsoft/dotnet:2.2-aspnetcore-runtime AS runtime
WORKDIR /app
COPY --from=build /app/out ./

ENTRYPOINT ["dotnet", "<your app>.dll"]

Comment: yes, same as when you just run the dll from debugger or command line
Comment: note to use the correct .NET core version in the base images (2.1, 2.2 etc)
Comment: so does ENTRYPOINT .. "find" the  static main method (inside Program.cs)..........inside ".dll" ?  Is that the magic?
Comment: First, it did not work. I had just replaced /app with  /source on the second line. Then it worked
Answer: It's a question more not about docker itself, but .net docker images
You can go to the https://hub.docker.com/r/microsoft/dotnet/ click in particular image find Dockerfile and understand what exactly software builds in this image and find the difference between different Dockerfile's
Regarding second question better to "build a docker image, get the code, and build the console app on the image itself." So you build the image, expose port, mount your code as volume, and your code executes inside the container with help of software installed in the container
Answer: For .NET 7 the following code works
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
WORKDIR /source

COPY . .
RUN dotnet restore <your app name>.csproj --disable-parallel
RUN dotnet publish <your app name>.csproj -c Release -o /app --no-restore

FROM mcr.microsoft.com/dotnet/aspnet:7.0
WORKDIR /app
COPY --from=build /app ./

ENTRYPOINT ["dotnet", "<your app name>.dll"]

Answer: microsoft/dotnet:2.1-runtime-nanoserver-1709 - This image is used to setup .net runtime, under which any .net app runs.
microsoft/dotnet:2.1-sdk-nanoserver-1709 - This image is of SDK used to compile your .net core app
Refer this blog for how to create & run .net core console app in docker:
Answer: I put an example on Github on how to do this for a .net core webapi application, so should be pretty much the same for a console application.
My docker file looks like:
https://github.com/MikeyFriedChicken/MikeyFriedChicken.DockerWebAPI.Example
This is doing pretty much the same as yours.
Just to clarify previous answers what your dockerfile is doing is creating 'temporary' images which have the ability to build your software.  Once it is all built these images just get scrapped.
If you look at your last lines in your dockerfile you can see it copies the output from the build images to your final image which is based on 'microsoft/dotnet:2.1-runtime-nanoserver-1709' which has just enough libraries and dependencies for running your .net core application.
Answer: My answer for the first question is:
microsoft/dotnet:2.1-runtime-nanoserver-1709 is a docker image you can run .net core apps,
And microsoft/dotnet:2.1-sdk-nanoserver-1709 is a docker image you build apps , you can also run app with it.
And my answer for the second question is:
If you just want to run app in docker, build your app with visual studio on you local machine (this will be the most easy way to build it), use the microsoft/dotnet:2.1-runtime-nanoserver-1709 , build a docker image.


How to print a message of number of rows from a table variable name

Question: I have to print out the number of rows when given only a variable named after the table and not the actual table name itself. Below is my attempt to make this work. It should print out to the message box of SQL Server "X" number of rows.
DECLARE @tableName AS VARCHAR(100)
SET @tableName = 'Tb_Offers' --Name of table i need to find the number of rows therin

DECLARE @rowCount AS INT --variable to store count of rows
SELECT @rowCount = COUNT(*) FROM @tableName

PRINT @rowCount --statement to print count to MS SQL message box.

Comment: You can't use a variable for a tablename without using dynamic SQL.
Answer: Never SELECT COUNT(*) FROM <anything>; to get a count. Try:
DECLARE @tableName sysname = N'Tb_Offers';

SELECT @rowCount = SUM(rows)
  FROM sys.partitions
  WHERE [object_id] = OBJECT_ID(N'dbo.'
    + QUOTENAME(@tableName))
  AND index_id IN (0,1);

Additionally:

Object names are sysname or nvarchar(128), not varchar(100), and strings that contain entity names need to be prefixed with N. Use the system metadata correctly to avoid getting burned.
Stop counting rows the hard way; there is zero reason to read an entire table to get the number of rows.
Comment: @George Yes, it is accurate. Notice that I use a `SUM` to aggregate across all partitions and I only look at either the heap or the clustered index. As for what "approximate" really means, please [read the link](https://sqlperformance.com/2014/10/t-sql-queries/bad-habits-count-the-hard-way). If neither of those is what you mean, please clarify what you mean by "accurate"...
Comment: Is this accurate? I notice in the documentation that [rows] "Indicates the approximate number of rows in this partition."
Comment: Good stuff. Gonna wrap this in a procedure for ease of use.


How to make angular material expansion panel to expand only one at a time

Question: I created a mat expansion panel. I want to make only one expandable at a time. Means when one particular record is expanded, and when i click on another record of mat expansion, then other record of mat expansion should close. Is there any way to do it?
Answer: You just need to wrap your expansion panels in a mat-accordion (see docs)
Make sure to set multi to false to disallow multiple expansion panels to be opened at the same time.
<mat-accordion [multi]="false">
  <mat-expansion-panel></mat-expansion-panel>
  <mat-expansion-panel></mat-expansion-panel>
</mat-accordion>

Here is a live example
Comment: No no no. I am displaying data using *ngFor. Inside mat-expansion i am displaying table. table data is getting after click of particular record of  mat-expansion. After click id of that row is going and api is hitting.


html, body click event except an element which has a focus function

Question: I need to show the options on focussing the input which I am able to achieve using the below jquery
HTML

<input type="text" id="subject" name="subject" placeholder="Please select the subject">

Your subject is required.

Loremp ipsum

Dolor blah

Sit amet

Consectetur blah

Adipiscing elit

jQuery
$(document).ready(function() {
  $('.select-subject').each(function() {
    $(this).find('input').focus(function() {
      $(this).parents('.select-subject').find('.options').fadeIn();
      $('html').click(function() {
        if ($('.options').is(':visible') {
            //hide .options div
            }
            });
      });
    });
  });

CSS
.options {
 display: none;
}

When .options is visible and the user clicks on anywhere in  or  I need to hide the div. I tried multiple options but it's not going through. Thanks for the help.
Answer: You mean as below, i.e. when you focus input it hide options and on blur again visible,

The blur event is sent to an element when it loses focus.
The focus event is sent to an element when it gains focus.

$(document).ready(function() {
    $('.select-subject').each(function() {
        $(this).find('input').focus(function() {
            $(this).parents('.select-subject').find('.options').fadeIn();
        });
    });
    $('.options li').each(function() {
        $(this).click(function() {
            var selectValue = $(this).find('a').html();
            console.log(selectValue);
            $(this).parents('.select-subject').find('input').val(selectValue).focus();
            $(this).parents('.select-subject').find('.options').fadeOut('fast');
        });
    });
    $("#subject").on("focus",function(){
     $(".options").hide();
    });
    $("#subject").on("blur",function(){
     $(".options").show();
    });
});

<input type="text" id="subject" name="subject" placeholder="Please select the subject">

Your subject is required.

Loremp ipsum

Dolor blah

Sit amet

Consectetur blah

Adipiscing elit

Comment: @swamysa Okay, but as said before that this could be achieved by stopping the bubbling of event to parent, as in this jsFiddle I have chained clicked and focus() event listener as both are performed on input, https://jsfiddle.net/d3o31hha/
Comment: Check this jsFiddle, you can make use of e.preventDefault. which stop the default action from occurring https://jsfiddle.net/4Lsh5us2/1/, as you have added fadeOut on click so it hides that div.
Comment:  will be hidden when page loads. On focus of input, .options will be visible. While .options is visible and clicking on 'body' it should be hidden but this event should not get fired when clicking the input parent div.
Comment: Also cannot have #subject since I have 2 forms in the same page - Thanks
Comment: Welcome @swamysa :-)


Commerce 2 how to set to live paypal signature API Credentials

Question: I have set up a sandbox account and I can take TEST payments without issue but there is nowhere for the live account details.
If I set the app you can create to live it gives different account API settings but no signature.
It seems Paypal has changed the layout and the PayPal module in D8 commerce 2 and has no help docs as of yet for this just help documents for the old D7 version.
Answer: Ok I sussed this out quicker than I expected. So for anyone else having this issue do this..

Login to the merchant account NOT the developer account.
Menu on Top right Click Profile > Profile and settings
My selling preferences > API access > update
Under Pre-built payment solution > Manage API permission
Under Option 2  > View API Signature
Under View or Remove API Signature expose the fields to show the Credential API Signature, API Username, API Password.

Add these to your PayPal settings in the commerce payment making sure you set this to live.


Calling an AngularJs function when window goes to close

Question: I need call an AngularJS function when a window goes to close. I have this code now:
app.controller("reportCtrl", function($scope, $http) {

$scope.deleteReport = function() {
    $http.get("/SCTrakker/api/deleteReport").success(function() {
    });
};

window.onbeforeunload = function(){
  $scope.deleteReport();
}; });

This controller and angular libraries are loaded successfully, that's not the problem. The problem is where i go to close the window not execute the event and does nothing. I don't have any idea what i can to do more.
Thanks to all!
Answer: You can bind on window close event with JQuery and call your function.
$(window).bind("beforeunload", function() {
    $scope.deleteReport();
})

Or you can try to use $locationChangeStart event.
$scope.$on("$locationChangeStart", function(){
    $scope.deleteReport();
});

Comment: Nah, doesn't works... the same problem, the event does nothing. Thanks for reply ^^
Answer: The problem has been resolved!
As my problem was that I could not use AngularJS to call the server, what I did was make that call with AJAX and now works perfectly!
Comment: could you elaborate why this can't be achieved using angular? Just curious.


Design pattern when search service fail

Question: I have a UserRepository to search database (solr, elasticsearch, others...) and i have this user data in my SQL database (MySQL, PostgreSQL, others...), My question is what place do I put this? In repository ?  Or other abstraction (Service, Controller)?
My example is in Java, but i will apply this to java (Spring) and PHP:
public interface UserRepository extends SolrCrudRepository<User, String> {}

Comment: *what* is your question? please edit your answer so everyone gets your point
Comment: @Lino what place do I put this? In repository? Create a service just for this ?
Answer: If I understood you you're doing things right
The Repository Pattern lets you abstract where the data comes from. So you use cases/controllers/whatever doesn't need to care about that
BUT the repository doesn't need to know the details about how to retrieve that data. That is a task for a DAO (Data Access Object). A DAO encapsulates the details about how the data is stored
So you repository can have several DAOs that access several data sources and coordinates them. e.g.

Use myDAO1 to retrieve user data
if there is no user data in the data source myDAO1 is fetching then use myDAO2 to fetch another data source
Keep going until the repository find the needed data (maybe implementing a Chain of responsability) or return null or throw an exception or do whatever you define to do
Comment: understand... I can create a UserRepository and he call DAO's (UserSQL and UserSolr for example) and my services, controllers call just repository, this a workflow ?
Comment: Can I do this with hystrix ? (if you know hystrix from Netflix)
Comment: 1. Check any blog post about Clean Architecture. It should clarify your mind about the workflow. 2. I haven't used Hystrix but I'd say that you can do it in any situation
Comment: Thanks :D , I will follow your words

Design pattern when search service fail


D6 Is it possible to set node reference field and use this value in another field on the same node/add form?

Question: I have two node reference fields in a Content Type.
Driver
Manager
Each driver belongs to a certain organisational unit. Every organisational unit has a set of managers. I need the organisational unit to retrieve the right selection of managers in the node reference field Manager.
Now I need to select the driver, save the node and edit the node again. Then I can select the manager from the right set of managers (based on the organisational unit token I supply in the node reference field).
Is there any other way I can do this without implementing a 2-step form?
Answer: These two modules are intended for that purpose and have D6 versions.  I think Dependent Fields sounds closer to what you want, but Hierarchical Select Node Reference may work almost as well.
Dependent Fields

The Dependent Fields module (formerly AHAH Dependent Fields) allows cck based fields to specify another field as a controller field, and react to its changes on the form using AHAH/AJAX without the form re-loading.

Hierarchical Select Node Reference

This module allows the use of Hierarchical Select form element as a widget for CCK node reference field, both in node add/edit form and in views filter.
Comment: Thanks for the update. I had a look at the Conditional Fields (http://drupal.org/project/conditional_fields) module before and I thought this wasn't what I was looking for. I missed out on the Dependent Fields module. Thanks!


$\{a_n\}_{n\geq 1}$ be a sequence of strictly decreasing positive numbers then....

Question: Let $\{a_n\}_{n\geq 1}$ be a sequence of strictly decreasing positive numbers i.e., $$a_1>a_2>a_3>\cdots$$
Then which of the following is always true?

$\lim _{n\rightarrow \infty} a_n=0$
$\lim _{n\rightarrow \infty} \frac{a_n}{n}=0$
$\sum_{n=1}^{\infty}\frac{a_n}{n}$ converges.
$\sum_{n=1}^{\infty}\frac{a_n}{n^2}$ converges.

I guess all options are correct but i could not give a concrete proof.
For third bullet, Take $b_n=\frac{a_n}{n}$ and look for ratio test :
$\lim_{n\rightarrow \infty}\frac{b_{n+1}}{b_n}=\lim_{n\rightarrow \infty}\frac{a_{n+1}}{n+1}.\frac{n}{a_n}\rightarrow 0$ Thus  $\sum_{n=1}^{\infty}\frac{a_n}{n}$ converges.
For fourth bullet, I would just use :
As $a_n$ are positive and  $\sum_{n=1}^{\infty}\frac{a_n}{n}$ converges with $\frac{a_n}{n^2}<\frac{a_n}{n}$.
we would say $\sum_{n=1}^{\infty}\frac{a_n}{n^2}$ converges.
I can not convince myself that this is a proof.
So, please help me to make this a bit more clear.
Thank you :)
Comment: Hint: How does $a_n=42+\frac{1}{n}$ behave?
Comment: Ah... May be that is the reason i could not come up with result $\lim a_n=0$ :D Thank you so much....
Answer: The sequence $a_n=1+\frac{1}{n}$ shows that the first and the third point are not true.
the inequalities
$$0\leq \frac{ a_n}{ n}\leq  \frac {a_1}{ n}$$
prove that the second point is true and the inequalities
$$0\leq \frac{ a_n}{ n^2}\leq  \frac {a_1}{ n^2}$$
prove that the last point is also true.
Comment: You're welcome.
Answer: The correct options are the second and the fourth (Peter's comment contains a counterexample to both the first and third options).  You can deduce the second option from the fourth.
Comment: @SamiBenRomdhane corrected, thanks.
Answer: For the third bullet point you can also consider this
$a_n=\frac{n}{2n-1}$
Comment: interesting in the sense that it disproves 1and 3 simultaneosuly
Comment: why would you think this is worth considering? Is there something more interesting than other examples? I would like to know more about this...
Comment: this will disprove bullet point 3
Comment: Yes Yes i understand that this would disprove third bullet point but i was expecting you want to say that this is more simple/interesting than other examples... Thank you any ways :)
Comment: valid point :) Thank you :)


How is "so" correctly translated into predicate logic?

Question: I have come across an exercise that asks to have "There is only one ball, so you need to have it" translated into predicate logic. Using the predicates $\text{Ball}(x)$ for $x$ is a ball and $\text{Have}(x, y)$ for $x$ must have $y$, I translated it this way:
$$\exists x((\text{Ball}(x) \land \forall y(\text{Ball}(y) \rightarrow (x = y))) \rightarrow \text{Have}(\text{you}, x))$$
The answer in the back, on the other hand, is:
$$\exists x(\text{Ball}(x) \land \forall y(\text{Ball}(y) \rightarrow (x = y)) \land \text{Have}(\text{you}, x))$$
I want to know whether I am wrong or not, and why. The exercise and answer can be found here
https://textbooks.open.tudelft.nl/textbooks/catalog/view/53/144/370-1, on page $51$ (exercise $8$) and page $189$ respectively.
Thank you.
Comment: This question is not really a mathematics question, because it requires some linguistic knowledge to parse the meaning of the given sentence before even trying to translate it into predicate logic.
Comment: My first thought was: Probably you need some form of causality logic to formalize the natural language semantics of "so"...
Comment: Some clarification is needed. Are we talking about some kind of game that requires the use of a single ball? Is it the case that if we have a ball, then we can then play this game?
Answer: I like neither translation.
Yours is certainly not right, since your statement would be rather vacuously true if there exists something that is not a ball: that something would make $Ball(x)$ False, hence the whole antecedent of the conditional false, and therefore the whole conditional true.
But the one offered by the book merely says: "There exists one ball and you need to have it" ... which really doesn't capture the 'so' part.  Indeed, the statement given is really an expression of an argument: [This], therefore [that]. And there is really no truth-functional connective or other nice way to logically represent a 'therefore' or 'so'.
Of course, what you can do is to represent this argument using two statements in predicate logic, and use the mathematical 'therefore' in between:
$\exists x (Ball(x) \land \forall y (Ball(y) \to x = y))$
$\therefore$ $\exists x (Ball(x) \land Have(you,x))$
Answer: "$\phi \to \psi$" means "not $\phi$ or $\psi$. So your formula permits for the possibility where there is not exactly one (i.e. no or more than one) ball. But we need to have that there is one ball, and that you have it. Though there is more to the semantics of "so" than just that both sides are the case; it additionally carries the meaning of a causal connection, and this additional meaning can not be expressed solely by truth-functional operators.
Answer: $$A(z), \text{ so }B(z)$$ has the same meaning as A(z), therefore B(z): it first asserts that A(z) is true, then implicitly asserts that B(z) is a consequence of A(z), and finally concludes that B(z) is true. Its complete predicate-logic formalisation is $$A(z)\;\land\; \Big(A(z)\to B(z)\Big)\;\land\; B(z),$$ where the final conjunct is a logical redundancy.

"There is only one ball, so you need to have it"

This statement's final word refers to a specific ball, which was introduced in the first part of the statement. So: $$\exists x\big(\operatorname{Ball}(x) \land \forall y(\operatorname{Ball}(y) \rightarrow x = y)\big) \;\land\; \operatorname{Ball}(z) \\
\land\quad \Big(\exists x\big(\operatorname{Ball}(x) \land \forall y(\operatorname{Ball}(y) \rightarrow x = y)\big) \;\land\; \operatorname{Ball}(z)\Big)\to \operatorname{Have}(\operatorname{you}, z)\\
\land\quad \operatorname{Have}(\operatorname{you}, z).$$

I translated it this way:
$$\exists x((Ball(x) \land \forall y(Ball(y) \rightarrow (x = y))) \rightarrow Have(you, x))$$
The answer in the back, on the other hand, is:
$$\exists x(Ball(x) \land \forall y(Ball(y) \rightarrow (x = y)) \land Have(you, x))$$

The main issue with your formalisation is that it fails to assert that there actually is only one ball, while the book's formalisation is merely asserting "you have the only ball" and failing to capture the given statement's implicit conditional.


2014 New Table Tennis ball material rules for ITTF

Question: I was reading on reddit that there's a new ball being used for table tennis. Is this true?
Are there new rules in place regarding a new ball? If so what caused the change to of rules?
Comment: The balls re not good for playing because they changes direction after bounce this make d ball not to give perfect accurate touch on the raket
Answer: Up until recently, all table tennis balls were made of celluloid.  ITTF has mandated a change to a new ball, known as the plastic ball or poly ball.  The deadline for the use of the plastic ball was July 1, 2014, and the Belarus Open was the first event to use the plastic ball.  From this point on, all World Title and ITTF sanctioned events will use the plastic ball.
The reason behind the switch to the plastic ball is two-fold.  Initially, the reason given was that celluloid is increasingly becoming difficult and expensive to obtain, due to dangers in production and increasing regulatory restrictions.  However, ITTF president Adham Sharara revealed in an interview in February 2014 that another purpose was to slow down the game:

From the technology point of view, we're going to reduce speed. In fact, we're developing a technology  test, which'll have a bounce limit. If you see Chinese players performing the stroke, it's difficult to see the ball. This has to slow down. We're also changing balls. FIFA made the balls lighter and faster, but we're changing balls from celluloid to plastic for less spin and bounce. We want to slow down the game a little bit. It'll come into effect from July 1, which, I think, is going to be a very big change in the sport.

In addition to the material change, the diameter of the ball is changing slightly.  Celluloid balls were required to be between 39.50 and 40.50mm, and the new plastic balls need to be between 40.00 and 40.60 mm.
The new balls are controversial.  Many of the old plastic balls (before 2014) were not reviewed well.  They did not meet ITTF requirements and were more prone to breaking than celluloid balls.  ITTF claims that all of the plastic balls that were approved this year (the first plastic balls were approved on January 24, 2014) are better than the older plastic balls.  As more tournaments using the plastic balls occur, time will tell what changes the new balls introduce to the sport.
ITTF is still approving celluloid balls, and they may still be used for non-ITTF sanctioned events.  If you have an ITTF-approved ball in your hand and are unclear if you have a celluloid or plastic ball, the plastic balls have "40+" printed on them.  Celluloid balls have "40" printed without the "+" character.
ITTF has published a Q&A fact sheet on the new plastic balls (pdf).
Answer: After reading the Q&A Sheet. I did some more research and watched a couple youtube reviews. The youtube video does confirm the intent of ITTF: slowing down the game.
Mainly this one: https://www.youtube.com/watch?v=g0-ogajfDqI
Here are some key aspects they highlighted:

Ball is heavier
Sound of ball is different. Sounds almost like a broken ball
Takes more effort on loops from a distance