Hypothesis Testing: Different p-values from different test statistics

Question: this is a question that has been lingering in my mind for a very long time, but came up again in practice and I thought I'd reach out and ask about it.
The situation I'm interested in is when you are performing a Null Hypothesis Test and you can generate multiple test statistics with your data.  You know, both analytically and confirmed via simulation, the distribution of these different test statistics.  When you compute p-values using your actual observed data against these distributions, you get different results.  Similar results, it must be said, but different.  Different enough that were one to hew to the traditional critical values to reject a null hypothesis, one might make different decisions for the different test statistics.
A little bit more concretely, consider the Likelihood Ratio Test in addition to whatever usual test statistic you are going to look at.  For example, a t-statistic when comparing sample means. -2 times the natural log of the Likelihood Ratio is going to follow a Chi-Square(1) distribution, which can be confirmed via simulation or analytically.  The t-statistic is obviously going to follow a t-distribution.  With your actual observed data, you compute p-values using both test statistics and get different results.  Which one should be used?
More concretely, I was doing homework question 8.6 in Casella and Berger.  The problem setup there is X = sum of n exponential(theta) variables, and Y = sum of m exponential(mu) variables.  The null hypothesis is that the rates theta and mu are the same.  Sums of exponentials are gamma random variables, and the ratio X / (X + Y) of gamma random variables is a beta(n,m) random variable (I have confirmed this analytically and via simulation).  So I can use a beta(n,m) to generate p-values based on observed data.  I can also generate the likelihood ratio, which follows a chi-square(1) distribution, which I have confirmed via simulation.  The two test statistics lead to different p-values, and they are different enough that I felt compelled to reach out and ask this community for advice.
To summarize my question, when different test statistics can be used to generate p-values, which test statistic and p-value should be chosen?
Answer: Depending on what you know and one the assumptions you are willing to make about the population from which your sample was taken, there may be many different ways to test whether
$H_0: \mu=\mu_0$ against $H_a: \mu=\mu_a.$
Because the two tests may use different methods or distributions their powers may differ. That is, one may be more likely to detect the difference $\delta = 1$ between $\mu_0=1$ and $\mu_a = 0.$
If you have a symmetrical sample you might feel
comfortable assuming it its population is normal and using a t test. But for another symmetrical sample, you may use a nonparametric one-sample
Wilcoxon test, based on ranks of the data.
<code> set.seed(2022)
 x = rnorm(25, 0, 3)

 t.test(x, mu = 1)

         One Sample t-test

 data:  x
 t = -2.2657, df = 24, p-value = 0.03277
alternative hypothesis: true mean is not equal to 1
95 percent confidence interval:
 -1.5620832  0.8805949
sample estimates:
  mean of x
  -0.3407441

wilcox.test(x, mu = 1)

        Wilcoxon signed rank test

 data:  x
 V = 93, p-value = 0.06263
 alternative hypothesis: true location is not equal to 1
</code>
The t test is significant at the 5% level because
its P-value is below $0.05,$ but the Wilcoxon test
is not significant at the 5% level. One test detects
the difference between $\mu = 1$ and $\mu = 0;$ the other does not. Nothing is "wrong" with either test. They are based on different assumptions and use test statistics with different distributions, so it is not surprising that they give different "answers."
The following simulations in R show that the t test has somewhat better power in this situation than does the Wilcoxon test.
<code> set.seed(630)
 pv.t = replicate(10^5, t.test(rnorm(25,0,3), mu = 1)$p.val)
 mean(pv.t <= 0.05)
 [1] 0.361          # Aprx power t test 36%

 pv.w = replicate(10^5, wilcox.test(rnorm(25,0,3), mu = 1)$p.val)
 mean(pv.w <= 0.05)
 [1] 0.34359b       # Aprx power Wilcoxon SR test 34%
</code>
Comment: Thanks for the reply and you bring up a few good insights about power and symmetry that I will think about.  But instead of comparing a parametric and non-parametric test, how about the case where you are comparing two parametric tests where you know for certain what the distributions are?  For example, X=sum of n exponentials and Y = sum of m exponentials.  One test statistic is X+Y which will be Gamma(n+m, rate).  Another test statistic is X / (X+Y) which is Beta(n,m). Or Likelihood Ratio (too long to type out) which is ChiSq(1).  None of these are assumptions, so which is to be prefered?
Comment: There are several such cases in which more than one CI may be optimal, depending on assumptions made about the population. // If you are especially interested in a specific case, maybe that is a new Question. // [Here](https://stats.stackexchange.com/questions/565036/chi-squared-confidence-interval-for-variance/565059#565059) is a link in which two of several CIs might reasonably be chosen.
Comment: Also, [possibly relevant](https://stats.stackexchange.com/questions/564486/estimating-variance-given-the-mean/564507#564507)


Improvising Chord Progressions

Question: Usually when playing along with jazz standards we check out the changes before we start, the changes define the song.
I was wondering if it is possible to not have a predetermined set of changes before the song starts, but to be able to improvise them as you are playing.

Related questions, with answers:

How to figure out piano chord progressions while playing?
Does improvisation usually start with a chord progression?
Comment: I've been there and done it. It takes both players to listen well, and be able to move together. Sadly, no recordings, but it can, and does happen, and it's magic when it does. No need to even have a key in mind, it's uncanny, but wonderful when it happens. Not very often though...
Comment: Right, @jdjazz isn't the concept of free jazz based on improvising every aspect of music?
Comment: Free jazz crossed my mind too. I didn't include it because I think it's more accurate to say that free jazz doesn't have defined chords. When playing free jazz, I think the goal usually isn't to improvise agreed-upon chords that the entire band plays together at the same time. The structure of everyone playing the same set of chords isn't usually there. That's different from playing outside the changes, which tends to follow a more predictable pattern (e.g., a half-step up, etc.) and often involves staying on a single "new" chord for a longer period of time (allowing the band to catch up).
Comment: Phish improvises lots of music and changes, but you don't have to agree ahead of time to take turns. You just have to know each other and listen carefully. Hand signals and/or signal riffs don't hurt either.
Comment: I'm voting to reopen as this now asks about a very specific technique in jazz. It most often occurs in two contexts: when the soloist "plays outside" the chord changes, and the rest of the band follows. Some great examples of where to hear that are in the classic Coltrane quartet, in the Joshua Redman quartet from the 90s (check out Brad Mehldau's solos and listen for how bassist Christian McBride follows Brad away from the chord changes).
Answer: First of all the changes do not define the song.  Any tune from the Real Book, or other sources, can be harmonized by several different sets of chords, you have many options for this.  The Head defines the tune.  If you look at a few dozen tunes from the Real Book at random you will likely find a few common sets of changes.  If all anyone did was follow the changes then every tune would sound the same and solos would be boring.  Improvisation is variation on a theme.  The Head is the theme and that is where you get the most bang for the buck.
That all being said, in western music changes naturally arise from the melody and application of a few simple rules.  If you really understand the rules of harmony theory you can harmonize as you go.  Piano players and guitarists do this all the time. With the melody in front of you you definitely can "improvise" changes.  Given some knowledge of the circle progression, cycle extensions, and substitutions you could get some pretty intricate harmonization of even a simple melody.  Being able to do this takes a lot of practice in my experience but it is possible.
If this is not what you were asking about, please comment and I'll edit the answer.
Comment: At the time of the post, I didn't quite understand that the changes didn't define the song, I get that we can harmonize a melody with different sets of chords now. What I wonder now is if we have a guitar player and a piano player how can they both improvise the harmony together without clashing? With respect to my original question, what I was trying to ask is if it's possible for a melody to be improvised and simultaneously have someone harmonize it (improvising chords for it).
Comment: That would likely lead to a mess.  One person has to lead and the others follow.  With NO idea to start with cohesion is not likely or easy.  At the very least you could pick a key and see what happens but even then you would likely run into situations where the two player move in directions that "clash".  You cannot predict what you haven't heard, or seen.  One possibility is voice leading.  If both players are equally well developed and one moves the other can kind of predict what the next move is likely to be.  There has to be some template, 16 bars, 12 bars, where should the resolution go.
Comment: etc.  (I ran out of characters).
Comment: Let's say you have a drummer, saxophone, guitar and piano. In this situation if everyone knows the standard they're going to play and the guitarist and pianist just play the stock chords, everything will go smoothly and sound predictable, if we just give them the melody and let them harmonize it might work out, if we don't give them any lead sheet at all and say "play" then it's a train wreck. How do we strike the perfect balance ?
Comment: 1. They will not play stock chords.  Why would they.  If they know the standard they have many compatible options.  Substitutions usually work well together.
Comment: 2. Perhaps there us no balance.  If you're assuming that this is possible and insisting that a formula be found, your assumption might be wrong.

Improvising Chord Progressions


Add new rows to a pandas dataframe

Question: I have two dataframes df1 and df2 that that were computed from the same source, but with different methods, thus most of the values are same, with some differences. Now, I want to update df1 based on values in df2.
For example:
df1 = pd.DataFrame({'name':['john','deb','john','deb'], 'col1':[490,500,425,678], 'col2':[456,625,578,789],'col3':['TN','OK','OK','NY']})
 name col1 col2 col3
 john  490  456  TN
 deb   500  625  OK
 john  425  578  OK
 deb   678  789  NY

df2 = pd.DataFrame({'name':['deb','john','deb','john','deb'], 'col1':[400,490,500,425,678], 'col2':[225,456,625,578,789],'col3':['TN','TN','OK','OK','NY']})
 name col1 col2 col3
  deb  400  225  TN
 john  490  456  TN
  deb  500  625  OK
 john  425  578  OK
 deb   678  789  NY

So, in this case .append should append only the first row from df2 to df1. So, only if there is a new row in df2 that is not present in df1 (based on name and col3) that column will be added/updated, else it wont be.
This almost seems like something that concat should do.
Comment: *Why* should it only append that row? How, specifically, do you decide which rows you want?
Comment: Sorry, I forgot to insert a row in df2. Hope this is much clear. `col3` is a category variable, so is there is new `name` in the category, you would append.
Comment: To put it another way: you want to concatenate the two frames and then drop duplicates?   Or if there's a new row involving Deb from Oklahoma -- say `deb 1000 2000 OK` -- do you want the original `deb 500 625 OK` row to be removed?
Comment: Simply put, i just want to add a row that is unique (based on the two column). One caveat with dropping duplicate is that how do i make sure i keep the value from the df1 only?
Answer: There are two ways of acheiving your result.

Concat both dataframes, then drop duplicates
Using an outer join/merge, then drop duplicates

I will show you both.
Concat then Drop
This should be more CPU friendly
df3 = pd.concat([df1,df2])
df3.drop_duplicates(subset=['name', 'col3'], inplace=True, keep='last')

