What stretches can be done to prevent wrist cramping?

Question: When playing Bass, sometimes my left wrist starts to feel a little crampy- especially when practicing modal scales and chord arpeggios at slightly faster tempos. My right wrist also sometimes starts feeling crampy after a while when practicing 16th notes at slightly faster tempos.
I try to keep good posture with my back and shoulders, hold the bass at a comfortable angle, and use my left arm to do as much of the work as possible when pressing down strings to the fretboard, but after prolonged practice, the cramping feelings start to come.
I've been told by my teacher that it's important to stop or slow down practice if I start feeling signs of pain because "ignoring" the pain and practicing on at that point can lead to injury in the long term, so I also make sure to stop at those points. I do also trust that in the long term, my muscles will grow stronger and I'll be able to play for longer. But I also think stretches could help a little in the short term.
My teacher mentioned that he does wrist stretches to help prevent cramping (I guess it's similar to how athletes to stretches before physical activity).
What kinds of stretches are helpful to prevent wrist cramping when playing Bass?
Please try to describe the stretches as best you can in words. If you can supplement the descriptions with diagrams or videos, that would also be quite helpful.
I did see this existing question, but the question is about causes of cramping and not about wrist stretches.
Since my teacher told me about some of the stretches he does, I'll share those in a self-answer, but I'm really curious to know if there are other stretches my teacher doesn't know about or didn't tell me about (it was quite a while ago and I'm no longer in close contact with them).
Comment: Even though you notice the discomfort in wrist/forearm, I'd encourage you to think about relaxing and stretching in the bigger picture too—whole arm, shoulder muscles, etc. And that *relaxing* the muscles is just as important as stretching them. I find simply "shaking it out" frequently is good, or making big windmill motions.
Comment: Relax your hands. Something as a severe as a cramp indicates tension in your hands. Music is meant to be enjoyed. Even if you make a mistake the music police will not arrest you.
Answer: As promised, here are the wrist stretches my teacher told me about:

Hold forward the arm you want to stretch. Hold it out straight, completly outstretched, and perpendicular to your body and parallel to the ground.

Point the palm outward with fingers pointing up. Use the other hand to gently bend the fingers and hand toward the body. Do it enough that you feel a little bit of stretching. Don't overdo it! You could injure yourself by stretching too hard.

Do the same thing except with the fingers pointing downward.

Hold both arms outward to the sides (like a T-pose). Hold them out straight, completly outstretched, and perpendicular to your body and parallel to the ground.

Point the palms outward and fingers upward such that you feel a bit of stretching in the wrists. Don't overdo it.

Do the same thing except with fingers pointing downward.

Now to help relax the wrists after stretching, repeat the previous steps except with the palms pointing inward (this should be more comfortable)
Comment: These are good; I use #1 regularly. And "don't overdo it" is important; it's possible to injure yourself just by stretching zealously!
Answer: Pain is God's way of telling the recipient 'you've done enough of that for now - give it a  rest!' Take notice, and stop at that point. Or move on to different activities, more gentle, while giving the 'injured' body parts time to recover.
I can't understand why modal scales should be any more stretchy than any other scales, and arpeggios can be re-figured so that the stretches are minimised. Think more about fingering. Are you using certain finger patterns which mean you have to stretch further than needed?
For starters, keep your practice times down to shorter than you already use - work out when the pain starts, and crop a couple of minutes off that time next practice session. You say you're holding the bass correctly, but try finding other positions which may be more correct for you. Like having the whole bass so that the head is far higher than the body - more like a double bass player's way of playing, or somewhere in between.
There must be plenty of 'stretching' exercises that you can come up with yourself, but I recommend working more on not needing them, instead changing your playing. Are you sitting or standing? That will make a big difference in itself. How high/low do you sling your bass? Is it a 4 or 5 string? Does it happen with just the one or any bass you happen to play?
I could proffer ideas for exercises, but first I'd be looking at other factors which may be causing that discomfort. Even changing to a short scale bass guitar, where the stretches obviously won't be as wide anyway.
O.k., so you wanted some exercises. Start well up the neck, one finger per fret. Play chromatically, as fast as you need, up and down, and gradually move down to the 1st-4th frets. Please don't try to keep all fingers touching the strings as you move - the index finger will have no purpose being left on while the other fingers are pressed down!


Convertendo Bases em Python

Question: O código abaixo, recebe um número decimal e converte para bases de 2 a 9
def converte(numDecimal, base):
    if numDecimal != 0:
        numConvertido = ""
        while numDecimal > 0:
            resto = numDecimal % base
            numConvertido = str(resto) + numConvertido
            numDecimal = numDecimal // base
    else:
        numConvertido = "0"
    return numConvertido

n = int(input())
while n != -1:
    for b in range(2, 9 + 1):
        r = converte(n, b)
        print(r, end=" ")
    print()
n = int(input())

Caso agora eu queira fazer ao contrário, e receber um número binário e converter para bases de 3 a 10, por exemplo, como eu faria?
Comment: O mais simples é interpretar o binario como decimal e de seguida usar a função que já tem de convesão para outras bases
Answer: Opa, saudações! Cara existe um jeito mais fácil de converter números em bases diferentes para inteiros na base decimal, vou dar um exemplo abaixo:
Abaixo é um conversão de um número(String) binário para a base decimal:
b = '0111'
print(int(b, 2))
>> 7

O int() nesse caso recebe dois parâmetros, o primeiro sendo o número a ser convertido que deve ser passado como string, e o segundo a base em que ele se encontra, então podemos fazer outro exemplo em que um número está na base 5 e queremos convertê-lo para decimal:
b = '0410'
print(int(b, 5))
>> 105

Sabendo disso, acho que facilita bastante a construção do seu código!
Agora sendo direto a sua pergunta, ao receber um número binário e querer passá-lo para outras bases, o melhor seria convertê-lo para decimal e então para a base em questão utilizando a função que já tens.

Convertendo Bases em Python


Create CSS buttons with equal padding

Question: I am use the following css to create buttons
.cssButton {
background-color:#333333;
border:1px solid #CCCCCC;
display:inline-block;
color:#FFFFFF;
cursor:pointer;
text-decoration:none;
font-family: arial, helvetica, sans-serif;
}

When applied to anchor links and inputs, I get different heights. Is there a way to force the properties to match in both elements?
Thanks
Comment: keep height and width in your css, I attached answer also
Answer: Yes, by setting a default font-size and padding.
.cssButton {
    background-color:#333333;
    border:1px solid #CCCCCC;
    display:inline-block;
    color:#FFFFFF;
    cursor:pointer;
    text-decoration:none;
    font: 12px arial, helvetica, sans-serif;
    padding: 2px;
}

Also check this Fiddle
Answer: Like this
add padding:5px; in below class :
DEMO
CSS
*{
    margin:0;
    padding:0;
}

.cssButton {
background-color:#333333;
border:1px solid #CCCCCC;
display:inline-block;
color:#FFFFFF;
cursor:pointer;
text-decoration:none;
font-family: arial, helvetica, sans-serif;
 padding:5px;
}

Answer: With CSS Padding property
{
padding:5px
}
Answer: .cssButton {
    background-color:#333333;
    border:1px solid #CCCCCC;
    display:inline-block;
    color:#FFFFFF;
    cursor:pointer;
    text-decoration:none;
    font: 12px arial, helvetica, sans-serif;
    width:100px;
    height:30px;
}

you didn't keep height, width in your css. gud luck
Comment: if necessary then you can also attach 'float:left; '
Comment: This, along with `line-height:30px;` is the best solution. You also wouldn't need `float:left;` since it's inline-block.

Create CSS buttons with equal padding


What is performance bottleneck of my Apache server?

Question: I have too many requests waiting which can be seen from netstat as follows
<code>$netstat -anp | grep :80 | grep TIME_WAIT | wc -l
840
$netstat -anp |grep :80 | grep ESTABLISHED | wc -l
50
</code>
memory usage : 850MB / 1000MB
apache2.conf contains..
<code><IfModule mpm_prefork_module>
    StartServers          5
    MinSpareServers       5
    MaxSpareServers      10
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

<IfModule mpm_worker_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

<IfModule mpm_event_module>
    StartServers          2
    MaxClients          150
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxRequestsPerChild   0
</IfModule>
</code>
Are there any configuration changes that can help me or its just my RAM the bottleneck here ?
Urgent help needed..!!
Comment: what is the current mpm configuration, prefork? worker?. And gives us any configuration concerning Keepalive and tiemout, check as well http://serverfault.com/questions/86550/apache-keep-alive-or-not-keep-alive for nice explanations on TIME_WAIT problem (which is not completly related to keep alive, but keepalive timeout is maybe your problem).
Answer: You should start by checking out the mod_status module. It will show you much more information about what your Apache web server is doing.
There is documentation available at http://httpd.apache.org/docs/2.2/mod/mod_status.html including an example of how to use it.


what is the probability that every man marry this year??

Question: In the Goland Kingdom, there are always more unmarried women, 18 years old or more,
than unmarried men, 18 years old or more. Because of this, the king gave the following law.
On the 1st of April of every year, each unmarried women 18 years old or more has to tell
the king on a written note her name and the name of one unmarried man older 18 years or
more that she proposes to marry. The king collects all the notes and give to each man the
note addressed to him. Each man can get no proposal, one proposal, or several proposals. If
a man gets no proposal, he will remain unmarried until the next year. If a man gets exactly
one propoasal, he has to accept it and marry. If a man gets more than one proposal, he
must choose his bride from the list of all unmarried women that proposed him and marry. If
this year there are m unmarried women and n unmarried men, what is the probability that
every man marry this year?
Comment: Are you assuming that every woman picks randomly among all men a uniform distribution? That seems not very realistic.
Comment: By using the Principle of Inclusion-Exclusion.)
Comment: Unless you know how many marriable women are there, there is no way to compute anything.
Answer: The women's option will determine a function from $W$ to $M$ where $W$ is the set of available women and $M$ the set of available men (available sounds better than unmarried).
All men will marry if the function is surjective. so the probability is just the number of surjective functions from $W$ to $M$ divided by the number of functions from $W$ to $M$.
The hard part is finding how many surjective functions there are from $W$ to $M$. In other words how many surjective functions exist from a set of caridinality $n$ to a set of cardinality $m$.
So first you need to find out in how many ways you can  partitions a set of size $n$ into $m$ parts. This is done via stirling numbers of the second class.
Then select which element of range is mapped by each of the parts in $m!$ ways.
Therefore the probability is $$\frac{|M|!S(|W|,|M|)}{|W|^{|M|}}\cdot$$
Comment: you might also want to read up on the twelvefold way
Comment: Can you please explain how you use stirling numbers in order to partition a set of size n into m parts? @User4140
Comment: an can you please explain the last part of the solution more explicitly? @user4140
Comment: The number of ways to partition a set of size n into m parts is exactly S(n,m). Once a partition has been chosen(so the bundles of the domain have been asserted). All that is left to chose is which of these bundles will map to each of the elements of the codomain. We can do this in m! ways. So there are n!(S(n,m) surjective functions. However the probability a function will be surjective is (number of surjective functions)/(number of functions) and the number of functions is $n^m$


Does Windows Server backup use BITS?

Question: I've been told that Windows Server 2008 and newer uses the BITS service to transfer files that are backed up to a UNC share (using Windows server backup/NTbackup) but I can't find any documentation to support this. Is this true? If so, is it the default or does it require additional configuration of the backup job to use the service?
Comment: BITS is client-side...it uses SMB to send files to a remote share.
Answer: The information you were provided is inaccurate. Background Intelligent Transfer Service (BITS) is not used by Windows Server Backup in any way.
Windows Server Backup was introduced in Windows Server 2008 (and Windows Vista) as a replacement for the old "NTBackup" utility and the derived versions present in Windows 2000 Server and Windows Server 2003. It was significantly revised in Windows Server 2008 R2 and continues to be present in current versions of Windows Server.
It's difficult to "prove a negative" here, in terms of giving you a link to a Microsoft document that says "Windows Server Backup doesn't use BITS" because no such document exists. Windows Server Backup creates virtual hard drive (VHD) files and loads them with the contents of the filesystem being backed-up. On locally-mounted volumes serving as the backup destination multiple generations of backup are able to be stored in one location (by virtue of the Volume Shadow Copy Services (VSS) functionality). Remotely-mounted volumes (over SMB) serving as the backup destination do not have this capability and can only store a single generation of backup per location.
Comment: Though, if one had to, one could set up a script using the PowerShell BITS cmdlets to arrange for a backup stored locally to be sent to a remote location via BITS.  I... have had to do such things recently. :(

Does Windows Server backup use BITS?


Is there a standard method to deal with label switching problem in MCMC estimation of mixture models?

Question: Label switching (i.e., the posterior distribution is invariant to switching component labels) is a problematic issue when using MCMC to estimate mixture models.

Is there a standard (as in widely accepted) methodology to deal with the issue?
If there is no standard approach then what are the pros and cons of the leading approaches to solve the label switching problem?
Comment: I was considering asking "How can I do an MCMC model of the output on lmer for models with random slopes?" but I'm wondering whether that question is redundant with this one.  That is, is the "label switching issue" when using MCMC to estimate mixture models the same sort of problem take makes it so that pvals.fnc() in languageR is able to MCMC intercept models but not models with slopes?  If not, please let me know and I'll go back to asking my initial question.
Comment: @drknexus I do not know R to comment in your question. Perhaps, you should just post your question with a comment that your qn may be lined to this one.
Answer: There is a nice and reasonably recent discussion of this problem here:

Christian P. Robert Multimodality and label switching: a
  discussion. Workshop on mixtures, ICMS March 3, 2010.

Essentially, there are several standard strategies, and each has pros and cons. The most obvious thing to do is to formulate the prior in such a way as to ensure there is only one posterior mode (eg. order the means of the mixuture components), but this turns out to have a strange effect on the posterior, and therefore isn't generally used. Next is to ignore the problem during sampling, and then post-process the output to re-label the components to keep the labels consistent. This is easy to implement and seems to work OK. The more sophisticated approaches re-label on-line, either by keeping a single mode, or deliberately randomly permuting the labels to ensure mixing over multiple modes. I quite like the latter approach, but this still leaves the problem of how to summarise the output meaningfully. However, I see that as a separate problem.
Comment: seems the link is broken
Comment: I fixed the link by finding it on web.archive.org and providing link to a copy of thos slides hosted by the author on SlideShare.
Answer: Gilles Celeux also worked on the problem of label switching, e.g.

G. Celeux, Bayesian inference for
Mixture: the label switching problem.
Proceedings Compstat 98, pp. 227-232, Physica-Verlag (1998).

As a complement to @darrenjw's fine answer, here are two online papers that reviewed alternative strategies:

Jasra et al., Markov Chain Monte Carlo Methods and the Label Switching Problem in Bayesian Mixture Modelling
Sperrin et al., Probabilistic relabelling strategies for the label switching problem in Bayesian mixture models
Answer: With the R-Package "label.switching" (https://cran.r-project.org/web/packages/label.switching/index.html), the following algorithms can be compared:
ECR algorithm (default version), ECR algorithm (two iterative versions), PRA
algorithm, Stephens' algorithm, Artificial Identifiability Constraint (AIC), Data-Based relabelling and a probabilistic relabelling algorithm (SJW).
With the function permute.mcmc() the labels in the mcmc chains can be relablled for parameters that differ between mixture components or latent classes.


How to make div stack first vertically then horizontally?

Question:
Possible Duplicate:
How to stack divs from top to bottom in CSS

When i have multiple adjacent divs with float:left, they stack like this:
 _______
| 1 2 3 |
| 4 5   |
|_______|

I want a stack like this:
 _______
| 1 4   |
| 2 5   |
|_3_____|

jsFiddle with the horizontal stacking
How can i achieve vertical stacking ?
Comment: This is a good question, but why in first place ? you want to fill the space the user have displayed then continue to scroll to see more...
it seems you're working on some mobile website or so
Answer: @ pinouchon; for this type of layout you can use css3 column-count property for this.
CSS:
div#multicolumn1 {
        -moz-column-count: 2;
        -moz-column-gap: 10px;
        -webkit-column-count: 2;
        -webkit-column-gap: 10px;
        column-count: 2;
        column-gap: 10px;

}

Check my example here for more How to stack divs from top to bottom in CSS
read this article for more http://www.quirksmode.org/css/multicolumn.html
Comment: This is technically not a correct solution because the css will prioritize horizontal first then vertical, for proof try to have only 2 items. OP's question seems want to prioritize vertical and then horizontal.
For prioritizing vertical and then horizontal, look into, display: flex; flex-direction: column; flex-wrap: wrap;
Comment: This [doesn't work for IE, at all](http://caniuse.com/#search=column-count).
Comment: yes; css3 column-count property is not work in IE for this you can use js http://www.csscripting.com/css-multi-column/ put this in IE comment.


xml.etree or xml.dom?

Question: I am trying to read some xml, but I'm not sure which library I should use.
What is better xml.etree or xml.dom, and why?
Please, explain your answers and give arguments.
Also, do you think one of them is going to get deprecated? Which one?
Answer: Neither will be deprecated.
ElementTree (xml.etree) is a pythonic API to access XML. DOM (xml.dom) is a cross-platform, language independent standard.
Use ElementTree unless you have a compelling reason to use the XML DOM instead. For python code, the ElementTree API is far easier to use than the DOM API.
If you are not averse to installing extra python libraries, you should take a look at the lxml library as well; it implements the ElementTree API as well, on top of very fast C libraries, and adds a few more options to work with XML effectively.
Comment: @MateuszKowalczyk: lxml is based on the ElementTree API; hence my use of that term. I've added it as an extra option.
Comment: I'd like to add that OP should also look into the lxml library, which is pretty similar, but quite a fair bit faster.

xml.etree or xml.dom?


How to use str_replace in laravel

Question: how to use php function str_replace in laravel framework.
My array key names on table columns name so keys have '_' like first_name, last_name etc. i want to remove these '_' in blade file. my requirement is string replace in .blade.php file.
i am trying this php code but it's useless.
{{str_replace('_', ' ', $str)}}

thanks
Comment: What do you mean by "useless"? I see no reason why this wouldn't work.
Comment: It works. My guess is `$str` is undefined or empty.
Comment: You may want to actually make them camel case instead ("firstName" instead of "firstname").  See the Laravel camel_case() function for that.
Answer: Which version of Laravel did you use?
For laravel 5.x, use this
{!! str_replace('_', ' ', $str) !!}

Answer: You can use php code in .blade.php file
try like this
 <?=str_replace('_', ' ', $str)?>

Answer: use Illuminate\Support\Str;

$string = 'The event will take place between ? and ?';

$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);

// The event will take place between 8:30 and 9:00

For Blade
 $item = "Free-Active";
{{ Str::replaceArray('free-', [''], $item) }}

Answer: In Laravel 8 you can use the String Helper function:
use Illuminate\Support\Str;

{{ Str::replace('_', ' ', $str) }}

Answer: You may use this
{{-- */ echo str_replace('_', ' ', $str); /* --}}

OR
{{-- */ $data = str_replace('_', ' ', $str); /* --}} {{$data}}

How to use str_replace in laravel


simple error: point array

Question: I have the following:
array<Point>^ ADC1=gcnew array<Point>(2);
ADC1={Point(period,points[0][0]),Point(period,points[0][1])}; // error here!

However I get the following error when I attempt to compile the code:
error C2059: syntax error : '{'
The error is at the line ADC1={ ...
period is an int and points is a 2D array with int values.
can anyone help me out?
Thanks in advance
Comment: That was stupid! I used ADC1[0] and ADC1[1] and it worked. However, I would still like to know why the above doesn't work.
Comment: If I am right you can make initial value list only at constructor, not after constructing array.
Answer: I think you can explicit initial values only at constructor level, try:
array<Point>^ ADC1=gcnew array<Point>(2);
ADC1[0] = Point(period,points[0][0]);
ACD1[1] = Point(period,points[0][1]);

Comment: yea I figured that out. check my previous comment :) . Thanks
Comment: You have posted comment while I was writing this answer :)
Answer: Like in regular C++, C++ COM Extensions only allow you to do initialize with an aggregate when constructing, you can't assign an aggregate to an existing array. Something like this should work, though:
array<Point>^ ADC1 = gcnew array<Point>{Point(period,points[0][0]),Point(period,points[0][1])};

for more info, see the second example on this page:
http://msdn.microsoft.com/en-us/library/vstudio/dtbydz1t.aspx

simple error: point array


How can I calculate the confidence interval of a mean in a non-normally distributed sample?

Question: How can I calculate the confidence interval of a mean in a non-normally distributed sample?
I understand bootstrap methods are commonly used here, but I am open to other options. While I am looking for a non-parametric option, if someone can convince me that a parametric solution is valid that would be fine. The sample size is > 400.
If anyone could give a sample in R it would be much appreciated.
Comment: The Central Limit Theorem implies that the limiting distribution of the sample mean is normal regardless of the distribution of the original data (under some conditions). In many cases a sample size $n>400$ is large enough so that the normal approximation is quite accurate but the accuracy does depend on the parent distribution-- it might help if you, for example, posted a histogram of the original data.
Answer: First of all, I would check whether the mean is an appropriate index for the task at hand. If you are looking for "a typical/ or central value" of a skewed distribution, the mean might point you to a rather non-representative value. Consider the log-normal distribution:
x <- rlnorm(1000)
plot(density(x), xlim=c(0, 10))
abline(v=mean(x), col="red")
abline(v=mean(x, tr=.20), col="darkgreen")
abline(v=median(x), col="blue")

The mean (red line) is rather far away from the bulk of the data. 20% trimmed mean (green) and median (blue) are closer to the "typical" value.
The results depend on the type of your "non-normal" distribution (a histogram of your actual data would be helpful). If it is not skewed, but has heavy tails, your CIs will be very wide.
In any case, I think that bootstrapping indeed is a good approach, as it also can give you asymmetrical CIs. The R package simpleboot is a good start:
library(simpleboot)
# 20% trimmed mean bootstrap
b1 <- one.boot(x, mean, R=2000, tr=.2)
boot.ci(b1, type=c("perc", "bca"))

... gives you following result:
# The bootstrap trimmed mean:
> b1$t0
[1] 1.144648

BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
Based on 2000 bootstrap replicates
Intervals :
Level     Percentile            BCa
95%   ( 1.062,  1.228 )   ( 1.065,  1.229 )
Calculations and Intervals on Original Scale

Comment: Thanks very much for the detailed answer. Would you care to comment on the (minimal) difference between the percentile and adjusted percentile (BCa) statistics?
Comment: "The bootstrap bias-corrected accelerated (BCa) interval is a modification of the percentile method that adjusts the percentiles to correct for bias and skewness" (Hesterberg, T., Monaghan, S., Moore, D., Clipson, A., & Epstein, R. (2005). Bootstrap methods and permutation tests. Introduction to the Practice of Statistics, 14.1–14.70.). Whenever the software allows it, use the BCa corrected CI (note: it needs > 1000 resamples)
Comment: It seems from the [documentation](https://cran.r-project.org/web/packages/simpleboot/simpleboot.pdf) for the simpleboot package that the argument for trimming is no longer supported. :(
Answer: If you are open to a semi-parametric solution, here's one: Johnson, N. (1978) Modified t Tests and Confidence Intervals for Asymmetrical Populations, JASA. The center of the confidence interval is shifted by $\hat\kappa/(6s^2n)$, where $\hat\kappa$ is the estimate of the population third moment, and the width stays the same. Given that the width of the confidence interval is $O(n^{-1/2})$, and the correction for the mean is $O(n^{-1})$, you need to have a really sizable skewness (of the order $n^{1/2}>20$) for it to matter with $n>400$. The bootstrap should give you an asymptotically equivalent interval, but you would also have the simulation noise added to the picture. (The bootstrap CI corrects for the same first order term automatically, according to the general Bootstrap and Edgeworth Expansion (Hall 1995) theory.) For what I can recall about simulation evidence, the bootstrap CIs are somewhat fatter than the CIs based on the analytic expressions, though.
Having the analytic form of the mean correction would give you an immediate idea of whether the skewness really needs to be taken into account in your mean estimation problem. In a way, this is a diagnostic tool of how bad the situation is. In the example of the lognormal distribution given by Felix, the normalized skewness of the population distribution is $(\exp(1)+2)*\sqrt{ \exp(1) - 1}$, which is kappa = (exp(1)+2)*sqrt( exp(1) - 1) = 6.184877. The width of the CI (using the standard deviation of the population distribution, s = sqrt( (exp(1)-1)*exp(1) ) = 2.161197) is 2*s*qnorm(0.975)/sqrt(n) = 0.2678999, while the correction for the mean is kappa*s/(6*n) =  0.00222779 (the standard deviation migrated to the numerator since kappa is the scale-free skewness, while Johnson's formula deals with the unscaled population third central moment), i.e., about 1/100th of the width of the CI. Should you bother? I'd say, no.
Answer: Try a log-normal distribution, calculating:

Logarithm of the data;
Mean and standard deviation of (1)
Confidence interval corresponding to (2)
Exponential of (3)

You'll end up with an asymmetric confidence interval around the expected value (which is not the mean of the raw data).


Show that the total space $E$ of a fibre bundle $\pi : E \rightarrow M$ is connected.

Question: Let $(E,\pi,M,F)$ is a fibre bundle. The map $\pi : E \rightarrow M$ is the projection map. The smooth manifolds ; $E$ is the total space, $M$ is the base space, and $F$ is a smooth manifold appear in the following local trivialization : For any $p \in M$, there are open subset $U\subset M$ contain $p$ and diffeomorphism
$$\phi : \pi^{-1}(U) \rightarrow U \times F$$
such that $\pi = Proj_U \circ \phi$ on $\pi^{-1}(U)$, where $Proj_U : U \times F \rightarrow U$ is the projection to the first factor.
$\textbf{Problem}$ : If $M$ and $F$ connected, show that $E$ is connected.
I already make such construction, but i'm not really sure and curious about other solution too. Feel free to post new proof or disprove my proof :
I'm having hard time with this, but i end up trying to prove this by using the following theorem from topology (e.g from Willard's book theorem 26.15) : If a topological space $X$ is connected and $\mathscr{U}$ is an open cover for $X$, then any two points can be connected by a simple chain consisting of elements of $\mathscr{U}$.
By local trivialization for each $p \in M$ we have an open subset $U \subset M$ containing $p$ and a diffeomorphism $\phi : \pi^{-1}(U) \rightarrow U \times F$. Let $\{\pi^{-1}(U)\}$ be the open cover for $E$. Because $F$ and $M$ connected, then  $U\subset M$ connected, $U \times F$ connected, $\phi^{-1}(U\times F) = \pi^{-1}(U)$ connected. With this open cover, we have a simple chain where each of its elements is connected (implies path-connectedness). By this we can easily make a path connecting $v,w \in E$ by joining the paths from each chain.
Answer: Suppose that $E$ is not connected, there exists a surjective continuous function $f:E\rightarrow \{0,1\}$ write$U=f^{-1}(0), V=f^{-1}(1)$, $E=U\cup V$ where $U$ and $V$ are not empty, let $\pi:E\rightarrow M$ the projection map. Remark that $\pi$ is an open map. This implies that $\pi(E)=M=\pi(U)\cup (V)$ is the  union of the open subsets $\pi(U)$ and $\pi(V)$ wich are not disjoint since $M$ is connected. Let $x\in \pi(U)\cap \pi(V)$, there exists $y_1\in U, y_2\in V$ such that $\pi(y_1)=\pi(y_2)=x$, since $\pi^{-1}(x)$ is connected, the restriction of $f$ to $\pi^{-1}(x)$ is constant, but $f(y_1)=0, f(y_2)=1$. Contradiction.
Comment: Thanks. I think using contradiction to but i didnt realize that $\pi$ is an open map so i'm stuck. How i follow that $\pi^{-1}(x)$ connected ? Is it from $\pi = Proj_U \circ \phi$ ?
Comment: It is just a fibre of the fibration.


ImportError: cannot import name 'Sized' from 'collections'

Question: I am trying to use one package that somebody developed on GitHub called PyLipid.
The first parts of the code are importing various packages, but I am continuously getting this error, showed bellow:
%matplotlib inline
import pylipid
import collections
from pylipid.api import LipidInteraction
# print(pylipid.__version__) # make sure pylipid version is later than 1.4

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Input In [37], in <cell line: 4>()
      2 import pylipid
      3 import collections
----> 4 from pylipid.api import LipidInteraction

File ~/miniconda3/envs/work/lib/python3.10/site-packages/pylipid/api/__init__.py:32, in <module>
      1 ##############################################################################
      2 # PyLipID: A python module for analysing protein-lipid interactions
      3 #
   (...)
     14 # copies or substantial portions of the Software.
     15 ##############################################################################
     17 r"""
     18 PyLipID class
     19 =============
   (...)
     29
     30 """
---> 32 from .api import LipidInteraction

File ~/miniconda3/envs/work/lib/python3.10/site-packages/pylipid/api/api.py:30, in <module>
     28 import pandas as pd
     29 from tqdm import trange, tqdm
---> 30 from p_tqdm import p_map
     31 from ..func import cal_contact_residues
     32 from ..func import Duration

File ~/miniconda3/envs/work/lib/python3.10/site-packages/p_tqdm/__init__.py:1, in <module>
----> 1 from p_tqdm.p_tqdm import p_map, p_imap, p_umap, p_uimap, t_map, t_imap
      3 __all__ = [
      4     'p_map',
      5     'p_imap',
   (...)
      9     't_imap'
     10 ]

File ~/miniconda3/envs/work/lib/python3.10/site-packages/p_tqdm/p_tqdm.py:11, in <module>
      1 """Map functions with tqdm progress bars for parallel and sequential processing.
      2
      3 p_map: Performs a parallel ordered map.
   (...)
      8 t_imap: Returns an iterator for a sequential map.
      9 """
---> 11 from collections import Sized
     12 from typing import Any, Callable, Generator, Iterable, List
     14 from pathos.helpers import cpu_count

ImportError: cannot import name 'Sized' from 'collections' (/home/srdjanm/miniconda3/envs/work/lib/python3.10/collections/__init__.py)

Does anybody know how to solve this error? I have also posted the question on the webpage in github but it might take a while for someone to respond, also this seems to me like a more general problem. Is this the package or "python version" related issue?
Comment: It should be `from collections.abc import Sized` but maybe the library needs more updates to work.
Comment: What is your purpose with the lib? using it or developing it? If using is considered then you can just pip3 install it. and it should be collections.abc.Sized.
Comment: I wish to use it, but I think this library is too old and nobody has updated it for python 3 onwards. I'll check up on it. Thanks a lot!
Answer: You may want to modify one line in the library to it works. It was created a pull request in github of p_tqdm library

In file ~/miniconda3/envs/work/lib/python3.10/site-packages/p_tqdm/p_tqdm.py modify line 11 from
from collections import Sized

to
from collections.abc import Sized


How can I alter the php get_included_files array?

Question: http://php.net/manual/en/function.get-included-files.php
get_included_files — Returns an array with the names of included or required files
I need to be able to alter that array to stop inclusion of certain files.  I know this is a terrible design flaw, but I am presented with a problem of updating some read only files as a temporary solution while we complete a more permanent solution.  I was able to make a second set of the files and use .htaccess to redirect the web requests to my hacked files, but I would like to use the original files where modifications were not needed.
Long story short, if I can add a file to the array of files that have already been included my problem will be solved.
Thanks
Comment: Do you mean you want to tell PHP to pretend that it's included certain files, when it really hasn't?
Comment: If there is any solution to your problem, it is not "altering the included files" . So let's look at your goal: preventing the inclusion of files. Your possibilities depend on a) which files you can technically modify (talking about write permissions, not about what should not be modified) and b) how the files are included (include, include_once, require, require_once). Please add this information to your question.
Answer: By removing content from the array that get_included_files() function will return, will not help you. you need to manually remove that require or include line from the particular file where it is being used. If you are using any debugging tool it would be very helpful. Even eclipse 'll be helpful


Why use bar chart with error whiskers instead of box plot?

Question: Bar charts with error whiskers, like the one below (taken from What type of plot is it?), seem to be quite common in some communities.

I wonder, however, why is a bar chart used, and not a box plot? For pure values without uncertainties (i.e., when we wouldn't use the whiskers) I can see that bar charts are cleaner and easier to comprehend. But, box plots offer much more information about data spread, uncertainties, etc.
So, is there a good reason speaking in favour of bar charts with whiskers?
Comment: Boxplots don't lend themselves to making the comparisons implied by this chart (namely, formal tests of differences of means).
Comment: Three excellent answers to date. I want to flag generally the existence of even more negative views from some statisticians. often to be found by Googling one or more depreciatory terms _detonator plot_, _dynamite plot_  or _plunger plot_.  For example, https://simplystatistics.org/posts/2019-02-21-dynamite-plots-must-die/  and https://biostat.app.vumc.org/wiki/Main/DynamitePlots  I  find box plots often oversold, especially for discrete data, or equivalently data with just a few distinct values, where their logic often defeats users, and gives rise to many puzzled threads on this site.
Comment: The *very same* plot appears at https://stats.stackexchange.com/questions/591170, which includes more information about its source.
Comment: It's remarkable how many texts (and one has to guess courses too) advise supplementing analysis of variance with a look at box plots. Looking at graphs of distributions beats not looking at them, but as already mentioned in answers at the minimum the box plots should show means too.
Comment: Incidentally, [violin plots](https://en.wikipedia.org/wiki/Violin_plot) (also known as bean plots) convey much more information than boxplots. (If need be, you can overlay a box plot over a violin plot, or even add the individual observations if there are not too many of them - for the small numbers involved here, I would definitely try that and see whether it works well.)
Comment: Many posts on site relate to this question, I suggest trying some searches with suitable keywords
Answer: Personally, I have never encountered a good use case for bar plots and think it's mostly inertia in some fields that leads to their continued use.

If you like Tufte's ideas about data-ink ratios, it's clear that they take up far too much plot area to convey quite little information. All the information in the bar can be communicated with a point.
One-sided error bars also don't offer much leeway for communicating asymmetric errors/confidence intervals. Two-way error bars are less clear because of overlap with the bar itself.
Since the information is contained in the height, you need to be especially careful about the starting value and the scale for the Y-axis. I'd say that starting at zero and linear scales are generally more important for easy and intuitive interpretation of barplots than alternatives such as dot charts.

There's probably one feature that supporters would claim makes them superior, which is the ability to use shading/texture in the bar to distinguish between categories. I don't think this is a particularly strong point, but it's the only defence I can think of.
That said, in many circumstances, they are not actively harmful and non-statisticians seem to find them visually appealing, so they tend to persist.
I would add that though boxplots communicate more information, they also have weaknesses and can sometimes mislead. If you're summarising just a few data points, it's better to just plot the raw data, possibly with some jittering or transparency. Other options include histograms, violin plots, and dot charts/beeswarm plots.
Comment: Great answer.  I frequently tell people *"bar charts are for people who spend too much time in bars, and box charts are for people who spend too much time in boxes"*.  This intentionally confuses them, and by design, it finally gets them thinking about their choices. ;)
Answer: Realistically, the reason people do most of the things they do, is tradition / habit.  'Such-and-such is what I learned in graduate school, it's what I've always done, it's what everyone else in my field does, it's what reviewers / editors / readers will expect and understand readily.'

Having said that, we can ask if there is any better justification for bar charts with error bars over boxplots.  I agree that boxplots do show more information on the whole, but something can be said for bar charts:

People are typically interested in group means.  Bar charts display means directly.  Boxplots, by default, do not display means, although they can be augmented to do so.
People are typically interested in inferences about means.  The error bars on bar charts, while they can be tricky in some cases, do display information that is relevant to the inference about the means.  Boxplots, by default, do not, although they can be augmented to do so.
People are not typically primarily interested in various quantiles.  Boxplots make it easy to see the median and quartiles, and the minimum and maximum values.  I think these are interesting, but they are typically not what researchers are theorizing about.  Bar charts do not display this information, which people might consider extraneous and adding 'clutter' to the display.  (I don't really agree with that take, but I'm well aware that many people hold it.)

In short, bar charts display what most end users want to see, and not what they don't.  It's the opposite for boxplots, although I do wish these attitudes were less prevalent.
Comment: Nb, I have made boxplots for people and had them say, 'can you just make me a barchart?' :/
Answer: Boxplots (and violin plots, which I prefer because they convey more information, and the raw observations themselves) visualize observations and summary information of the observations. Barplots, as used in these communities, visualize parameter estimates. Typically, as in the example you give, the estimate is simply the group mean, so there actually is little difference, and the choice is down to a community's traditions and expectations.
However, suppose there is one grouping factor, and also one numerical covariate. Boxplots or violin plots can plot the data and their means per group. But we would lose the information about the covariate. A simple way of giving a visual summary would be to plot three bars per group: one with the estimated response within the group with the covariate at its 25% quantile, one with the covariate at its median and one with the covariate at its 75%. In each case, we can also add a whisker to show the standard error of the estimate. Note that boxplots can't convey this kind of information.
However, I would still say that a simple dot with whiskers would still be superior to the bar plot, if only because of the within-the-bar-bias that barplots induce. And in any case, one must note in the figure caption what the whiskers refer to - are they the estimate plus one standard error of the estimate (e.g., SEM), or plus two standard errors, or are they the standard deviation of the raw data being plotted, or what?
Comment: (+1) About your first sentence: it may not be standard, but it seems to me that Bayesian posteriors could easily (and helpfully) be visualised with violin plots, so they need not be restricted to observations.
Comment: Yes, they are. But they are *observation*-derived, not *model*-derived. A dotchart (and its worse analogue, the barplot) can also plot *model*-derived quantities. You could also plot regression coefficient estimates and their standard errors using dotcharts/barplots, but you can't use boxplots for that.
Comment: "Boxplots ... visualize ... summary information of the observations": But the mean and the standard deviation (of the sample) **are** summary information, too, aren't they?


Tools to show a function is decreasing

Question: I was asked to prove that the following function is decreasing
$f(x)=\left(\left(1-\frac{1}{x}\right)^{x}\right)^{x}$ for every $2<x$
I was wondering what tools do I have except the derivate method?
It seems that there is some trick with this specific functions, as $\left(1-\frac{1}{x}\right)^{x}$ is increasing.. Which also quiet confuses me..
Answer: $(1-\frac{1}{x})^x$ does increase a little as $x$ increases but that is not the point, the point would be how much it increases and more specifically if it reaches a point where it is $> 1$ as this is going to be raised to a power and any a number greater than $1$ raised to a positive power will get bigger while any positive number less than $1$ raised to a positive power will get smaller.
Take a look at this graph of $(1-\frac{1}{x})^x$ for $x>2$, as you see it does increase a little bit at first but then you can see the curve flatten out even for smaller numbers and most importantly stays below $1$ for all values.
In fact, an interesting result is that $\lim_{x->\infty}(1-\frac{1}{x})^x=\frac{1}{e}\approx 0.367$ so raise that to the power $x$ and the bigger $x$ bigger the more this will increased as it is a positive number smaller than $1$
Answer: As $x$ increases, $\left( 1 - \frac{1}{x} \right)$ decreases for $x>2$.  Raise that to a power of $x$, it decreases even more.  Raise that to a power of $x$ and it decreases even more.
Here's a graph:
Comment: I don't think that's correct.. as x increasing 1/x decreases and 1-1/x increases. :(

Tools to show a function is decreasing


What does if(false) in php mean?

Question: Today, I decided to download wordpress and the first file that I have come across is wp-admin/install.php. the first thing in the file is this:
// Sanity check.
if ( false ) {
?>
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Error: PHP is not running</title>

WordPress

Error: PHP is not running

WordPress requires that your web server is running PHP. Your server does not have PHP installed, or PHP is turned off.

<?php
}

Now I am kind of wondering, What is if( false ) ? and how does it mean that the user is not running php on their server?
Answer: If the PHP is running on the server, the statement inside if ( false ) will be skipped, because this equates to FALSE or its like if(0) .
But in such cases that PHP compiler does not exist, the server will parse all html codes inside that statement ,(saying PHP is not running).
It's a sanity check.
Answer: Yes, because condition is never true when being executed by PHP server, in consecuence PHP is running in the server. Otherwise you will see the HTML that say PHP is not running. Because php code is what is not being executed in this case.

What does if(false) in php mean?


Por que não posso usar o método delete() do StringBuilder mais de uma vez no mesmo bloco de código?

Question: Estou tentando apagar um intervalo de conteúdo de uma StringBuilder, mas ao usar o método delete() mais de uma vez o programa dá erro.
Especificamente, estou tentando deletar a parte da resolução em pseudocódigo de algumas questões de um livro virtual, deixando apenas o enunciado.
Há um padrão no momento de início dos pseudocódigos, pois iniciam com prog e termina com fimprog. Observe o exemplo abaixo:
algoritmo 362
Criar um algoritmo que leia dois conjuntos de números inteiros, tendo cada
284 um 10 e 20 elementos, e apresente os elementos comuns aos conjuntos. Lembre-se de que os elementos podem se repetir, mas não podem aparecer repetidos na saída.
prog vetorl10

pseudocógigos...

fimprog

algoritmo 363
Criar um algoritmo que leia vários números inteiros e positivos. A leitura se en-
cerra quando encontrar um número negativo ou quando o vetor ficar completo.
Sabe-se que o vetor possui, no máximo, 10 elementos. Gerar e imprimir um vetor
onde cada elemento é o inverso do correspondente do vetor original.
prog vetorl11

pseudocógigos...

fimprog

algoritmo364...

Etapas do código:

O programa ler um arquivo;
Coloca o conteúdo em uma StringBuilder;
O programa pega o índice inicial da palavra "prog" e da "fimprog";
O programa chama o método delete e apaga o conteúdo dos intervalos definidos;
O programa pega novamente o próximo índice da palavra "prog" e da "fimprog" e consegue, mas na hora de apagar o próximo intervalo dá erro.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.Character.Subset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BuscarPadroes {

    public static void main(String[] args) {

        String path = "c:\\socket\\Lista_vetor.txt";

        String line;
        StringBuilder conteudo = new StringBuilder();
        int cont = 0;
        try (BufferedReader br = new BufferedReader(new FileReader(path))) {

            while (br.ready()) {
                line = br.readLine();
                cont++;
                conteudo.append(line + "\n");
            }

            int start = conteudo.indexOf("prog");
            int end = conteudo.indexOf("fimprog");
            conteudo.delete(start, end);

            start = conteudo.indexOf("prog ");
            end = conteudo.indexOf("fimprog");
            conteudo.delete(start, end);

        } catch (IOException erro) {
            System.out.println("Error: " + erro.getMessage());
        }
    }
}

Answer: O problema está na lógica do seu delete. O método indexOf retornará o índice do começo da palavra, então você precisa considerar o tamanho da palavra ao passar para o método delete. Se não fizer isso, na segunda iteração a palavra "fimprog" estará antes da palavra "prog", causando erro.
int start = conteudo.indexOf("prog");
int end = conteudo.indexOf("fimprog") + "fimprog".length();
conteudo.delete(start, end);

Para mais detalhes consulte a documentação da classe StringBuilder: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/StringBuilder.html
Comment: Ótimo. Eu compreendi o método indexOf de outra maneira, mesmo lendo a documentação. Muito obrigado!
Answer: Tem vários problemas aí. O primeiro já foi indicado na outra resposta: indexOf retorna o índice onde começa a ocorrência da substring. Ou seja, conteudo.indexOf("fimprog") vai retornar a posição onde começa a string "fimprog", o que quer dizer que "fimprog" não será removido de fato, pois segundo a documentação, o segundo índice não é incluso (por exemplo, delete(1, 4) apaga as posições 1, 2 e 3). Ou seja, "fimprog" não é removido, e na segunda vez que você busca, ele estará antes de "prog", ou seja start será maior que end - e a documentação diz que nesse caso dá erro.
Então você tem que pegar mais 7 posições à frente (ou 8 se quiser eliminar também a quebra de linha), mas ainda tem outros problemas. Seu código foi feito de forma que só busca duas ocorrências de "prog" e "fimprog", mas e se tiver mais (ou menos - o que inclui o caso de não ter nenhuma)? E se só tiver "prog" sem o respectivo "fimprog"? Etc...
Enfim, para um caso mais geral, seria melhor fazer um loop. Enquanto tiver "prog" e "fimprog", vai removendo. Quando não tiver mais, sai do loop:
while (true) {
    int start = conteudo.indexOf("prog");
    if (start < 0) {
        // não tem prog, nem adianta continuar
        break;
    }
    int end = conteudo.indexOf("fimprog");
    if (end < 0) {
        // não tem fimprog, nem adianta continuar
        break;
    }
    if (start > end) {
        System.out.println("texto mal formado, prog está depois de fimprog");
        break; // texto mal formado, nem adianta continuar
    }
    // somar o tamanho de "fimprog", senão ela não é apagada
    conteudo.delete(start, end + 7);
}

Invertendo a lógica
Mas na verdade, eu acho que isso tudo é desnecessário. Em vez de jogar o texto inteiro para uma String e depois sair buscando e removendo alguns trechos, não seria melhor simplesmente não adicionar os trechos que você não quer?
Assumindo que "prog" e "fimprog" sempre estão no início da linha, ficaria assim:
boolean adiciona = true;
while (br.ready()) {
    line = br.readLine();
    if (line.startsWith("prog")) {
        adiciona = false;
    } else if (line.startsWith("fimprog")) {
        adiciona = true;
    } else if (adiciona) {
        conteudo.append(line + "\n");
    }
}

Ou seja, se encontro "prog", eu ignoro todas as linhas dali em diante, até encontrar "fimprog" (e aí eu volto a adicionar as linhas, até que encontre um "prog" novamente). O detalhe é que neste caso não estou verificando se o arquivo está mal formado (se só tiver um "prog" e não tiver o respectivo "fimprog", por exemplo, todo o restante do arquivo depois desse "prog" será ignorado). Se existe essa possibilidade, aí a primeira opção acima seria melhor (ou, dependendo do caso, talvez seja o caso de fazer um parser próprio para validar). Mas se é "garantido" que o arquivo é sempre bem formado, eu acho melhor fazer assim, em vez de adicionar tudo para depois ir removendo.
Comment: Poxa, muito obrigado. Era exatamente a lógica inversa que eu tentei fazer, porém, não consegui e resolvi tentar dessa maneira. Detalhe, eu coloquei duas ocorrências para teste e por falta de uma compreensão melhor do indexOf. Voltarei a ler a documentação do método.


Erro ao realizar update Mysql com chaves compostas

Question: Tenho a seguinte tabela no Mysql

Tentei de todas as formas realizar um sql de update porem todas as vezes retorna o mesmo erro abaixo.

Cannot add or update a child row: a foreign key constraint fails

Esse é o sql de update
UPDATE ACDM_TREI_RLZD_ALU_EXCC SET EST_EXCC = 'OK' WHERE CD_ALU = 1 AND TS_RLZC_TREI = '2019-02-16' AND NR_EXCC= 1

Essa é a tabela em que ela é dependente

Alguma ideia do que posso estar errando?
Comment: Essa coluna EST_EXCC é referenciada em outra table?
Comment: Não. Ela é uma coluna comum
Comment: Manda o create table dessa tabela.
Comment: Editei a pergunta e coloquei o create
Comment: O update foi normal aqui.

UPDATE ACDM_TREI_RLZD_ALU_EXCC SET EST_EXCC = 'OK'
WHERE CD_ALU = 1 AND
date(TS_RLZC_TREI) = '2019-02-16' AND
NR_EXCC= 1
Comment: qualquer coisa manda as outras tables que ele utiliza como foreign
Comment: Coloquei na pergunta as tabelas relacionadas
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/89808/discussion-between-bilico-and-user129333).
Answer: No create abaixo você está usando a coluna TS_RLZC_TREI da tabela ACDM_TREI_RLZD_ALU_EXCC como chave estrangeira. Porém o valor dela que é referência está atualizando sempre que você da um update devido o comando do create.
#`TS_RLZC_TREI` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),

O create ficaria desta forma:
CREATE TABLE IF NOT EXISTS `ACDM_TREI_RLZD_ALU_EXCC` (
  `CD_ALU` bigint(20) NOT NULL,
  `TS_RLZC_TREI` timestamp NOT NULL DEFAULT current_timestamp(), /*A alteração está aqui*/
  `NR_EXCC` int(11) NOT NULL,
  `CD_EXCC` int(11) NOT NULL,
  `QT_SRE` int(11) NOT NULL,
  `QT_RPTC` int(11) NOT NULL,
  `HR_DESC` time DEFAULT NULL,
  `QT_KG` decimal(15,3) DEFAULT NULL,
  `HR_DRCO` time DEFAULT NULL,
  `TX_OBS` varchar(255) DEFAULT NULL,
  `TS_ULT_ALT` timestamp NOT NULL DEFAULT current_timestamp(),
  `CD_USU_RSP` int(11) NOT NULL DEFAULT 0,
  `EST_EXCC` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


flask session not reloading

Question: Right now I am using Flask and a flask 3rd party library Flask-Session
Using the code below, I reload the page 4 times and get the following output:
set userid[0]
127.0.0.1 - - [27/Sep/2014 22:28:35] "GET / HTTP/1.1" 200 -
set userid[1]
127.0.0.1 - - [27/Sep/2014 22:28:37] "GET / HTTP/1.1" 200 -
set userid[2]
127.0.0.1 - - [27/Sep/2014 22:28:37] "GET / HTTP/1.1" 200 -
set userid[3]
127.0.0.1 - - [27/Sep/2014 22:28:38] "GET / HTTP/1.1" 200 -

Code:
from flask import Flask, session
from flask.ext.session import Session

app = Flask(__name__)
sess = Session()

nextId = 0

def verifySessionId():
    global nextId

    if not 'userId' in session:
        session['userId'] = nextId
        nextId += 1
        sessionId = session['userId']
        print ("set userid[" + str(session['userId']) + "]")
    else:
        print ("using already set userid[" + str(session['userId']) + "]")
    sessionId = session.get('userId', None)
    return sessionId

@app.route("/")
def hello():
    userId = verifySessionId()
    return str(userId)

if __name__ == "__main__":
    app.config['SECRET_KEY'] = 'super secret key'
    app.config['SESSION_TYPE'] = 'filesystem'

    sess.init_app(app)

    app.debug = True
    app.run()

Shouldn't session['userId] be 'saved out' each time I reload the page?
Comment: Are cookies enabled? A session id is saved in a cookie, tied to the filesystem storage.
Comment: @MartijnPieters Yeah... that was the issue. It's been a long few days with this, thanks for your help.
Answer: You need to have cookies enabled for sessions to work. Even Flask-Session cannot track a browser without those.
Flask-Session sets a cookie with a unique id, then later on finds your session data again by that cookie.

flask session not reloading


Transformation of 2D profile to 3D coordinates

Question: I am sure that answer for similar questions have being given more than one thousandth times, but correct answer that suits my needs I still haven't found.
Currently I am developing simple 3D app. My task is to draw beams in 3D space.
What is my input:

Profile of beam, which is represented with set of 2D coordinates.
For example, that profile is a triangle with coordinates A (-1, 0),
B (0, 1), C (1,0).
Two 3D points P (1,2,3) and D (4,5,6). This points represent axis of my beam.
edit: OZ axis of 2D profile must lay at the same plane as OZ axis of 3D space do.

What I need to get:
I need to get from set of 2D coordinates set of 3D coordinates. In other words, my profile coordinates need to be placed on the 3D plane, which is perpendicular to PD axis.
Please, help me to solve this problem.
Comment: You need more input to specify a unique solution. With what you have so far, the profile may be rotated around the axis, and there is no tellin which rotation is the one you want. I assume that you want to origin of the 2d plane to coincide with your 3d axis, but if not, you might have to clarify that point as well.
Comment: Really, origin of my profile is coincident to 3d axis.
Comment: You cannot have the plane of the profile be both perpendicular to the $PD$ axis and parallel to the $OZ$ axis unless $PD$ is parallel to $OZ$, which it is not in your example.
Comment: Sorry, I am again with mistake. ^^ Hope my new edit adds some clarity.
Answer: Let's see. You are looking for a local coordinate system such that the $OX$ axis of the plane is at the same time orthogonal to the $PD$ axis of extrusion and to the $OZ$ axis of the 3d coordinate system. You can obtain a vector which is parallel to two given vectors by computing the cross product, although you'll want to scale the resulting vector back to unit length.
$$ w_1 = \begin{pmatrix}0\\0\\1\end{pmatrix}\times(P-D) \qquad
v_1 = \frac{w_1}{\lVert w_1\rVert} $$
For the second coordinate direction, you want to be orthogonal to $v_1$ and again orthogonal to $PD$, so you could use
$$ w_2 = w_1\times(P-D) \qquad v_2 = \frac{w_2}{\lVert w_2\rVert} $$
Then any point $(x,y)$ in the profile plane will correspond to the line connecting $P+xv_1+yv_2$ to $D+xv_1+yv_2$.
Note that the above answer is only characterized by orthogonality requirements, but don't mention orientation. For each of the two cross products, you might change the order of operands, resulting in the opposite (i.e. negative) vector. I guess we could start analyzing which signs you obtain from the above computation, and which signs you actually want. But I suggest you simply give it a try, and flip the order if you find some sign to be different than what you want it to be.
Example
In your question, you provided some example coordinates. To make this example more illustrating, I'll use a different point in the plane, though, taken from your comment below.
$$ P = \begin{pmatrix}1\\2\\3\end{pmatrix} \qquad
D = \begin{pmatrix}4\\5\\6\end{pmatrix} \qquad
M = \begin{pmatrix}4\\5\end{pmatrix} $$
Then you get
$$ v_1=\frac{1}{\sqrt{18}}\begin{pmatrix}3\\-3\\0\end{pmatrix}=
\frac{1}{\sqrt2}\begin{pmatrix}1\\-1\\0\end{pmatrix} \qquad
v_2=\frac{1}{\sqrt{486}}\begin{pmatrix}9\\9\\-18\end{pmatrix}=
\frac{1}{\sqrt6}\begin{pmatrix}1\\1\\-2\end{pmatrix} \\[6ex]
P+4v_1+5v_2 =
\begin{pmatrix}1\\2\\3\end{pmatrix} +
\frac{4}{\sqrt2}\begin{pmatrix}1\\-1\\0\end{pmatrix} +
\frac{5}{\sqrt6}\begin{pmatrix}1\\1\\-2\end{pmatrix} =
\begin{pmatrix}
1 + \frac{4}{\sqrt2} + \frac{5}{\sqrt6} \\[2ex]
2 - \frac{4}{\sqrt2} + \frac{5}{\sqrt6} \\[2ex]
3 - \frac{10}{\sqrt6}
\end{pmatrix} $$
So that ugly vector would be one of the endpoints of your line.
Comment: I already [answered a similar question](http://stackoverflow.com/a/23212131/1468366) today.
Comment: Thanks for your answer. But I am little confused with notation
$$
P + xv1 + yv2
$$
How can I get the standard for me $(x,y,z)$ view?
Comment: @HnatiukDmitriy: Well, $v_1$ and $v_2$ are unit length vectors, with three components each, computed as outlined above. You simply scale them by $x$ resp. $y$, which means multiply each component by that factor. Then you add them using vector addition, which means simple component-wise addition.
Comment: You mean that I need to add coordinates of P to scaled $v1$? Can you provide simple sample. Assuming that $v1$ is $(1,2,3)$ and some point M on 2D profile is $(4,5)$ and P is $(7,8)$.
Comment: @HnatiukDmitriy: You need $v_1$ to have unit length, and you need $P$ to be a 3d point, so your example from the comment doesn't work that easily. But I've updated my post to include an example.
Comment: So that ugly vector would be one of the endpoints of your line.

This is vector, or 3D representation of 2D point $M$?
Comment: To me, that vector *is* the 3D representation of the 2D point $M$. Or, to be more precise, the representation associated with the endpoint $P$ of your line, you get another representation at $D$. I don't see your distinction.
Comment: Thanks a lot for a help. My rate is lower 15th so I can't vote for your answer :(


Documented/reproducible examples of successful real-world applications of econometric methods?

Question: This question might sound very broad, but here is what I am looking for. I know there are many excellent books about econometric methods, and many excellent expository articles about econometric techniques. There are even excellent reproducible examples of econometrics, as described in this CrossValidated question. In fact the examples in this question come very close to what I am looking for; the only thing missing in those examples is that they are only research reports, without any mention of how the results of the study fared in a real-world application.
What I am looking for are documented/reproducible examples of real-world applications of econometric theory that ideally have the following characteristics:

They should be reproducible, i.e. contain detailed description of (and pointers to) data, econometric techniques, and code. Ideally the code would be in the R language.
There should be detailed documentation showing that the technique succeeded in the real world, according to a well-quantified measure of success (e.g. "the technique helped increase revenues because it enabled improved forecasting of demand, and here are the numbers involved")

I am using the term econometric quite broadly here -- I mean any sort of data-mining, statistical data-analysis, predictiion, forecasting or machine-learning technique.
One immediate problem in finding such examples:  many successful applications of econometrics are done in a for-profit setting and are therefore proprietary, so if a technique worked well, it probably will not be published (this is especially true in the case of proprietary trading strategies), but I am nevertheless hoping there are published examples that have at least property (2) above if not both (1) and (2).
Comment: @pchalasani, Does LTCM count? ;)
Comment: What about discrete choice modeling? I'd think most people would consider DCM to be a branch of econometrics and the entire travel demand forecasting industry relies on DCM to generate inputs for their forecasting models...that may not be what you had in mind though.
Comment: @pchalasani, yes, how broadly *are* you interpreting the word "econometric"? Does, for example, Netflix's "Cinematch" system count (or any of the other successful "recommender" engines out there)?
Comment: Arnold Zellner isn't a bad name to look up.  larry bretthorst's phd thesis on spectral estimation is also good
Comment: @chase and @cardinal: yes Travel demand forecasting and Netflix Cinematch ( and other recommendation engines) would be great examples, if there were any documentation about how they work, or at least a description of the underlying techniques. Other examples could be from non-profit domains such as education or government.
Comment: @probabilistic logic: thanks for the refs I will look them up.
Answer: As mentioned in the comments, travel demand forecasts often use inputs from discrete choice models (multinomial logit, nested logit, mixed logit, etc) to assist in the development of behavioral mode choice or route assignment in their travel demand forecasts. DCM certainly has many applications outside travel demand forecasting, but it has been used in the transportation industry for 30+ years so there should be lots of good examples.
As for reproducible examples:

Biogeme is an open source piece of software that is optimized for estimating logit models. The website provides the data, code, and a paper write up describing their methods.
travelR is a project to make travel demand forecasts with R. There was a presentation at useR! 2010 about the project, abstract here and slides here. There is also a webinar coming up in a few weeks regarding R and travel demand forecasting that I'll find the link to and update here for those interested.
Transportation Review Board Conference has made a list of all papers available online this year. I don't have a specific paper to link to, but there are several committee's worth of papers regarding the application of choice models in the transportation context.
Comment: thanks for the details @Chase, DCM is an area I'm not familiar with, but looks interesting.
Comment: @pchalasani - for a more general overview of discrete choice modeling, [Kenneth Train's book](http://www.econ.berkeley.edu/books/choice2.html) is a very good place to start for both theory and practical applications. It's a fairly dense read, but well worth the effort if you are interested.


For $k$ a field, $k[x]$ is Noetherian but not Artinian?

Question: I have a question regarding some Commutative Algebra facts.
I am using the book A Course in Commutative Algebra by Gregor Kemper. On page 24 he states that if $k$ is a field, the polynomial ring $k[x]$ is Noetherian, and not Artinian. And in theorem 2.8 he states:
Let $R$ be a ring. Then the following statements are equivalent:
$R$ is Artinian $\Leftrightarrow$ $R$ is Noetherian and every prime ideal of $R$ is maximal.
Now I learned in my basic algebra courses that if $k$ is a field, then $k[x]$ is a principal ideal domain. And in a PID, every prime ideal is maximal. But this would be in contradiction with theorem 2.8, since $k[x]$ is Noetherian and PID and therefore $k[x]$ must be Artinian. What goes wrong here?
Comment: The ring $k[x]$ has a certain trivial prime ideal that is not maximal. Actually all PIDs have that trivial ideal.
Comment: You are correct that if $k$ is a field, that $k[x]$ is a PID, because $k[x]$ is a Euclidean domain, with the degree of the polynomial the Euclidean valuation, and every Euclidean domain is a principal ideal domain
Answer: In a PID, every nonzero prime ideal is maximal. But the condition for an artinian ring is that every prime ideal must be maximal, even the zero ideal (if it is prime). Therefore, the only PIDs that are artinian are fields.
Answer: $\cdots (x^3)\subseteq (x^2)\subseteq (x)$ is an infinite decreasing sequence of ideals.
Comment: $(x^3) \subset (x^2)$, because $(x^2)$ is an ideal of $k[x]$, so by the definition for every $r \in k[x], a \in (x^2), ra \in (x^2)$. In particular, with $r = x$ and $a = x^2$, $x^3 \in (x^2)$.
Comment: Is $\left(x^3\right)\subseteq\left(x^2\right)$? Did you mean $\left(x^4\right)\subseteq\left(x^2\right)$?


Why does VGG16 double number of features after each maxpooling layer?

Question: VGG16 is a Convolutional Neural Network architecture, presented in the paper Very Deep Convolutional Networks for Large-Scale Image Recognition (ILSVRC-2014 conference presentation here). As explained in the paper,

The width of convolutional layers (the number of channels) is rather small, starting from 64 in the first layer and then increasing by a factor of 2 after each max-pooling layer, until it reaches 512.

Why is the number of channels doubled after each convolutional layer?
Jeremy Howard in the fast.ai course says it is not to lose information. Is it important to maintain the same number of weights on every layer for a convolutional neural network? Can it be beneficial to lose information?
Comment: Please add the link to the lecture in which Jeremy Howard says that.
Answer: You should really ask in the course forum :) or contact Jeremy on Twitter, he's a great guy. Having said that, the idea is this: subsampling, aka pooling (max pooling, mean pooling, etc.: currently max pooling is the most common choice in CNNs) has three main advantages:

it makes your net more robust to noise: if you alter slightly each neighborhood in your input layer, then the mean of each neighborhood won't change a lot (the smoothing effect of the sample mean). The max doesn't have this smoothing effect, however since it's the largest activation value, the relative variation due to noise is (on average) smaller than for other pixels.
it introduces some level of translation invariance. By reducing the number of features in the output layer, if you move slightly the input image, chances are the output of the subsampling layer won't change, or it will change less. See here for a nice picture
also, by reducing the number of features, the computational effort in training and predicting is reduced. Also overfitting becomes less likely.

However, not everyone agrees with point 3. In the famous Alexnet paper, which can be considered as the "rebirth" of CNNs, the authors used overlapping neighborhoods (i.e., strides along x and y smaller than the extension of the subsampling neighborhood along x and y respectively) in order to get the same number of features for the input and the output of the subsampling layer. This makes the model more flexible, which is what Jeremy was hinting at. You get a more flexible model, at the risk of more overfitting - but you can use other Deep Learning tools to fight overfitting. It's really a design choice - you'll typically need validation data sets to try different architectures and see what works best.
EDIT: It just occured to me that I have misunderstood what you were asking for. VGG16, unlike Alexnet, uses nonoverlapping max pooling (see chapter 2.1 of the paper I linked, right at the end of the first paragraph). Thus the size of the channels does reduce by 50% after each pooling layer. This is compensated by the doubling of the width of the convolutional layers:

actually, it doesn't happen always - after the penultimate maxpool, the width remains 512, the same as before pooling. Again, this is a design choice: it's not set in stone, as confirmed by the fact that they don't follow this rule for the last convolutional layer. However, it's by far the most common design choice: for example, both LeNet and Alexnet follow this rule, even though LeNet uses nonoverlapping pooling (the size of each channel is halved, as for VGG16), while Alexnet uses overlapping pooling. The idea is simple - you introduce maxpooling to add robustness to noise and to help making the CNN translation equivariant, as I said before. However, you also don't want to throw away information contained in the image, together with the noise. To do that, for each convolutional layer you double the number of channels.  This means that you have twice as many "high level features", so to speak, even if each of them contains half as many pixels. If your input image activates one of this high level features, their activation will be passed to following layers.
Granted, this added flexibility adds a risk of overfitting, which they combat with the usual techniques (see chapter 3.1): $L_2$ regularization and dropout for the last two layers, learning rate decay for the whole net.
Answer: If you think that first convolutional layer extracts simple features, like lines, than the next convolutional layer has to combine these lines into more complected structure. Basically, each channel in the next layer responsible for the combination of different lines into more complicated structure. Since structure getting more complicated there are getting more features that you can construct from simple lines.
If you think of lego-building classifier. First layer learns basic building lego-blocks, the second one looks for what things you can construct using these blocks and clearly there are way more things that you can build from basic building blocks.
Another analogy is a digital number classifier. You have 7 LEDs in one matrix, which means that you can learn using first layer all 7 lines (or maybe 2 if you learn that there is one horizontal and one vertical line, just in different places).

Using just 7 features you can construct 10 different digits. In addition to it, you can construct letters, like L, A, H and so on. So in the next convolutional layer, you should have more than 7 layers in order to be able to learn different letters and digits.
These are toy-examples, but the same intuition you can extend to more realistic problems that large convolutional neural networks are trying to solve
Answer: If somebody is wondering how technically maxpool layer can double the number of features in VGG architecture, I could answer that in the essence it is just Conv2d layer which doubles number of features right after maxpool layer. I checked that in torchvision repository. Some visualizations of VGG architecture are misleading. They make you think that maxpool layers double the number of features.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stats.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://stats.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/352013)


Find the maximum and minimum of a function (involving an trigonometric integral)

Question:
Question: How can I find the maximum and minimum of this function, for a value of $\text{n}$?

$$\text{G}_\text{sc}\left(\text{n}\right)=\alpha\cdot\left(1+\epsilon\cos\left(\theta\right)\right)^2\tag1$$
Where $\alpha\space\wedge\space\epsilon\in\mathbb{R}^+$
And, for $\theta$ we know that:
$$\frac{\text{n}}{\text{A}}\int_0^{2\pi}\frac{1}{\left(1+\epsilon\cos\left(x\right)\right)^2}\space\text{d}x=\int_0^\theta\frac{1}{\left(1+\epsilon\cos\left(x\right)\right)^2}\space\text{d}x\space\Longleftrightarrow\space\theta\left(\text{n}\right)=\dots\tag2$$
Where $\text{A}\in\mathbb{R}$ and $0<\text{n}\le\text{A}$ and $\color{red}{\text{when you solve}}$ $\color{red}{\theta}$ $\color{red}{\text{we will get that}}$ $\color{red}{\theta}$ $\color{red}{\text{a function is of}}$ $\color{red}{\text{n}}$

My work:
In order to find the minumum and maximum:
$$\text{G}'_\text{sc}\left(\text{n}\right)=\frac{\text{d}}{\text{d}\text{n}}\left(\text{G}_\text{sc}\left(\text{n}\right)\right)=0\tag3$$
But I do not understand how to proceed.
Comment: where is $n$ in the rhs of (1)?
Comment: @Guangliang You have to read further, because $\theta$ is a function of $\text{n}$. See the red part!!
Comment: Is $n$ restricted to be an integer?
Comment: @Dr.MV No, $\text{n}$ does not have to be an integer
Answer: Let $$I(\theta) = \int_0^\theta \frac1{(1+\epsilon\cos x)^2}\,dx,$$ then$$\frac{dn}{d\theta} = \frac{A}{I(2\pi)(1+\epsilon\cos\theta)^2}.$$ The first order condition of $G' = 0$ becomes $$0 = \frac{dG}{dn} = \frac{dG}{d\theta}\frac{d\theta}{dn} = -2\alpha\epsilon \frac{I(2\pi)}{A}\sin\theta(1+\epsilon\cos\theta)^3.$$  The zeros occurs at $\sin\theta = 0$ or $(1+\epsilon\cos\theta) = 0$.
Comment: Once you solved $dG/dn = 0$ for $\theta$, then $$n = \frac{A}{I(2\pi)}I(\theta).$$  Do you need closed form solutions or will numerical solutions work?
Comment: One obvious solution is $\theta = 2\pi$, which leads to $n  = A$.
Comment: From your Eq. (2),  the lhs is $\frac{n}{A}I(2\pi)$, the rhs is $I(\theta)$.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/55020/discussion-between-guangliang-and-jan-eerland).


div contents scrolls back up when using overflow: auto in IE 10

Question: I am trying to add multiple input elements and other data inside a div and using overflow:auto for that div (using jquery to show/hide that div)
It works fine in Firefox browser but in IE (10) the scroll bar does come when the elements are more than the height of that div, but when the user uses the scroll bar to scroll down, and then if moves the mouse over to any of the input element or other element in that div to enter data, the div content scrolls back up to the top. So the users cannot access the elements/contents of that div which are below the height of that div
here is the link for the fiddle where you can see the code
http://jsfiddle.net/euMJn/1/
code of that html page  (as code is required with the jsfiddle link)
Any help or direction would be appreciated
Thank you for you help and time
----code starts below----

<title>Div Scroll</title>

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css"
        type="text/css" rel="Stylesheet" />

<button id='trigger' style="background-color:yellow"> Mouse over here</button>

Text above input01

        Input 1:  <input name='input01' id='inp01' type='text' size='25' value='input' >

Text above input02

        Input 2:  <input name='input02' id='inp02' type='text' size='25' value='input' >

Text above input03

        Input 3:  <input name='input03' id='inp03' type='text' size='25' value='input' >

Text above input04

        Input 4:  <input name='input04' id='inp04' type='text' size='25' value='input' >

Text above input05

        Input 5:  <input name='input05' id='inp05' type='text' size='25' value='input' >

Text above input06

        Input 6:  <input name='input06' id='inp06' type='text' size='25' value='input' >

Text above input07

        Input 7:  <input name='input06' id='inp07' type='text' size='25' value='input' >

Text above input08

        Input 8:  <input name='input06' id='inp08' type='text' size='25' value='input' >

Text above input09

        Input 9:  <input name='input06' id='inp09' type='text' size='25' value='input' >

Text above input10

        Input 10:  <input name='input06' id='inp10' type='text' size='25' value='input' >

Answer: Instead of using mouseout, use mouseleave.
$('#outer').mouseleave(function () {
    $(this).hide();
});

New fiddle here.
If you take a look at jQuery.mouseleave docs you will notice this line.

mouseout fires when the pointer moves out of child element as well, while mouseleave fires only when the pointer moves out of the bound element.

Basically IE decides to reset the visibility whenever you hover over a child element, thus resetting the visibility of the outer div. Other browsers seem to be smart enough that if it's already visible, they don't touch it.
Comment: It worked like a charm, thank you so much for not only giving the solution but also for explaining why it was doing it and why the new fix will fix it. Thank you once again for your help and time


Linear dependency and eigenvalues

Question: Statement:
Let $V$ be a vectorial space, $T: V  \to V$ a linear operator, u is a eigenvector of T associated to eigenvalue $\lambda$ and v a eigenvector T associated to eigenvalue $\alpha$ .
a) If $\lambda \neq \alpha$, then u and v can be linearly dependent.
My question is: Why is this not true?
What I tried to do:
My approach to this question was:
There's a matrix A associated with T so that Au = $\lambda$u and Av = $\alpha$v. Also, for some $\beta$, it's true that $\beta$v = u.
So I tried to do some math with those, but could not get anywhere...
Any hints on how to solve this?
Thank you!
Comment: Distinct eigenvalues means distinct eigenspaces, so if one vector is in the complement of the eigenspace of the other vector's eigenvalue, it must be linearly independent of the vectors in that space. Why do you think this is false?
Answer: Fairly trivial. Assuming $u \neq 0, v \neq 0$:
$Au = \lambda u \space \mathrm {and}\space Av = \alpha v \space \mathrm {and}\space u=\beta v \implies \lambda u = A(\beta v) = \beta Av = \beta \alpha v = \alpha (\beta v) = \alpha u \implies \lambda = \alpha$
$\beta$ cannot be null because it $\beta = 0$ and $u=\beta v \implies u =0$

Linear dependency and eigenvalues


Can anyone explain how to differentiate the Lambert W function?

Question: I'm interested in the differentiation of the Lambert W function $y = xe^x$.
I am unable to understand how to proceed for it.
Answer: The Lambert W-function is not $y=x e^x$, it is the inverse function of $xe^x$.
Since:
$$e^{W(x)}W(x) = x \tag{1}$$
by differentiating both sides of $(1)$ with respect to $x$ we get:
$$ W'(x)(1+W(x))e^{W(x)} = 1 \tag{2}$$
or:
$$ W'(x)(1+W(x)) = \frac{W(x)}{x}\tag{3}$$
hence:
$$ W'(x) = \frac{W(x)}{x(1+W(x))}.\tag{4}$$
Answer: Hint: Use the product rule for differentiation.


How to prove that $\frac{\cosh (2 \pi x)}{x^2}$ is convex?

Question: I want to prove that this function $$f(x)=\frac{\cosh (2 \pi  x)}{x^2}$$ is convex $(0<x<10)$, and find its minimum. The first and second derivatives are a follows
$$f'(x)=\frac{2 (\pi  x \sinh (2 \pi  x)-\cosh (2 \pi  x))}{x^3}$$
$$f''(x)=\frac{\left(4 \pi ^2 x^2+6\right) \cosh (2 \pi  x)-8 \pi  x \sinh (2 \pi  x)}{x^4}$$ How to prove that $f''$ is positive?
Comment: **Hint**: Look at the graphs of $\mbox{cosh}$ and $\mbox{sinh}$ for positive inputs.
Comment: Have you found any inflection points?
Answer: I think my hint might've been a little too vague so here's a direct method.
Since $x^4$ is always positive then we just have to show that the numerator is positive. Using the definitions $\mbox{cosh}(x) = \frac{e^x + e^{-x}}{2}$ and $\mbox{sinh}(x) = \frac{e^x - e^{-x}}{2}$ then we have
$$(4 \pi ^2 x^2+6) \cosh (2 \pi  x)-8 \pi  x \sinh (2 \pi  x)=(4 \pi ^2 x^2+6)\frac{e^{2\pi x} + e^{-2\pi x}}{2} - 8\pi x\frac{e^{2\pi x} - e^{-2\pi x}}{2}$$
now simplifying and ignoring the $1/2$ factor because it's not important then we just have to show that
$$(4\pi^2 x^2 - 8\pi x + 6)e^{2\pi x} + (4\pi^2 x^2 + 8\pi x + 6)e^{-2\pi x}$$
is positive. Now, the quadratic $4\pi^2 x^2 - 8\pi x + 6$ is positive at $x=0$, and its determinant is negative. Therefore it has no real roots, and so it is positive for all values of $x$. And since  the coefficient of $e^{-2\pi x}$ is positive in the range $0<x<10$ then the entire expression is positive in the range $0<x<10$. And so $f^{\prime\prime}$ is positive for $0<x<10$.
Comment: The expansion of the second derivative is amazing. Cheers :-)
Comment: @SeraPhim  I am a new contributor and, I could not vote your answer. Thanks.
Comment: @Laura that's quite alright, glad I could help.
Answer: For starting the problem, let us make life simpler
$$f(x)=\frac{\cosh (2 \pi  x)}{x^2}$$ Let $2\pi x=t$ and consider the problem of
$$g(t)=\frac{\cosh (t)}{t^2}$$ for which $$g'(t)=\frac{t \sinh (t)-2 \cosh (t)}{t^3}\qquad \text{and} \qquad g''(t)=\frac{\left(t^2+6\right) \cosh (t)-4 t \sinh (t)}{t^4}$$ Considering the numerator of the first derivative, we have
$$y_1=t \sinh (t)-2 \cosh (t)=-2+2\sum_{n=2}^\infty \frac{ (n-1)}{\Gamma (2 n+1)}t^{2n}$$ In the summation, all coefficienst are positive and then $y_1$   cancels only once. Considering the first terms as a truncated Taylor expansion, using series reversion we have
$$t=z-\frac{z^3}{60}+\frac{9 z^5}{11200}-\frac{z^7}{19200}+\frac{96463
   z^9}{24837120000}+O\left(z^{11}\right) \qquad \text{where} \qquad z=\sqrt[4]{12 (y_1+2)}$$ Making $y_1=0$, that is to say $z=\sqrt{2 \sqrt{6}}$, this gives for the solution the approximate solution
$$t_*=\frac{44048063 }{21560000}\sqrt[4]{\frac{3}{2}}-\frac{43}{100\, \sqrt[4]{24}}\approx 2.06673$$ Since we face an alternating series, this gives a slightly overestimate of the solution (effectively, using Newton method,
the "exact" solution is  $t=2.06534$.
Doing the same with the numerator of the second derivative gives
$$y_2=\left(t^2+6\right) \cosh (t)-4 t \sinh (t)=6+\sum_{n=2}^\infty \frac{2 n^2-5n+3}{n\,\Gamma (2 n)}t^{2n}$$ All coefficients are positive; then $g''(t)$ is always positive.
Back to $x$ and $f(x)$, the minimum occurs at $x_*=\frac {t_*}{2 \pi} \approx 0.328930\sim \frac 1 \pi$. Expanding as a Taylor series, we then have
$$f(x)=\pi ^2 \cosh (2)-\frac{2 \pi ^3 }{e^2}\left(x-\frac{1}{\pi }\right)+\pi ^4 \left(\frac{4}{e^2}+\cosh (2)\right)\left(x-\frac{1}{\pi }\right)^2
    +O\left(\left(x-\frac{1}{\pi }\right)^3\right)$$ which gives as a refinement
$$x_*=\frac 1 \pi \left(1+\frac{2}{9+e^4} \right)\approx 0.328320$$
$$f(x_*)=\frac{\left(5+10 e^4+e^8\right) \pi ^2}{2 e^2 \left(9+e^4\right)}\approx 37.0894$$ while a full numerical optimization would give $x_*=0.328709$ and $f(x_*)=37.0883$.
Comment: I am a new contributor and, I could not vote your answer. Thanks.
Answer: Convexity of $f(x)$ is easy to prove from the expansion:
$$ f(x) = \frac{1}{x^2} \sum_{n=0}^{\infty} \frac{(2\pi x)^{2n}}{(2n)!} = \sum_{n=0}^{\infty} \frac{(2\pi)^{2n}}{(2n)!} x^{2n-2}. $$
Since $x \mapsto x^{2n-2}$ is convex on $(0, \infty)$ for each $n \in \{0,1,2,\dots\}$ and the coefficients are positive, $f(x)$ must be also convex.
Comment: Thanks. But there is a counterexample n=1. It is not convex in that case,
Comment: @Laura, When $n=1$, the term $x^{2n-2}=1$ is still convex (although it is not strictly convex). If what you want is the strict convexity, still there is no issue because the $n=1$ term will only contribute to a constant term which is totally harmless for strict convexity.
Comment: Do you mean that a constant function $f(x)=2\pi ^2$ can be convex? But the second derivative is zero. As far as I know, it is neither concave nor convex.
Comment: @Laura, A function $f$ defined on interval $I$ is called [convex](https://en.wikipedia.org/wiki/Convex_function) if it satisfies $$ f(\lambda x+(1-\lambda)y)\leq \lambda f(x)+(1-\lambda)f(y)$$ for all $x, y \in I$ and $0 \leq \lambda \leq 1$, i.e., its graph on the subinterval $[x, y]$ always lies on or below the line segment joining $(x,f(x))$ and $(y,f(y))$. Constant functions satisfy this property perfectly, and they are the only examples which are both convex and concave.
Comment: Thank you so much for explanation.


Can I migrate to database created without migration in Entity framework?

Question: I had created a desktop application which uses SQL CE 4.0 and Entity framework with Code First mode. So, Initially I had installed application on a system, it worked fine.
Now I added few properties to model class, so for this purpose I enabled migrations using Enable-Migrations and added new migration using Add-Migration "MyMigration". This was also successfull and I was able to install new version and upgrade database without any issue.
But now when I install this setup on a system with no existing database then it fails, so after studying I realized that I need to add Initial Migration So, I revoked changes in model and also deleted my SQLCE database file, added initial migration, then Update-Database. So if I try to Update-Database using old-database which was created without enabling migrations then it fails, it tries to apply initial migration to database which it shouldn't according to me.
Now if I delete old-database file and then Update-Database then new db is created and then once again added my changes to model and added expected migration.
So after this, turnaround I am able to install my application on blank system but it fails on a system with old database i.e. it doesn't upgrade database.
It tries to apply Initial-Migration also, i.e. creating all the tables once again and fails saying that, The table already exists which isn't expected.
Comment: Try using the command update-database -verbose ... after failing scroll up and you'll see which table is causing the issue
Comment: Update-Database works but, when I build setup file and deploy on any of the client system, it tries to apply InitialCreate migration and recreate all tables, which gives error as **XYZ table already exists**
Answer: The thing is that it checks a table called Migrations, where I think it get information of the current squema and changes. If you make a lof of changes of the DB without using EF, somehow you'll get to a point when a lot of clonflicts would happen.
You can use fluent migrations to do everything yourself and have more control of the changes and the rollbacks
Example:
 [Migration(201610250659)]
public class _201610250659_AddedMinimumValue_Prices : Migration
{
    public override void Up()
    {
        Alter.Table("Prices")
            .AddColumn("MinimunValue").AsInt32().NotNullable().WithDefaultValue(1);
    }

    public override void Down()
    {
        Delete.Column("MinimunValue")
            .FromTable("Prices");
    }
}

Answer: What you need is
update-database

this will update the database accordingly. Just remember everytime you add-migration you need to update-database, and when you install the system somewhere else, all you need is to do a update-database to get the older database on par with entity framework.
Comment: I am deploying my application through msi installer created with help of InstallShield, how can I update-database in that case?
Comment: I've never installed in with msi installer before, but anyhow, entity framewok shouldnt try initial-migration everytime, it should only do it once. you do add-migration -> update-database and the database should have the migrationhistory table to update properly, atleast that is the way entity framework should work
Comment: Please go through my question once again, hope you understand my problem. I am installing my setup on 100 different machines.
Comment: Yes how are you doing add-migration? You said you added new migration using add-migration so you are definitely typing this somewhere right? why can't you run update-database after add-migration?
Comment: Does your database have a migrations table? When you install from scratch using update-database, how many rows are in migrations table? You should get one row for each add-migration you've done. Now i suspect old database doesnt upgrade because they have different rows in migrations table, for example, new database could have something like init, first-update etc, but your old database could have initial as the first row which is different from your application and it fails. I suggest you do a clean database install on each machine using update-database only, don't do any initial-database.
Comment: Its really hard to tell because it could be anything
Comment: And when you update your model and add-migration, just update-database on new machines see it works fine now.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/138197/discussion-between-aniket-bhansali-and-mindless).
Answer: you need to check if into initial scripts, if table already exist or not. Its not EF issue, even if your try to simply run create database scripts with table definition without checking existing one, it will fail.
For Example,
I don't have any database installed into my machine and I'm having script for create new with some table into it..
so this is script for creating table
    USE [TestStudent]
GO
/****** Object:  Table [dbo].[EmployeeInformation]    Script Date: 18-03-2017 19:12:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EmployeeInformation](
    [Id] [int] NOT NULL,
    [Name] [nvarchar](50) NULL,
    [LastName] [nvarchar](50) NULL,
    [Designation] [nvarchar](50) NULL,
 CONSTRAINT [PK_EmployeeInformation] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[sample]    Script Date: 18-03-2017 19:12:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[sample](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [TableId] [int] NULL,
 CONSTRAINT [PK_sample] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Notice that I'm just creating the tables not checking for object existence, now if I run this on new machine with blank database it will run without error..

Now, I try to run same script on existing database with existing objects may be for updating some tables like in your case but here's the trick, your update script will be at the bottom of this... so it will first try to create the tables and if existed it will throw you error..

so you need to check the object existence before you create tables, like in this script...
    USE [TestStudent]
GO
/****** Object:  Table [dbo].[EmployeeInformation]    Script Date: 18-03-2017 19:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EmployeeInformation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[EmployeeInformation](
    [Id] [int] NOT NULL,
    [Name] [nvarchar](50) NULL,
    [LastName] [nvarchar](50) NULL,
    [Designation] [nvarchar](50) NULL,
 CONSTRAINT [PK_EmployeeInformation] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[sample]    Script Date: 18-03-2017 19:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sample]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[sample](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [TableId] [int] NULL,
 CONSTRAINT [PK_sample] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO

so when you try to run this, it will skip the already existing objects that are in table will proceed to your update scripts...

hope this helps...
Answer: OK, so if you have, say, 2 migrations: Initial and MyMigration and now you have an old database that has the changes represented by the first migration, but not the second and it keeps trying to apply the unneeded first migration - then you can resolve it this way:
1) Generate a complete migration script (BTW, this can be used to create a blank database of your model):
Update-Database -Script -SourceMigration: $InitialDatabase

2) The code at the top of this script will check for the existance of __MigrationHistory and create it if it is missing.
3A) Next, it will check for each migration with code like below. Since your database already has these you should comment those lines out.
IF @CurrentMigration < '201702231958592_Initial'
BEGIN
     -- objects already exist, but EF doesn't know this
     -- CREATE TABLE, etc.
END

3B) Entity framework will insert a record into __MigrationHistory so it knows this migration has been applied. Do not comment this line out! (The long hex string is a representation of your model).
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'201702231958592_Initial', N'MyApp.Data.Migrations.Configuration',  0x1F8B08000000

4) Steps 3A and 3B will be repeated for each migration, so leave them in there if they have not been applied. Comment out the object changes if they do.
Moving forward if you haven't messed with migrations EF will be smart enough to apply the changes to various deployments in different states of applied migrations.
As to your installer issue, you could either call this script via ADO.NET or you could use DbMigrator to do migrations in code.