This method is possibly more memory intensive than an outer join because at one point you are holding df1, df2 and the result of the concatination of both [df1, df2] (df3) in memory.
Outer join then Drop
This should be more memory friendly.
df3 = df1.merge(df2, on=list(df1), how='outer')
df3.drop_duplicates(subset=['name', 'col3'], inplace=True, keep='last')

Doing an outer join will make sure you get all entries from both dataframes, but df3 will be smaller than in the case where we use concat.
Version 0.15 and older note:
The keyword keep='last' used to be take_last=True

Add new rows to a pandas dataframe


superfish settings not visible

Question: I'm having a strange problem with the Superfish module. If I go to blocks > superfish menu > configure, I only see Pages, Pages Exclude, and Content Types. There's no other settings. I was somehow able to put the main menu into the Superfish 1 menu, but none of the settings are visible. I have the superfish library in /sites/all/libraries, and the superfish module in /sites/all/modules.
I'm using Navin, a subtheme of Omega.
Thanks for the help
Comment: Would the mongodb module have anything to do with it? I know it affects the block settings
Comment: Any errors showing up in your error logs you can report? Have you flushed cache?
Answer: The problem was that the mongodb block module disabled the normal block module. When I re enabled the block module, and disabled the mongodb block module, it worked fine.

superfish settings not visible


Comparing two groups with many zeros

Question: I am comparing the difference in time-activity-budgets of two populations of seabirds, those in the presence of ship disturbance and those not in the presence of ship disturbance. Focal animals were chosen haphazardly and observed for up to 10 minutes. Not all animals were observed for 10 minutes but the purpose of this analysis we have chosen to include all observations that exceed 3 mins. For this reason I have chosen to model proportion of time spent rather than actual time. I do have time (secs) spent in each category and total observation time if that makes the analysis easier to accomplish. This would need to be weighted somehow though. Three activities (flight, loafing, foraging) were defined and proportions sum to 1.
I am interested in 1. determining if the time spent in flight between the two groups differs and 2. if there is a difference, do both the other activities decrease/increase or only one.
Flight is not a common activity to observe in this species and therefor there are a lot of zeros in the data. Here is the distribution of proportion time spent flying for the two populations

I think that I need to use generalized linear modeling with a zero inflated Poisson distribution but I am unclear on how to make that work correctly. Also it appears that the data is over-dispersed.
I am working in R. Any help or advice for papers to read is appreciated.
Thanks.
UPDATE: 2/6/14
I ran a zero-inflated negative binomial model and ship presence and time of day came out as significant predictors. Since my data was in proportional format I needed to transform the data to integers without loosing the weighting that proportions offered my. I multiplied all the proportions by 600 (max observation time) allowing each observation to have equal weight when using seconds flying.
The mean % time flying was best predicted with presence of ship (0,1) and time of day (morning, mid-day, evening). The predicted times matched closely with the observed times.
Interpretation: These birds appear to spend about 3 times more time flying when ships are present then absent for all three time periods. I then wanted to figure out if they were which activity(s) they were doing less of when ships were present (I measured three mutually exclusive events: flying, foraging, or loafing). Foraging time was also heavily dominated by zeros so I modeled it in the same way. This time when comparing the best fit model with predictors (just presence of ship this time) it did not improve on the fit of the null model (p = 0.10). Could this be that the true distribution is not zero-inflated negative binomial or can I interpret this as there is not a significant difference in the mean time spent foraging when ships are present and absent? This is how the raw data appears to me. The Mann-Whitney U test also comes up non-significant for foraging (although it is suggestive of a difference, p = 0.069).
Assuming that there is no true difference in foraging and a marked difference in flying am I safe to assume that birds in this specific region (I am aware of scope of inference) compensate for extra flying time by loafing less rather than foraging less when ships are present (raw data supports this claim).
Thanks for all the input so far.
Comment: Have you considered using an independent samples test comparing the mean proportion of time flying in the two groups, and similarly for loafing and foraging?  Why do you think it requires anything more sophisticated? Your only independent variable appears to be binomial (presence or absence of a ship), so there is very limited scope for any regression technique.
Comment: @AdamBailey are you suggesting using a Mann-Whitney U-test to test if the distributions are dissimilar? I am familiar with this approach but I was hoping to ultimately generate an estimate of how different these samples are, i.e. some form of logistic regression as you can just look at the distributions and see how different they are. There may also be other variables that I would like to include in the modeling effort to ensure that these results are not an artifact of time of day, season, or some other variable.
Comment: Mann-Whitney U sounds good.  Putting it into an anova framework may be needed if you put in other factors.
Comment: @marcellt I was suggesting an independent samples t-test, relying on the Central Limit Theorem to ensure that the sample means have an approximately normal distribution even if the underlying distribution is Poisson-like. However, this is not appropriate if you want to control for other variables such as time of day.
Answer: If your data seem overdispersed you should apply Negative Binomial distribution, with its additional parameter to account for that. However, this normally applies to count data, not proportions.
The use of the Zero-Inflated Negative Binomial model in R is examplified here:
Fitting a zero-inflated negative binomial regression with R
The theory is explained here:
https://stats.idre.ucla.edu/r/dae/zinb/
Both dichotomic and time parts should initially consist of only the intercept term. You should then perform the Likelihood Ratio test to see if the Ship presence factor contributed to reduce the deviation significantly.
Comment: I will look into your suggestion. I am ultimately interested in the difference between ship presence and absence but I suspect that other variables (time of day, time of season, etc.) may also play a factor in the difference. Therefor I would like to control for them. Can I add them after I add ship presence and perform the Likelihood Ration test to the additional terms to see if these reduce the deviation? Thanks.
Comment: I have tried running the Zero-inflated negative binomial model but it does not like that my dependent variable is not an integer (range = 0-0.7). Should I scale this back to count data (number of seconds in flight for each observation). I would then need to scale this value so that I am not giving more weight to the longer observations. Thoughts?
Comment: "Can I add them after I add ship presence and perform the Likelihood Ration test to the additional terms to see if these reduce the deviation?" Yes. That's ok. As for the dependent variable: The integer seconds would be acceptable, if we assumed the time variable in continuous measurement had Weibull distribution. Which is not unexpected.

Comparing two groups with many zeros


Diff tool that can be integrated into a C# app

Question: I have a small C# app and I'd like to provide the ability to preview diffs and accept changes. My inputs are only text files. I came across some tools like kdiff3 and winmerge and I was wondering if anyone's integrated them inside a C# app and if yes, how was it done? I also came across some nice projects on CodeProject from an earlier stackoverflow question but since those projects were written in 2004, I was wondering if you have any suggestions for an open source diff and merge tool that I can integrate? Thanks!
Answer: Have you checked out csdiff ?
http://code.google.com/p/csdiff/
Comment: Thanks for the link. I did look at their website right now, but I'd rather not have a diff tool which provides the output like the google diff merge tool. I'm looking for a library which can display the files side by side and colored appropriately, similar to what review board or winmerge provide.
Comment: @Rndm, is that google csdiff project what happened to the page gone, apache test page, http://www.componentsoftware.com/   , referenced on http://download.cnet.com/windows/componentsoftware/3260-20_4-54271-1.html ? I loved CSdiff so much, really want a replacement. I'm worried about the cnet one. Should I be?
Answer: You might want to checkout DiffPlex. It is (amongst other things) a library that can be used to generate text diffs. It also provides some higher level classes that provide a more complete "diff model" that should be easier to use for rendering diffs in, say, a textbox.
Personally, I have only used it for minor tasks, but it looks powerful enough to handle more sophisticated scenarios as well.
Comment: Thanks for the reply. I did try downloading DiffPlex and the interface as a diff tool does look good but it does not provide merging/patching
Comment: Oh, I missed that "and accept changes" in your question. Sorry.
Comment: Thanks for the DiffPlex reference! DiffPlex makes it extremely easy to compare strings and return a string that shows changes.
Answer: Winmerge, as you mentioned, can be integrated with other apps via the command line.  Here's an example of visual studio using these command line parameters to replace the built in diff client.  In regards to launching winmerge itself, I found this simple example of how to call an external program from C#.


Branch cuts for $\sqrt{z(z-1)}$

Question: I am studying for quals and found this question in a previous exam:

Find a branch cut for $\sqrt{z(z-1)}$ that is analytic in $\mathbb{C}
\> \setminus [0, 1]$ and takes the value of $-\sqrt{2}$ at $z=2$.

My first instinct was to rewrite this as $z \sqrt{1-\frac{1}{z}}$. The value requirement suggests that $\arg_\tau(1/2) = 2 \pi + 2 \pi k$. But this is analytic on $z \in \mathbb{C} \setminus \mathbb{R}$, which isn't what we want.
After that, I did some googling and found that some people choose to rewrite powers of this form as $f(z) = \sqrt{|z||z-1|} e^{i \frac12 (\arg(z) + arg(z-1))}$ to find their branch points. But I don't know how to proceed further with this to get the branch cut I want.
Comment: How about $$ f(z)=-z\left(1-\frac{1}{z}\right)^{1/2}, $$ where $w^{1/2}=\exp(\frac{1}{2}\log w)$ stands for the principal square root? This $f(z)$ is analytic away from the branch cut $\{0\}\cup\{z:1-\frac{1}{z}\leq 0\}=[0,1]$ and satisfies $$f(z)^2=z^2\left(1-\frac{1}{z}\right)=z(z-1)$$ together with $f(2)=-\sqrt{2}$.
Comment: Indeed, that works. Thank you! I got into the habit of always writing $z = \sqrt{z^2}$ without considering the other branch.
Answer: Using the definition of the complex exponential, we have
$\sqrt{z(z-1)}=e^{\frac12\log(z(z-1))}$
In term of set equivalence, $\log(z(z-1))=\log(z)+\log(z-1)$.  This means that any value of $\log(z(z-1))$ can be expressed as some value of $\log(z)$ and some value of $\log(z-1)$.  Conversely, it means that the some of any value of $\log(z)$ and any value of $\log(z-1)$ can be expressed as some value of $\log(z(z-1))$.  Therefore, we can write (as set equivalence)
$$\sqrt{z(z-1)}=\sqrt{z}\sqrt{z-1}$$
There are branch points at $z=0$ and $z=1$ (and one at the point at infinity).  We are free to choose branch cuts that begin at these branch points and extend to the point at infinity.
Let's choose branch cuts from $z=0$ and $z=1$ that are rays along the negative real axis such that
$$-\pi\le\arg(z)<\pi\\$$
$$\pi\le\arg(z-1)<3\pi$$
At $z=2$, $\sqrt{z}=\sqrt{2}$ and $\sqrt{z-1}=-1$ so that $\sqrt{z(z-1)}$
We could have chosen instead the branches in which
$$\pi\le\arg(z)<3\pi\\$$
$$-\pi\le\arg(z-1)<\pi$$
Then, we see that at $z=2$, we have $\sqrt{z}=-\sqrt{2}$ and $\sqrt{z-1}=1$ so that $\sqrt{z(z-1)}=-\sqrt{2}$ as expected!

Branch cuts for $\sqrt{z(z-1)}$


How to treat arima models with some non-statistical significant p-values?

Question: This is a pretty simple question but didn't find anything relevant here, so hope it's not a duplicate.
I've used statsmodels python library to find the best parameters (minimizing the AIC) for an ARIMA model and the result of the fitting with such parameters set [(1,1,1)x(1,1,0,12)] on the data is:

Now, while that model will minimize the AIC value, I see some coefficients with p-values that indicate non statistical significance (ar1 with 0.966 and ar.S with 0.543). What does that mean? Should I set those coefficients to 0 or the corresponding parameters and refit the model?
Any hint or clarification is greatly appreciated.
Thank you
Comment: 2) Yes, you can. 1) I means that your library couldn't work with incomplete polynoms and fit all $\phi / \theta$ values of characteristic polynomials.
Comment: sorry Dmitriy, could you elaborate more on that? Also, would you suggest alternative libraries? Thanks
Comment: Unfortunately, I can recommend only R libraries. So, I think your library should support fixed values for $\phi / \theta$ parameters.
Answer: There's no rule that says p-values have to be significant. Your fit/estimator is the best one (in the sense of AIC/likelihood) regardless of what the p-values are (there's a big general controversy going on in statistics and areas where statistics is applied about sense, nonsense and rampant overinterpretation of p-values in general). So there is no reason to set parameters to zero.
An insignificant p-value in fact means that, assuming that all the other parameters are still in the model and general model assumptions hold, a model with that particular parameter set to zero is compatible with the data. This doesn't mean that the parameter is in fact zero; the value that you estimated is also compatible with the data and still better in the sense of AIC. The p-value is relevant if it is your research aim to make statements about whether that term is required, or if for some reason you want to get rid of certain parameters (in which case some people think that there are better options than using the p-value). However if you just want a good fit or a model that gives good predictions, use the fit you got and don't worry about p-values.


How to solve problem to see preview in android studio? String index out of arange: -1

Question: I cant see the preview of this layout, is the only with this problem, can build and everything else is ok.
Latout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PriceActivity">

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fabAddCart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="16dp"
        android:clickable="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:srcCompat="@drawable/ic_baseline_add_shopping_cart_24" />

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/editCode"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:autofillHints=""
                android:ems="10"
                android:hint="Code"
                android:inputType="number|text" />

            <ImageButton
                android:id="@+id/imgbScan"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:adjustViewBounds="true"
                android:background="@drawable/btn_primary"
                android:cropToPadding="true"
                android:padding="8dp"
                android:scaleType="fitCenter"
                android:tint="#fff"
                app:srcCompat="@drawable/ic_baseline_qr_code_scanner_24" />

        </LinearLayout>

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:visibility="gone"
            tools:srcCompat="@tools:sample/backgrounds/scenic" />

        <TextView
            android:id="@+id/txtPrice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:textColor="#2E7D32"
            android:textSize="24sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/txtName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:textAlignment="center"
            android:textSize="24sp" />

    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

the error message is:
String index out of range: -1
Details:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
at java.base/java.lang.String.charAt(String.java:693)
at android.content.res.BridgeTypedArray.getType(BridgeTypedArray.java:1024)
at android.content.res.BridgeTypedArray.getType(BridgeTypedArray.java:809)
at android.content.res.BridgeTypedArray.getValue(BridgeTypedArray.java:778)
at android.content.res.BridgeTypedArray.peekValue(BridgeTypedArray.java:847)
at android.view.View.<init>(View.java:5951)
at android.view.ViewGroup.<init>(ViewGroup.java:697)
at android.widget.FrameLayout.<init>(FrameLayout.java:99)
at com.android.layoutlib.bridge.MockView.<init>(MockView.java:55)
at com.android.layoutlib.bridge.MockView.<init>(MockView.java:51)
at com.android.layoutlib.bridge.MockView.<init>(MockView.java:47)
at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:324)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:1121)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1095)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:1124)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1095)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:1124)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1095)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at android.view.LayoutInflater.inflate(LayoutInflater.java:499)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:325)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:369)
at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:141)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:710)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$6(RenderTask.java:865)
at com.android.tools.idea.rendering.RenderExecutor$runAsyncActionWithTimeout$2.run(RenderExecutor.kt:174)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)

the problem is new, is probable after i update android studio, i don't now when exactly have this problem but is only in this layout. app works correctly but the preview and content tree of design view in android studio is not showing.
Comment: Late but I have added a solution. Please check if you still have the issue.
Answer: The issue lies in android:autofillHints="". Remove android:autofillHints="" from EditText and add android:importantForAutofill="no". Above EditTextshould look like below:
        <EditText
        android:id="@+id/editCode"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:importantForAutofill="no"
        android:ems="10"
        android:hint="Code"
        android:inputType="number|text" />

After applying above change, please close this xml file and re-open it to refresh the rendering of Views.
Answer: I had this exact problem and I found this solution to be working for me.
It seems like it might be the solution for you too.
All credit goes to Jin with their post that's available here


setting different indicators for different groups in android

Question: I would like to know how to set different indicators for different groups in ExpandableListView.
I tried :
<code>if(true condition for a group say groupA)
{
    getExpandableListView().setGroupIndicator(getResources().getDrawable(R.drawable.image));
}
</code>
but the above code sets the indicator for all the groups in the view !
I want different indicators for all the groups like :
groupA having a different indicator;groupB having a different indicator;groupC having a different indicator
where groupA,groupB and groupC have certain number of children.
Can anyone suggest something ?
-Adithya.
Comment: Is there a solution for my requirement ? In case of yes please let me know.
Comment: A lot of time is past. I think (and hope) you solved your issue. If not, and for future users having the same problem, refer to this tutorial: http://androidexample.com/Custom_Expandable_ListView_Tutorial_-_Android_Example/index.php?view=article_discription&aid=107&aaid=129
Answer: To create different indicator in expandable listview.
First of all create Adapter for expandable listView.
Create custom layout for all different indicator.
Now in your getGroupView method
<code>@Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
LayoutInflater infalInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if (groupPosition == 0) {
                convertView = infalInflater.inflate(INFLATE YOUT LAYOUT HERE, null);
            } else if (groupPosition == 1) {
                convertView = infalInflater.inflate(INFLATE YOUT LAYOUT HERE, null);
            }else if (groupPosition == 2) {
                convertView = infalInflater.inflate(INFLATE YOUT LAYOUT HERE, null);
            }
}
</code>
Try this this is work for me...
Hope this is helpful for you..
Comment: I vaguely remember that i had worked on something like this long time back. I will have to write the entire code and see :)
Comment: Let me know if it's working or not because In my current app I have many expandable list and I resolve that issue using this code and working fine. If this answer is helpful for you than accept it.


URL de imagem com a função the_post_thumbnail()

Question: Como posso extrair somente a URL (valor do atributo src) de uma imagem gerada pela função the_post_thumbnail e atribui-la a uma imagem?
O resultado que procuro seria algo como:
<img src="<?php the_post_thumbnail(); ?>">

Answer: Se você está dentro do Loop, a ID do post é conhecida pelo WP, então é só usar a função get_post_thumbnail_id() sem parâmetro.
Se estiver fora do Loop, é questão de usar get_post_thumbnail_id($post_id).
E com essa informação à mão, usar a função wp_get_attachment_image_src que indica o Leandro.
Exemplo:
$img = wp_get_attachment_image_src( get_post_thumbnail_id() );
echo "";

Como funciona: a função the_post_thumbnail é um simples encapsulamento pra função get_the_post_thumbnail, que por sua vez termina chamando a função wp_get_attachment_image.
Answer: Você pode fazer da seguinte maneira:
<?php
  $imagem = wp_get_attachment_image_src( $attachment_id, $size, $icon );
?>
<img src="<?php echo $imagem[0]; ?>" />

Aqui está a documentação caso tenha alguma dúvida.


JAVA Efficient way to draw bullets firing from character to mouse position?

Question: I'm creating a 2d game and I wanted to implement shooting. However, bullets for some reason shoot only at a -45° angle. Provided below is my code. The if statement is also important and needs to know when the bullet goes out of range. I've looked up answers for the issue and none of them seem to work.
Also, .getEntity returns the JLabel of the entity.
public class Bullet extends Entity
{
private double speed, dmg, dist, vX, vY, xDest, yDest;
private double traveledDist = 0;
private JLabel bullet;

private String img;

public Bullet(double nSpeed, double nDmg, double xDest, double yDest, double nDistance, String img, double vX,
            double vY)
{
    super(80, 80, "res/img/bullet.png");
    speed = nSpeed;
    dmg = nDmg;
    dist = nDistance;
    this.xDest = xDest;
    this.yDest = yDest;
    this.img = img;
    this.vX = vX;
    this.vY = vY;
    Image image = new ImageIcon("res/img/bullet.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT);
    ImageIcon imageicon = new ImageIcon(image);
    JLabel bullet = new JLabel(imageicon);
    bullet.setSize(80, 80);
    bullet.setVisible(true);
}

public String toString()
{
    return ("[Speed: " + speed + ", Damage: " + dmg + ", xDest: " + xDest + ", yDest: " + yDest + ", vX:" + vX
                + ", vY" + vY + ", Distance: " + dist + ", Traveled Distance: " + traveledDist + ", Image Path: " + img
                + "]");
}

public double getxDest()
{
    return xDest;
}

public double getyDest()
{
    return yDest;
}

public double getvX()
{
    return vX;
}

public double getvY()
{
    return vY;
}

public JLabel newBullet()
{
    return bullet;
}

public double getSpeed()
{
    return speed;
}

public double getDmg()
{
    return dmg;
}

public double getDist()
{
    return dist;
}

public String getImg()
{
    return img;
}

public double getTraveledDist()
{
    return traveledDist;
}

public void setTraveledDist(double nDist)
{
    traveledDist = nDist;
}

}
private void fireBullet()
{
    System.out.println("bullet");

    double originX = lblCross.getX() - lblChar.getX();
    double originY = lblCross.getY() - lblChar.getY();
    double mouseX = MouseInfo.getPointerInfo().getLocation().getX();
    double mouseY = MouseInfo.getPointerInfo().getLocation().getY();
    double bulletVelocity = 1.0;
    //mouseX/Y = current x/y location of the mouse
    //originX/Y = x/y location of where the bullet is being shot from
    double angle = Math.atan2(mouseX - originX, mouseY - originY);
    double xVelocity = (bulletVelocity) * Math.cos(angle);
    double yVelocity = (bulletVelocity) * Math.sin(angle);

    Bullet tempBullet = new Bullet(((ProjectileWeapon) sWeapon).getProjectileSpeed(), sWeapon.getDamage(), 0, 0,
                sWeapon.getRange() * 100, ("res/img/bullet.png"), xVelocity, yVelocity);

    tempBullet.getEntity().setVisible(true);
    room.add(tempBullet.getEntity());
    room.repaint();
    tempBullet.getEntity().setLocation(lblChar.getX(), lblChar.getY());
    bullets.add(tempBullet);
}

private void updateBullet()
{
    for (int i = 0; i < bullets.size(); i++)
    {
        bullets.get(i).getEntity().getY());
        if (true)
        {
            System.out.println("updating" + bullets.get(i));
            Bullet b = bullets.get(i);
            b.getEntity().setLocation((int) (b.getEntity().getLocation().getX() + (b.getvX() * 10)),
                        (int) (b.getEntity().getLocation().getY() + (b.getvY() * 10)));
            b.setTraveledDist(b.getTraveledDist() + 1);
            room.repaint();
        }
                    else
                    {
                        room.remove(bullets.get(i).getEntity());
                        bullets.remove(i);
                        room.repaint();
                    }
    }
}

Your help is much appreciated.
Comment: What happens with another angles? What about coordinate rounding? To perform more exact moving, you'd better to store and update float coordinates and round them only for drawing (yes, I see x10 multiplier)
Comment: They all go in the same -45° angle no matter what
Comment: Perhaps your  updating values are wrong
Answer: Here's the code I ultimately used:
double theta = Math.atan2(destination.getY() - origin.getY(), destination.getX() -
origin.getX());
    xVelocity = Math.cos(-theta);
    yVelocity = -Math.sin(-theta);


How to run phpBB in Docker with NGINX, php installed on a different host than the database?

Question: How can I run a Docker image with NGINX, phpBB (and all required stuff like php installed) with persistence (Changes on the board shouldn't be lost) and with the database on another host (which already exists). So, let's assume I have the following: MySQL on 192.168.2.233 (local address) on port 3307 running. Now I want to create a Docker image with Alpine Linux (The smallest propably), NGINX and phpBB where the board runs on the NGINX webserver and connects to the database. Changes on the board (E.g. changing the webserver settings or so) should be persisted within the container. How can I do that?
EDIT:
The database on server 192.168.2.233 is already existing! So no, I don't need two or more Docker containers. I need one Docker container with phpBB running on the NGINX webserver and connecting to the database on another host in the same network. The container should use persistence (volumes) to save the settings made in phpBB.

I tried to use the following Dockerfile and modified it:
https://gitlab.com/boxedcode/alpine-nginx-php-fpm/blob/master/Dockerfile --> https://drive.google.com/open?id=1CW68OFCJE9RjIe8_RBC8q5Fa6juRtxmR
Comment: Hint: You'll probably want to run the various components in separate containers (e.g. the phpBB app in one, NGINX in another, the DB in another).  To persist your data mount external volumes.  I'd recommend having a go and then re-posting specific questions if you run into problems - you'll get better responses!
Comment: @bunnmat I already have a running instance of the database (See the edited question with the image).
Comment: Does https://hub.docker.com/r/bitnami/phpbb/ give you what you'd need?
Comment: @bunnmat: If I modify it a bit, I guess so :)
Comment: I've now found a solution using this repository: https://github.com/blueimp/phpbb/issues/1 and put my solution in there together with the owner of the repo.
Answer: Together with the owner of another repository I've now found a solution (that uses Apache however) here: https://github.com/blueimp/phpbb/issues/1. After a few errors and problems from my side, I figured it out. The solution I'm using now is placed here: https://github.com/SeppPenner/DockerApacheSSLphpBB


How can I get code assist for jQuery within a JSPX file in eclipse?

Question: I'm trying to edit and add some jQuery functionality to a jspx page and could really use a little code assist for playing with jQuery.  I've installed the aptana plugin and have tried switching to the aptana web perspective but I'm not getting any ctrl+space popups (I've enabled jQuery 1.3 and 1.4 in the eclipse -> aptana -> javascript -> code assist preference).  Is there a way to get aptana to kick in on a jspx file?  Is there another plugin I should try?
Answer: You could try to open your jspx file in the Aptana Html Editor.
Right click the file -> Open with -> Others... -> Aptana Html Editor.
Then the code assist should work for your javascript.
Comment: I tried that but the aptana plugin errors out when trying to open the file.
Answer: I ended up following instructions on this website:
http://www.langtags.com/jquerywtp/?page_id=4#comment-59
Which guides you through "patching" one of the wtp jar files...doesn't seem like the best solution, however, it does work.


Drupal 7 theme for specific page

Question: I have one page mortgages/%/view that needs to have it's own custom theme. I have the HTML created and it's ready to go. In my 'mortgage' module I have a mortgage.tpl.php file with this HTML in it.
My hook_menu looks like this:
function mortgage_menu() {

  $items = array();

  $items['mortgage/%/view'] = array(
    'page callback' => 'mortgage_callback',
    'page argument' => array(3), //pass 3rd argument of url -- 1. drupal 2. mortgage 3. %
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
 }

Then my callback function and mortgage_theme function look like this:
function mortgage_callback() {
 return theme('mortgage');
}

 /*
 * Implementation of hook_theme().
 */

function mortgage_theme(){
  return array (
    'mortgage' => array (
      'template' => 'mortgage' ,
      'arguments' => array(),
    ),
  );
}

This successfully calls my mortgage.tpl.php file into my mortgage/%/view page. HOWEVER, it only displays in the middle of my "content" section instead of correctly overriding the theme. Obviously this isn't correct.
How would I get this mortgage.tpl.php file to be THE theme file for this specific page?
e/ Mortgage is NOT a node. It's a custom module which allows users to get a full page view of mortgage details.
Comment: The HTML from mortgage.tpl.php appears to be missing from your post.
Comment: @othermachines - I didn't include it because it's a lot of code. I can put it in a GIST but it's essentially the bootstrap theme I use copied over and removed the header/mainmenu from it was all. I can post it all but just seemed irrelevant because it all posts just in the middle of the page and keeps the default template. It's like it's applying both templates o.O
Comment: Did you look at https://www.drupal.org/project/themekey module?
Comment: @ar7max can this be used to just remove certain parts of a current theme? I don't really want to make a whole new theme and change the entire theme.
Answer: In your module
function custom_theme($existing, $type, $theme, $path){
      return array(
        'mortgage_page' =>  array(
          'template' => 'theme/mortgage',
          'render element' => 'page'
        ),
      );
    }

function custom_preprocess_page(&$variables, $hook) {
  if ( preg_match("/mortgage\/.*\/view/", drupal_get_path_alias($_GET['q'])) ) {
   $variables['theme_hook_suggestions'][] = 'mortgage_page';
  }
}

Check for path alias to be correct and change theme_hook_suggestions to your theme.
Comment: Awesome! I edited yours a bit but custom_preprocess_page() was exactly what I was missing. I wish I could upvote it but I'm 1 shy lol

e/ jk I have 16 now since I accepted the answer!
Answer: This working as designed, if you want to override the whole page markup, you might consider custom page.tpl.php, Also you would use template_preprocess_page to add theme_hook_suggestions to let that page pickup your custom_page.tpl.php
Yourtheme_preprocess_page(&$vars) {
   if(something) {
      $vars['theme_hook_suggestions'][] = 'page_your_custom_page_tpl';
   }
}

Comment: Can I just load the page.tpl.php in my module instead of the mortgage.tpl.php? I guess this would completely override the standard page.tpl?
Comment: well yes, but you need to tell Drupal to pick it up by adding "theme_hook_suggestions"

Drupal 7 theme for specific page


Unbiased Estimator of the Variance of the Sample Variance

Question: At Mathematics Stack Exchange, user940 provided a general formula to calculate the variance of the sample variance based on the fourth central moment $\mu_4$ and the population variance $\sigma^2$ (1):
$$\text{Var}(S^2)=\frac{\mu_4}{n}-\frac{\sigma^4(n-3)}{n(n-1)}$$
I would be interested in an unbiased estimator for this, without knowing the population parameters $\mu_4$ and $\sigma^2$, but using the fourth and second sample central moment $m_4$ and $m_2$ (or the unbiased sample variance $S^2=\frac{n}{n-1}m_2$) instead.
Answer: The question is to find an unbiased estimator of:
$$\text{Var}(S^2)=\frac{\mu_4}{n}-\frac{(n-3)}{n(n-1)} {\mu_2^2}$$
... where $\mu_r$ denotes the $r^\text{th}$ central moment of the population. This requires finding unbiased estimators of $\mu_4$ and of $\mu_2^2$.
An unbiased estimator of $\mu_4$
By defn, an unbiased estimator of the $r^\text{th}$ central moment is the $r^\text{th}$ h-statistic:  $$\mathbb{E}[h_r] = \mu_r$$
The $4^\text{th}$ h-statistic is given by:

where:
i) I am using the HStatistic function from the mathStatica package for Mathematica
ii) $s_r$ denotes the $r^\text{th}$ power sum $$s_r=\sum _{i=1}^n X_i^r$$
Alternative:
The OP asked about finding an unbiased solution in terms of sample central moments $m_r=\frac{1}{n} \sum _{i=1}^n \left(X_i-\bar{X}\right)^r$. An unbiased estimator of $\mu_4$ in terms of $m_i$ is:

An unbiased estimator of $\mu_2^2$
An unbiased estimator of a product of central moments (here, $\mu_2 \times \mu_2$)is known as a polyache (play on poly-h). An unbiased estimator of $\mu_2^2$ is given by:

where:
i) I am using the PolyH function from the mathStatica package for Mathematica
ii) For more detail on polyaches, see  section 7.2B of Chapter 7 of Rose and Smith, Mathematical Statistics with Mathematica (am one of the authors), a free download of which is available here.
While mathStatica does not have an automated converter to express PolyH in terms of sample central moments $m_i$ (nice idea), doing that conversion yields:

Putting it all together:
An unbiased estimator of $\frac{\mu_4}{n}-\frac{(n-3)}{n(n-1)} {\mu_2^2}$ is thus:

or, more compactly, in terms of sample central moments $m_i$:
...........
And as a check, we can run the expectations operator over the above (the $1^\text{st}$ RawMoment of sol), expressing the solution in terms of Central moments of the population:

... and all is good.
Comment: Yes - the solutions assume the sample size $n \ge w$, where $w$ denotes the _weight_ of the expression. For instance, an expression containing $\mu_2^3$ has weight = 6. It also assumes, of course, that the moments of the parent random variable exist up to that weight. I have updated the answer above to provide the unbiased estimator of $\mu_2^2$ in terms of $m_i$ which is indeed neater.
Comment: @Hiro - checked and seems fine to me. I have further checked by converting the expression in sample central moments  back to power sums which can be done with  `expr /. Subscript[m, i_] :> SampleCentralToPowerSum[i][[2]] // Simplify` which returns the expression in power sums above. If you can post your (simulation?) code, I will be happy to look at what you are doing.
Comment: Great answer! Thanks! Two things: 1. It would be great if the estimator of $\mu_2^2$ could also be expressed in terms of $m_r$. 2. I'm often encountering terms such as $(n-1)(n-2)(n-3)\ldots$ in the denominator when unbiased quantities are involved. For instance, the unbiased estimator of $\mu_4$ that you have presented has $(n-1)(n-2)(n-3)$ in the denominator. Another example is Bessel's correction with $(n-1)$ in the denominator. Can I generally assume that _any_ unbiased estimator of $\mu_r$ is only defined for $n \geq r$? Is there a theorem for that?
Comment: Thanks for the explanation! However, I think that there is an issue with the unbiased estimator of $\mu_2^2$ in terms of $m_i$. I have checked it in Mathematica by calculating the average of multiple estimators and the result is quite off. It would be great if you could take a look at it again!
Comment: I have checked my code and noticed that I've made a mistake that introduced the bias. After correcting it, everything works great! :-) Sorry for that and again, thank you very much!
Comment: @wolfies Hello! Just one question: I've run this estimator 100.000 times and some realizations seem to be negative. Is that expected? How can that be explained if it's a variance? Here's a screenshot of my code i.stack.imgur.com/5YEp9.png


Server.MapPath falha dentro do Global.asax

Question: No código abaixo, quando tento chamar a função MapPath dentro do Global.asax, ocorre um erro em tempo de execução com a seguinte mensagem de erro:

System.Web.HttpException (0×80004005): Request is not available in
  this context.

O código com defeito é:
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    string path = HttpContext.Server.MapPath("~/assets/all.js")

    // ... code
}

Como usar uma função MapPath no Global.asax?
Answer: O problema está de fato no HttpContext.Server.MapPath. O problema ocorre pois quando chamado no Application_Start, não há um contexto Http. Esse contexto só existe quando há um chamado HTTP.
O Application_Start ocorre apenas quando sua aplicação web é iniciada via Start/Restart no IIS, reciclando o App Pool, entre outras formas. Como não há um contexto HTTP, você deve usar o contexto do ambiente.
Troque o HttpContext para HostingEnvironment.MapPath:
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    string path = HostingEnvironment.MapPath("~/assets/all.js")

    // ... code
}

O próprio Server.MapPath() chama o HostingEnvironment.MapPath(). A única diferença que importa no contexto dessa pergunta é que você precisa certificar que a string passada no parâmetro nunca é nula, senão uma Exception será disparada.
Comment: Nota: O antes utilizado `HttpContext.Current` passou a não estar disponível no `Application_Start` na versão 7 do IIS. Se a aplicação estiver hospedada em uma versão anterior ou no modo *classic* o contexto estará disponível. Mas claro, não recomendo essa dependência :)
Answer: O HttpContext é apenas disponível quando alguém faz um chamado HTTP (como ir no site por meio de um browser).
Nesse sentido, não é possível usar a função como descrito, no lugar onde se encontra no Application_Start. Entretanto, mesmo sabendo que a pergunta é a respeito do Global.ascx, a linha
string path = HttpContext.Server.MapPath("~/assets/all.js")

é código completamente válido se estiver usado dentro de um Controller ou View (usando MVC) ou o Code Behind (usando webforms do ASP.NET).
Answer: Tente:
System.Web.Hosting.HostingEnvironment.MapPath();


Uniform convergence of $\{n\sin\frac{1}{nx}\}$ on $(0,1]$

Question: Show that $f_n(x)=n\sin\frac{1}{nx}$ is not converges uniformly to limit function on $(0,1]$.
Tell me if that is right:
I have found that the limit function of $f_n$ is $\frac{1}{x}$.
Now,
$$|n\sin\frac{1}{nx}-\frac{1}{x}|\leq |n\sin\frac{1}{nx}|+\frac{1}{x}$$
Since, $\sin x< x$ for small $x\in (0,1]$ we have that:
$$|n\sin\frac{1}{nx}-\frac{1}{x}|+\frac{1}{x}<n\frac{1}{nx}+\frac{1}{x}=\frac{2}{x}$$
Thus, exist $\epsilon>0$, (i.e $\epsilon=2$) s.t for every $N\in\mathbb{N}$ and $n>N$:
$$|n\sin\frac{1}{nx}-\frac{1}{x}|>2$$
Hence $f_n \to f$ not uniformly.
Comment: You can't pass the inequalities like that...say $a2$ can we say $a>2$ as well?
Comment: Fix an $n$ odd. What happens when $x = \displaystyle \frac{1}{k} \Big(\frac{2}{n \pi}\Big)$ when k is an odd integer?
Answer: The non-uniform convergence of a sequence is normally proved in the following way.
Uniform convergence is

For any fixed $\epsilon>0$ there exists an $N$, such that for all $n>N$
  $$
|f_n(x) - f(x)| < \epsilon \quad \text{for any } x,$$
  or  more simply put
  $$
\sup_{x} |f_n(x) - f(x)|  \to 0.
$$

Now if we can negate above argument and try to find something like

For any fixed $N$, such that there exists an $\epsilon>0$ and $n > N$:
  $$
|f_n(x) - f(x)| \geq \epsilon \quad \text{for some }x,\tag{1}
$$
  or more simply put
  $$\sup_{x} |f_n(x) - f(x)| \not \to 0.\tag{2}$$

Then the convergence is not uniform.
For (1), there are many choices of such $x$ you can try (there are many other choices, based on an inverse involving an integer times $\pi$): for any $N$ fixed, let
$$
x = \frac{1}{N\pi},
$$
then letting $n= 2N > N$
$$
\left|n\sin \frac{N\pi}{n} - N\pi\right| = N(\pi-2) \geq \epsilon.
$$
Done.
Or you could try (2)
$$
\sup_{x}  \left| n\sin \frac{1}{nx}- \frac{1}{x}\right| \geq  \left| n\sin \frac{1}{n(2/(n\pi))}- \frac{1}{2/(n\pi)}\right| = n(\pi/2-1)\not\to 0 \quad \text{ as } n\to \infty.
$$


Taking screenshot of Part of Screen

Question: I have a UIImageView in my view controller whose screeshot I need to take. There is a UILabel on it as well. UIImageView doesn't cover the whole page just part of it. How can I take screenshot of just section of the screen?
I bet this question has been asked before but I looked into this post How to use UIGraphicsBeginImageContextWithOptions? and it was nothing but confusing with undefined variables

so far the code I have takes the screenshot of the whole thing. (not what I want). I tried playing with screenRect with no effect. I thought about cropping picture after taking the whole screen screenshot but the problem is that the crop sizes will be different for each device iphone3, iphone4, iphone5, iPad 1,2,3 etc.
So my question is there a way to take a screenshot of a section of screen without going through cropping route? If cropping is the only way to go then is there a way I can reliably cut the picture without worrying about different iOS devices with high/low pixels?
testBgImgVw = [[UIImageView alloc] initWithFrame:CGRectMake(0, 80, 320, 220)];

....

    -(IBAction) takeScreenshot
    {
        CGRect screenRect = [[UIScreen mainScreen] bounds];

        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
        {
            //its iphone
            screenRect  = CGRectMake(0, 0, 320, 480);
        }
        else
        {
            //its pad
            screenRect  = CGRectMake(0, 0, 768, 1024);
        }

        // This code is for high resolution screenshot
        UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, 0.0);
        [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        NSData* imageData = UIImageJPEGRepresentation(viewImage, 1.0);
        NSString* incrementedImgStr = [NSString stringWithFormat: @"UserScreenShotPic.jpg"];

        NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString* documentsDirectory = [paths objectAtIndex:0];

        // Now we get the full path to the file
        NSString* fullPathToFile2 = [documentsDirectory stringByAppendingPathComponent:incrementedImgStr];
        [imageData writeToFile:fullPathToFile2 atomically:NO];

    }

Comment: do you wanna capture the image & the label?
Comment: which section do you wanna crop?
Comment: I want to capture the image and label. The image and label are usually all in one area i.e. between (0, 80, 320, 220) coordinates
Answer: ok  if you just only want to capture the image & the label on the image ( if you can make sure the label is always on the image), then
add the label  on the imageview  (imageview addSubview:label)
then render it into a new image
UIGraphicsBeginImageContextWithOptions(screenRect.size, NO,[[UIScreen mainScreen]scale]);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

done  :)
if you wanna take a shot of several uiviews(imageview,label, etc), the best way is provide a UIView canvas
UIView *canvasView = [[UIView alloc]......]
[self.view addSubview:canvasView];

and add every view you wanna render on it ,  finally render it into a new image you want
Comment: that worked 50% - it took the screenshot of the image view section which is great but for some reason adding the label as subview didn't capture the label
Comment: it will capture the label  if the label is the subview of the imageview, unless you calculate the wrong position that the label is no shown in the visibal rect of the imageview
Comment: you should recalculate the relative position from the label to the imageview first, until the label is displayed right to the image you provide above
Comment: ok, this will take a lot of trail and error. To compound the problem I let users move label around. Now I have to figure out where did they leave the label relative to the image. Just adding this line doesn't do anything (in terms of screen capture) [testBgImgVw  addSubview:customLabel1];
Comment: I guess my only hope is to crop the whole screen capture starting at certain X,Y coordinates in this case (0,80).
Comment: i think you want to implement that add some text onto the imageview ? if i'm right , my way is correct,  if you want to capture the label if label's position is out of the image ,  then use a canvasview to wrap all the controls
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/28523/discussion-between-sam-budda-and-adali)

Taking screenshot of Part of Screen


Send parameter to class, but the class is wraped with array

Question: So i have some class that is wrap with array caled screenData, and i want to pass indexTheme to each of these class.

  int indexTheme = 1;

  final screenData = [
    const homeTest(),
    const productPage(),
    const trading(),
    const inventoryPage(),
    const masterPage(),
    const financePage(),
  ];

i can simply just pass data like this, but in the future i want to change value of int.
    int indexTheme = 1;

    const homeTest(
       indexTheme = 1;
    ),

Answer: You can use for loop to pass parameters
Void changeIndexTheme(int newIndexTheme){
    for(var classInstance in screenData){ //instead of var it's better to write your class name
        classInstance(
            indexTheme = newIndexTheme;
        );
    }
}

I think this way works if you didn't try it before, now you can call this function to change all values


How to use ALAssetLibrary to get Local Photos in Camera Roll

Question: ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
    [library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
                           usingBlock:libraryGroupsEnumeration
                         failureBlock:failureblock];
ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result, NSUInteger index, BOOL *stop){
        if (result!=NULL) {

            if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {

                [self._dataArray addObject:result];
            }

        }
    };

ALAssetsLibraryGroupsEnumerationResultsBlock
    libraryGroupsEnumeration = ^(ALAssetsGroup* group, BOOL* stop){
        //within the group enumeration block.filter to enumerate just photos.
        [group setAssetsFilter:[ALAssetsFilter allPhotos]];
        if (group!=nil) {
            NSString *g=[NSString stringWithFormat:@"%@",group];
            NSLog(@"gg:%@",g);//gg:ALAssetsGroup - Name:Camera Roll, Type:Saved Photos, Assets count:71
            [group enumerateAssetsUsingBlock:groupEnumerAtion];
        }
        else {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [self saveToDB:self._dataArray];

            });
        }

    };

Assume that my Camera Roll have 100 photos,and I want get first 30 to save to my database.but in above code ,I must wait for 100 results fisishing.After 30 write to database , continue to get another 30 until end.
because get 100 or even more photos will delay my UI refresh.It looks not comfortable.
Thanks a lot!
what should I write.?
Answer: You should try saving to the database on a background thread, and let CoreData (assuming you use CoreData) update the NSManagedObjectContext on the main thread by handling NSManagedObjectContextDidSaveNotification.
You could still save after 30 photos, that might relieve some of the I/O stress, but you'd have to test performance.
Answer: Try this one
if (result!=NULL) {

    if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])         {

          [self._dataArray addObject:result];

            if([self._dataArray count] == 30){

               dispatch_async(dispatch_get_global_queue(0, 0), ^{

                 NSArray *array = [[NSArray alloc] initWithArray:self._dataArray]; //please change the array declaration to top of this method. Because the Block will not allow to do it here.
                 [self._dataArray removeAllObjects];
                 [self saveToDB:array];
                 //array release,if not using ARC

           });
       }
    }

}

and
if (group!=nil) {

            [group enumerateAssetsUsingBlock:groupEnumerAtion];
        }
        else if([self._dataArray count] > 0) {

              dispatch_async(dispatch_get_global_queue(0, 0), ^{

                    [self saveToDB:self._dataArray];

            });
        }


How to create a list of similar nodes in Drupal 7/Views 3

Question: I face a rather common problem of displaying a list of nodes similar to current one. Similar node is defined as one having at least one taxonomy term that current node has. There are few solutions available as modules, however most modules I've found are in beta stage for Drupal 7.
I've also found a couple of solutions based on Views and contextual filters (such as http://scito.ch/content/show-related-nodes-block-based-taxonomy-terms-views-3-and-drupal-7) or relations. I quite like this way as it saves me installing extra modules and with Views being actively developed and supported I'd prefer to use them rather than any custom solution. The problem I can't get around is how to sort "similar nodes" by the number of terms they share. For example, if I have "IPhone 4S" Node with Terms "Gadget", "Apple", and "Phone", I want similar nodes in the following order:

IPhone 3 (Apple, Gadget, Phone)
IPad (Apple, Gadget, Tablet)
Mac (Apple, Computer)
Bramley (Apple, Fruit, Tree)

How can I sort nodes in this view by the number of terms they share?
Comment: For those upvoting and favoriting, I've got the answer here: http://stackoverflow.com/questions/10454507/creating-list-of-similar-nodes-in-drupal-7-views-3
Comment: Since you still haven't had many answers, I just wanted to point out that I'm fairly certain that with Views and it's aggregation settings, you can achieve this. It's something I've been meaning to test further myself, but never got around to it. This is essentially what [Similar By Terms](http://drupal.org/project/similarterms) but far less rigid.
Answer: For those upvoting and favoriting, I've got the answer here: https://stackoverflow.com/questions/10454507/creating-list-of-similar-nodes-in-drupal-7-views-3
It boils down to:

Create a block view
Add Contextual filter -> Content: Nid -> Provide default value -> Content ID from URL
Add Relationship -> Content: Taxonomy terms on node -> specify the appropriate vocabulary
Add Relationship -> Taxonomy term: Content using vocabulary as specified
above -> Check off Require this relationship
Turn on Views aggregation
Assuming you are listing title only, edit the title field to use the Relationship you set up in #4 above.
Add new sort criteria of Content: Nid. In aggregation settings, select Count. Use relationship from #4 and sort descending
Add Contextual filter -> Content: Nid -> Use relationship from #4 -> Provide default value - Content ID from URL -> Scroll down and expand "More" then check "Exclude" to remove current node from the view.
Answer: To get the results easily, try the Similar By Terms module.
Comment: I'm a bit reluctant to use beta version of any module. Specifically after installing Similar By Terms and enabling its block I get "Warning: Invalid argument supplied for foreach() в функции similarterms_taxonomy_node_get_terms()" (though it displays something credible in the block).


Como limpar campo de input com angular?

Question: estou tentando limpar o campo de texto, após o submit, mas não estou conseguindo.
Seguem os meu códigos
html:
Aqui no html, mudei de ng-model="msg" para mensagem.msg

            Enviar

angular:
$scope.mensagem = {
    msg:""
  };
$scope.enviarMsg = function (mensagem) {
    var enviaMsg = {
        msg: mensagem,
        idUsuario: $window.localStorage.getItem('idUsuario'),
        idCep: $window.localStorage.getItem('idCep'),
        nome: $window.localStorage.getItem('nome')
    }

    $http.post("http://www.vigilantescomunitarios.com/www/php/enviaMsgLogra.php", enviaMsg).success(function (data){

        pegaMsgsLogra();
        $scope.mensagem = {
             msg:""
            };
    });
}

Recebo essa mensagem no console:

TypeError: $scope.msgForm.$setPristine is not a function
Comment: Se você tirar isso: `delete msgForm` e isso `$scope.msgForm = []` não funciona?
Comment: Não, continua o mesmo aviso e não acontece nada.
Comment: http://jsfiddle.net/AhGDC/243/
Comment: Apareceu isso no console
TypeError: Cannot read property '$setPristine' of undefined
Comment: Consegui.
Vou postar aqui a solução
Comment: Veja se esse post te ajuda https://pt.stackoverflow.com/questions/94951/problema-ao-tentar-pegar-o-scope-do-form-com-ionic/113532#113532
Answer: Tente desta forma:
$scope.form = {}; //Definido logo no inicio do controller

$scope.form.msgForm.$setPristine(); //Definido no local onde deve ser feito a limpeza

E em seu html:
<form name="form.msgForm">

Normalmente isso acontece pois muitas vezes sua view é alternada ou o formulário é inicializado após o controller. Deste modo ele mantém referência ao formulário.

Para apagar o campo do input, você deve usar a mesma referência do ng-model e NÃO do nome do formulário. No seu caso, deve ser assim:
delete $scope.msg;

Assim você pode remover todas as definições $scope.msgForm = []; do seu controller.
Comment: Nada, o texto continua no campo.
Comment: E o console, o que mostra?
Comment: Nada também. Pelo menos isso kkkkkk
Comment: @GustavoSevero Editei minha resposta, dê uma olhada
Comment: Nada ainda... Ta bem complicado.
Comment: Conseguiiiiiiii!!!!!!
Vou postar aqui o como ficou... Tive que mudar o nome do ng-model
Comment: Será que você não tinha uma dupla declaração com o nome $scope.msg?
Comment: @GustavoSevero sua solução pode resolvido, mas a limpeza do seu formulário não está completa. Não usar $setPristine() não reseta o estado do seu formulário, ele vai ficar com algum lixo do preenchimento anterior.
Answer: delete $scope.msg;

$scope.msgForm.$setPristine();

Tenta isso
Comment: $scope.mensagem não possui nenhuma definição e `mensagem` é apenas um obj js. Deste modo, nada vai acontecer.
Comment: verdade, vi errado o form dele. No caso eu colocaria no ng-model, ng-model="mensagem.msg". Ae creio que funcione, mas como no caso só tem um input talvez não seja necessario
Comment: Na verdade era a referência dele que estava errada. Ele estava tentando apagar o formulário ao invés do campo. Veja minha resposta. =D

Como limpar campo de input com angular?


Understanding Hilbert's program

Question: Upon covering Hilbert's program in class and consulting https://plato.stanford.edu/entries/hilbert-program/, there were some questions I had on Hilbert's work, and was trying to find answers to them.

For Hilbert's Finitism, how does it manage to inherit/salvage methods of classical mathematics while still catering to the intuitionist's concerns?

I can see that Hilbert tried to eliminate all that was infinite (could be wrong on this statement) and only wanted to keep things that were finite but I don't see how he catered to intuitionism

What is the idea of a conservative extension and how does it relate to Hilbert's program?

Looking into the wiki article (https://en.wikipedia.org/wiki/Hilbert_system#Conservative_extensions), it's not quite clear to me of what the extension is referring to and when it mentions being fully extended, a hilbert-style system will resemble a system of natural deduction?
Thanks!
Comment: For 1. The program is aimed at grounding math on *contentful* math (i.e. the "finitistic"; more or less PRA; see also Skolem) that was "obviously" intuitionistically valid. The original Hilbert's project (that gave birth to Proof Theory) was to use this part to prove the *consistenty* of the "more general" infinitistic math: mainly analysis. Several partial results by Hilbert's school members (Ackermann, von Neumann) regarding the consistency proof of (fragments) of arithmetic and analysis were attained, until Godel's Incompleteness Th.
Comment: In the context of Hilbert's program, we have to consider also Herbrand's and Gentzen's researches and results.
Comment: Relevant : Wilfried Sieg, [Hilbert's Programs and Beyond](https://books.google.it/books?id=4lDrwqo-8TkC&printsec=frontcover), Oxford University Press (2013)
Comment: Gregory Moore, [Hilbert on the Infinite: The Role of Set Theory in the Evolution of Hilbert's Thought](http://www.sciencedirect.com/science/article/pii/S0315086001923328), *Hist Math* (2002)
Comment: Paul Bernays, [David Hilbert](http://www.phil.cmu.edu/projects/bernays/Pdf/bernaysHilbert_2003-05-17.pdf) (1967)
Comment: Craig Smorynski, [Hilbert's Programme](http://oai.cwi.nl/oai/asset/18149/18149A.pdf).
Comment: Curtis Franks, [The Autonomy of Mathematical Knowledge: Hilbert's program revisited](https://books.google.it/books?id=cQteMYUb_2IC&printsec=frontcover), Cambridge UP (2009).
Comment: Michael Detlefsen, [Hilbert's Program: An Essay on Mathematical Instrumentalism](https://books.google.it/books?id=VessBAAAQBAJ&printsec=frontcover), Springer (1986).
Comment: Richard Zach, [HILBERT'S PROGRAM THEN AND NOW](http://people.ucalgary.ca/~rzach/static/hptn.pdf).
Comment: Volker Peckhaus, [The Pragmatism of Hilbert's Programme](https://www.jstor.org/stable/20118355?seq=1#page_scan_tab_contents) (2003).
Comment: Per se, the "presentation" of the calculus has quite nothing to do with H's programme; we call it Hilbert-style because it has been formalized in the first moder math log textbook : Hilbert & Ackermann, [Grundzüge der theoretischen Logik](https://en.wikipedia.org/wiki/Principles_of_Mathematical_Logic) (1928). But iot is worth noting that Natural Deduction was discovered by [Gerhard Gentzen](https://en.wikipedia.org/wiki/Gerhard_Gentzen) developing previous researches on the "rule only" among other by [Paul Bernays](https://en.wikipedia.org/wiki/Paul_Bernays).
Comment: Hilbert in 1916 did a considerable amount of math for Einstein for the development of General  Relativity, and about none of it could be called finitistic. And Hilbert said, of Cantor's theory of infinite sets, "No one shall drive us out ot the paradise that Cantor has created for us."
Answer:
For Hilbert's Finitism, how does it manage to inherit/salvage methods of classical mathematics while still catering to the intuitionist's concerns?
  I can see that Hilbert tried to eliminate all that was infinite (could be wrong on this statement) and only wanted to keep things that were finite but I don't see how he catered to intuitionism.

I don't think it is right to think of Hilbert as trying to eliminate all that was infinite -- after all, he was one of the great (if not the greatest of) early 20th Century mathematicians, justly famous and revered for his ground-breaking work on various areas of classical (thoroughly infinitary) mathematics. He wasn't trying to sabotage his own work by sawing off the branches he was sitting on and "eliminating all that was infinite".
No, better to think of him as trying to secure the infinite by showing that classical mathematical ideas were not really threatened by apparent inconsistencies generated by the paradoxes and foundational problems that loomed early in the 20th Century, or by the critiques of intuitionists like Brouwer who claimed to find the classical theories incoherent.
How then did Hilbert (and his pupil then assistant Bernays, who perhaps was the philosophically clearer of the two) plan to secure classical mathematics?
The plan is (i) to give rigorous axiomatic presentations of chunks of classical mathematics (maybe we can do this wholesale by reducing it all to some set theory, or to arithmetic plus type theory, or something). (ii) Now  stand back from such axiomatic theories and note that -- while the theories may be about infinitary whatnots -- the theories themselves are finitary structures (in the sense that their sentences are finite objects, properties like being-a-correctly-formed-proof are finitely checkable, etc., etc.). So this means we can use finitary reasoning about the theories.
And now here is the hopeful thought (and it is a quite brilliant one): we can in particular aim to use finitary reasoning -- reasoning acceptable to even the sternest critics of classical mathematics including the intuitionists -- to show that our classical theories are consistent  after all(?!?!) That project is known as Hilbert's Programme.
It turns out, however, that we can't pull that off. For example, even though Zermelo Set Theory as a theory is a finitary object, we need infinitary reasoning at least as problematic as Zermelo Set Theory itself to show that the theory is consistent (we learn this from Gödel). Drat. Hilbert's Programme is a failure -- though a glorious failure, as it still leads to all kinds of highly important work in proof theory etc.
For a bit more on some details, and on the impact of Gödel's work (not an entirely straightforward matter), see my Introduction to Gödel's Theorems.
Comment: (+1) But what is the definition of *finitary reasoning*?
Answer: You can see :

David Hilbert & Wilhelm Ackermann, Grundzüge der theoretischen Logik (1928), English transaltion of the second 1936 edition, page 27 for the "Hilbert-style" presentation of the sentential calculus.

The axiom system is a simplification (due to Paul Bernays in 1926) of the axiom system of Alfred North Whitehead and Bertrand Russell, Principia Mathematica, 3 vols (1910-1913).
As you can see (page 27), the primitive conncetives are disjunction ($X \lor Y$) and negation ($\overline X$), while $\to$ is an abbreviation:

$X \to Y$ is to be merely a more convenient way of writing $\overline X \lor Y$.

Wiki's entry refers to the application to logical calculus of the more general concept of conservative extension meaning that:

if a formula $φ$ involving the new connective $\to$ [e.g.: $X \to (Y \to X)$] is rewritten as a logically equivalent formula $θ$ involving only negation and disjunction [i.e. as: $\overline X \lor \overline Y \lor X$], then $φ$ is derivable in the extended system if and only if $θ$ is derivable in the original system [i.e. from the axioms and rules of page 27-on].

Natural Deduction is a proof system with no axioms and with all the (main) conncetives as primitives.
It was developed by Gerhard Gentzen, a student of Paul Barnays, in the 1930s and it is based on previous researches of Hilbert's school.
A 10-axioms system with all the conncetives as primitive was used by Hilbert and Bernays already in 1922-23 (see Jan von Plato, Gentzen's proof systems: byproducts in a work of genius, Bull Symb Log (2012)).
Note. Propositional Natural Deduction is sound and complete proof system for tautologies, as well as Hilbert & Ackermann axiom system (with Modus Ponens and Substitution rules); thus, they can be seen as different "organizations" of the same logical principles: the tautologies of classical logic (and the same concept applies to the corresponding proof systems for e.g. Intuitionsitic Logic, with regards to the suitable semantics).

For a short overview, you can see The Development of Proof Theory.
For more details:

Paolo Mancosu, The Adventure of Reason: Interplay Between Philosophy of Mathematics and Mathematical Logic, 1900-1940, Oxford UP (2010), Parts I and II.

Understanding Hilbert's program


Reverse this array formula

Question: Array - from helpful comment by user Barry Houdini (great name too)

You can use PERCENTILE function in an array formula and get the result in one go, e.g. with data in A2:A29 try this array formula in B2
=MATCH(A2,PERCENTILE(A$2:A$29,{5,4,3,2,1}/5),-1)

confirm with CTRL+SHIFT+ENTER and copy down

I should like to reverse this; as for my purposes a LOW score is better.
It was not as simple as changing to {1,2,3,4,5}
Comment: @pnuts you should post this as an answer
Comment: Does `{1, 2, 3, 4, 5}` work if you change the [MATCH function's](http://office.microsoft.com/en-001/excel-help/match-function-HP010062414.aspx) `match_type` parameter from -1 (*descending*) to 1 (*ascending*)?
Comment: Thanks for your answer. It does, sort of - but now introduces errors on the smallest values that I didn't get with original array.
Answer: I believe that to reverse that array (?) formula, you will first have to reverse and shift the arrayed constants from 5→1 to 0→4. The MATCH` function's match_type parameter will also have to be changes from -1 (descending) to 1 (ascending).

The formula in D2 is,
=MATCH(A2,PERCENTILE(A$2:A$29,{0,1,2,3,4}/5), 1)

Fill down as necessary.
Two things to note:

I got the same results whether this was entered as an array formula (with Ctrl+Shift+Enter) or as a standard formula. I suspect that only a standard formula is actually necessary.
The MATCH function's match_type parameter's default is 1 so it can actually be left out of the formula altogether. e.g. =MATCH(A2,PERCENTILE(A$2:A$29,{0,1,2,3,4}/5))
Comment: Sorry @pnuts, Didn't see your comment before posting this. Will be deleting it as soon as the OP sees it (some vague extra info included).

Reverse this array formula


Function on $l^{\infty}$ that assigns sum to elements of $l^1$

Question: Disprove the following statement:
$$ \text{There exists an } f \in (l^{\infty})' \text{ such that } f(x) = \sum\limits_{n = 1}^{\infty} x_n \text{ for all } x \in l^1 \subset l^{\infty} $$
I think such a function would not be continuous, but how can I prove this?
Answer: Hint: Let $v_n$ be the sequence in $l^\infty$ that is $1$ in the first $n$ slots and $0$ elsewhere. Note that $f(v_n)= n.$
Comment: But $v_n$ doesn't converge to $(1, 1, 1, \ldots)$, right?
Comment: No, but it is bounded in $l^\infty.$
Answer: Such a functional cannot be continuous. Define $a_k$ the sequence
$$\left( \frac{1}{k}, \frac{1}{k+1}, \frac{1}{k+2}, \dots, \frac{1}{2k}, 0,0,0, \dots \right)$$
You have that $a_k \to 0$ in $l^{\infty}$, while
$$\lim_{k \to \infty} f(a_k) = \lim_{k \to \infty} \sum_{n=0}^k \frac{1}{k+n} = \log2 \neq 0$$
Answer: Suppose such a function exists. Let $k \in \mathbb{N}$ be arbitrary, and let $x$ be a sequence with $x_n = 1$ for $1 \leq n \leq 2k$ and $x_n = 0$ otherwise. Then
$$ ||f(x)|| = 2k > k = k \cdot 1 = k \cdot ||x||_{\infty} $$
so by definition, $f$ is not continuous, contradicting $f \in (l^{\infty})' = B(l^{\infty}, \mathbb{F})$.


Riemann curvature tensor identity proof

Question: Let $R_{abcd}$ be the Riemann curvature tensor defined by a torsion free and metric compatible covariant derivative.
Ultimately I am trying to prove that $R_{abcd} = -  R_{abdc}$
The prove in my textbook is as follows: (However I really am unsure as to what is happening here)
We know that $\nabla g_{bc} = 0$ , since we have been told that is metric compatible.
If we compute $\nabla_a\nabla_bg_{cd} - \nabla_b\nabla_ag_{cd} $ we have the following:
$$0 = \nabla_a\nabla_bg_{cd} - \nabla_b\nabla_ag_{cd} = R_{abc}^{\space \space \space \space \space  i}g_{id}  + R_{abd} ^{\space \space \space \space \space  i}g_{ci} =  R_{abcd} +R_{abdc}  $$
The part I am struggling to understand is where the term $ R_{abc}^{\space \space \space \space \space  i}g_{id}  + R_{abd} ^{\space \space \space \space \space  i}g_{ci}$ came from.
I am aware that $\nabla_a\nabla_dV_b - \nabla_d\nabla_aV_b = R_{adb}^{\space \space \space \space \space  i} V_i$ however I am still unsure as to where the part noted above comes from exactly.
Any help would be really appreciated.
Answer: I'm not very well versed, but I think the answer to your specific question follows from the metrinilic property of the metric as well the fact that the covariant derivative satisfies Leibniz's law; that is, it should be the case that
\begin{align*}
0 &= (\nabla_a\nabla_b- \nabla_b\nabla_a)g_{cd}\\
&= (\nabla_a\nabla_b- \nabla_b\nabla_a)(\textbf{e}_c\cdot \textbf{e}_d)\\
&= ((\nabla_a\nabla_b- \nabla_b\nabla_a)\textbf{e}_c)\cdot\textbf{e}_d + \textbf{e}_c\cdot((\nabla_a\nabla_b- \nabla_b\nabla_a)\textbf{e}_d)\\
&= (R_{abc}^{\space\space\space\space\space\space i}\textbf{e}_{i})\cdot\textbf{e}_d + \textbf{e}_c\cdot(R_{abd}^{\space\space\space\space\space\space i}\textbf{e}_{i})\\
&= R_{abc}^{\space\space\space\space\space\space i}g_{id} + R_{abd}^{\space\space\space\space\space\space i}g_{ci}\\
&= R_{abcd}+R_{abdc}\\
\end{align*}
Comment: Huh? What is $g_c$?
Comment: $g_c$ is the covariant basis of the tangent space.
Comment: You mean contravariant? $g$ is the metric tensor, so you need a different letter.
Comment: Sorry, yes the contravariant basis. Also I was not aware that a different letter is required, the text I refer to uses $\textbf{Z}_i$ as the contravariant basis and $Z_{ij}$ as the metric. I can change $g_c$ to $e_c$ in my answer if this is the typical notation?

Riemann curvature tensor identity proof


How do I tell UserManager.FindByNameAsync to include a relation?

Question: I am using ASP.NET Identity 2.2.0 with ASP.NET MVC 5.2.3 and Entity Framework 6.1.2.
I added a new property and its corresponding table to my database using ASP.NET Identity with Code First like so:
public class ApplicationUser
{
  [ForeignKey("UserTypeId")]
  public UserType Type { get; set;}
  public int UserTypeId { get; set;}
}

public class UserType
{
  [Key]
  public int Id { get; set;}

  public string Name { get; set; }
}

Now, from some action, when I call:
var user = UserManager.FindByNameAsync(userName);

It does get the user with the correct UserTypeId because that is a primitive, but it does not get the UserType property of the ApplicationUser class.
If I were not using this abstraction, I would either call LoadProperty<T> or the Include method in Entity Framework to include the navigational property or relation named Type (of type UserType) on the ApplicationUser class.
How do I do that with ASP.NET Identity's UserManager? I suspect the only way would be to override this method in my custom UserManager derived class and do it myself?
Comment: Have you tried making the `Type` property of your `ApplicationUser` class `virtual`?
Comment: Thank you. That did it. Many thanks. If you post that as an answer, please? :-)
Comment: So it wasn't able to proxy it?
Answer: With Entity Framework lazy loading, you need to ensure that your navigation properties are marked as virtual.
public class ApplicationUser
{
    [ForeignKey("UserTypeId")]
    public virtual UserType Type { get; set;}
    public int UserTypeId { get; set;}
}

Alternatively if you are unable/don't want to use lazy loading, then you can still use your context as you would any other entity:
var user = context.Users.Include(u => u.Type).Single(u => u.UserName == userName);

Comment: this does not apply anymore to Entity Framework Core. Lazy loading is disabled no matter if you use `virtual`.
https://docs.efproject.net/en/latest/querying/related-data.html#lazy-loading
Comment: @iberodev Well this question isn't tagged with EF Core so that's not an issue. In fact EF Core doesn't even support lazy loading yet, though it is on the roadmap, expect it to work in the next major release.
Comment: Perhaps overriding the user store users to include custom child entities will work, cases like one to many without navigationId column on the users table


proof in sequent calculus LK

Question: I was reading a book that uses sequent calculus (and calls than Natural deduction  )  and that mentions as rules
$$\frac{X,A\vdash B}{X\vdash A\to B}$$
and
$$
\frac{\begin{align}X &\vdash A\to B\\ Y& \vdash A\end{align}}{X,Y\vdash B}
$$
I wanted to rewrite proof from this book to an original sequent calculus proof in the original sequent calculus  (Gentzens LK system)
http://en.wikipedia.org/wiki/Sequent_calculus
http://gdz.sub.uni-goettingen.de/dms/resolveppn/?PPN=GDZPPN002375508
the rule $\to I$ above is in Gentzen's system FES or in modern language $\to R$
but the rule $\to E$ does not exist
How to derive $\to E$ in LK?
Answer: One method could be to use cut. (Forgive me, as far as I know, mathSE doesn't have a good way to type out sequent proof trees, so I'll just have to describe the tree.)
Suppose in your proof, you've derived both $X \vdash A \rightarrow B$ and $Y \vdash A$. Then using $\wedge R$ (and commutativity), you can derive $X, Y \vdash A \wedge (A \rightarrow B)$. Now, in a separate tree, start with the identities $A \vdash A$ and $B \vdash B$. Then, using $\rightarrow L$ (where $\Sigma$ and $\Delta$ are empty), we get $A, A \rightarrow B \vdash B$. By $\wedge L$ and contraction, you can then derive $A \wedge (A \rightarrow B) \vdash B$ (to do this, use $\wedge L_1$ to get $A \wedge (A \rightarrow B), A \rightarrow B \vdash B$, and then $\wedge L_2$ to get $A \wedge (A \rightarrow B), A \wedge (A \rightarrow B) \vdash B$; then use contraction). Finally, using cut on these two trees (where again $\Sigma$ and $\Delta$ are empty), you get $X, Y \vdash B$.
Now of course, by Cut Elimination, one could get a proof without using cut, but this proof tree is relatively simple because of the use of cut. Commutativity is needed if you want the order to be $X, Y$, though I imagine this wasn't a main issue. Contraction was used, but if you have an intensional conjunction in your system (as logics which reject contraction sometimes do), then the proof can be easily modified. So this proof still holds in quite a few Gentzen systems apart from LK.
Comment: Thanks this far, but the bit "A,A→B⊢B. By ∧L, you can then derive A∧(A→B)⊢B" is invalid
Comment: Ah, good point, thanks. I just fixed it. The proof now also involves contraction.
Comment: Thanks, how would a proof without contraction look?, also I am not sure about your comment about cut elimination, (i see it mentioned often) but as LK has no "remove connective" rule, how could you have a proof without cut? (i still don't understand this bit about LK)
Comment: The proof of cut elimination is rather involved, and it's a super important one in proof theory, so if you're interested you ought to have a look at some intro proof theory book. A proof without cut would probably be rather complex, which is why cut is so great.

As for a proof without contraction, some proof systems for instance add an intensional conjunction $\circ$ which has as its left rule: $A, B \vdash C$ implies $A \circ B \vdash C$, which is what I was trying to do originally with $\wedge L$. If something like this rule is allowed for $\wedge$, the proof will go through.
Comment: thank for the last comments as well
Answer: You can see Sara Negri & Jan von Plato, Structural Proof Theory (2001), Ch.8 : Back to Natural Deduction for a very useful discussion of the relation between :

derivability relation of single succedent sequent calculus, written $\Gamma \Rightarrow C$,

and

derivability relation of natural deduction, written $\Gamma \vdash C$.

Natural deduction rule $\rightarrow$-I :

$$\frac {\frac {[A]} B } {A \rightarrow B}$$

may be rewritten in "sequent form" as :

$$\frac {\Gamma \cup \{ A \} \vdash B } {\Gamma \vdash A \rightarrow B}$$

With this form, the comparison with sequent calculus rule $\rightarrow$-right is easy :

$$\frac {A, \Gamma \Rightarrow \Delta, B } {\Gamma \Rightarrow \Delta, A \rightarrow B}$$

With natural deduction rule $\rightarrow$-E, things are a little bit more complicated.
The "standard" rule :

$$ \frac{A \rightarrow B \quad \quad A}{B}$$

may be rewritten in "sequent form" (as in your question) as :

$$ \frac{\Gamma \vdash A \rightarrow B \quad \quad \Delta \vdash A}{\Gamma,\Delta\vdash B}$$

Negri & von Plato consider the $\rightarrow$-E rule in a more general form :
$$ \frac{\vdash A \rightarrow B\ \quad \Gamma \vdash A \quad B \vdash C}{C}$$
Now, we can see the connection with the sequent calculus rule $\rightarrow$-left :

$$\frac {\Gamma_1 \Rightarrow A \quad \quad B, \Gamma_2 \Rightarrow C } {A \rightarrow B, \Gamma_1, \Gamma_2 \Rightarrow C }$$
Comment: Dear Mauro - Of course, I see your fine contribution on MSE, especially with regard to matters logical. May I impose on you for some advice. I have to some extent studied logic, but as a self-studier, am always looking to enhance my understanding of things I've already looked at. In another comment I saw you recommended Kunen's "Foundations." And, no doubt you are familiar with Boolos & al. "Computability and Logic," where there is an emphasis on sequent calculus and Gentzen-type material. How important is sequent calculus? (cont)
Comment: Does it come up a lot, or is it more specialized, and perhaps I would be better off focusing on Kunen. Thanks and kind regards,
Comment: @Andrew - sequent calculus is quite "peculiar": more suited for proof theory. You can see some of it introduced into Jan von Plato, [Elements of Logical Reasoning](https://books.google.it/books?id=8RUOAwAAQBAJ&printsec=frontcover). Boolos & co. is a very good book, but it uses seq calc only for a small part and, IMO, this specific topic is not very clearly treated.
Comment: Thanks - That's great advice. Really appreciate it.

proof in sequent calculus LK


Não consigo centralizar o título

Question: Usando react-native e react-navigation, por alguma razão nada que tentei funcionou para centralizar o título.
Tentativas:

AlignSelf

export default class First extends React.Component {
    static navigationOptions = {
        title: 'Start',
        headerStyle: {
            backgroundColor: '#000080',
        },
        headerTintColor: '#ffffff',
        headerTitleStyle: {
            fontWeight: 'bold',
            fontSize: 20,
            alignSelf: 'center',
        },
    }

TextAlign

export default class First extends React.Component {
    static navigationOptions = {
        title: 'Start',
        headerStyle: {
            backgroundColor: '#000080',
        },
        headerTintColor: '#ffffff',
        headerTitleStyle: {
            fontWeight: 'bold',
            fontSize: 20,
            textAlign: 'center',
        },
    }

Ambos

export default class First extends React.Component {
    static navigationOptions = {
        title: 'Start',
        headerStyle: {
            backgroundColor: '#000080',
        },
        headerTintColor: '#ffffff',
        headerTitleStyle: {
            fontWeight: 'bold',
            fontSize: 20,
            alignSelf: 'center',
            textAlign: 'center',
        },
    }

Tentei também utilizar headerRight/headerLeft vazios, mas nada aconteceu.
Answer: O problema é que você não está definindo o display do cabeçalho. Para resolver esse problema basta adicionar flex:1. No caso, no seu código ficaria:
static navigationOptions = {
    title: 'Start',
    headerStyle: {
        backgroundColor: '#000080',
    },
    headerTintColor: '#ffffff',
    headerTitleStyle: {
        fontWeight: 'bold',
        fontSize: 20,
        flex: 1,
        textAlign: 'center',
    },
}

É possível ver o código funcionando com alinhamento a esquerda nesse link
Extraindo da documentação:

headerTitleStyle: if we want to customize the fontFamily, fontWeight and other Text style properties for the title, we can use this to do it.

Ou seja, em tradução livre, o headerTitleStyle utiliza as propriedades de estilo do Text.
Answer: Utiliza a propriedade headerTitleAlign = 'center'
Comment: Não publique código em links ou imagens. Código deve ser publicado como texto no corpo da resposta.

Não consigo centralizar o título