What is the problem with overdifferencing a long memory time series?

Question: Suppose I have a long memory time series and instead of using fractional differentiation I take a first difference.
What kind of problems am I going to run into? Is there any advantage to doing the fractional differentiation?
Answer: First differences remove all the long term memory whilst fractional differences preserve some of it. If, therefore, the long term memory is important for your intended application fractional differencing is the way to go. Chapter 5 of the book Advances in Financial Machine Learning discusses this in some detail.
For example, assume you want to predict a long term ( financial?) trend using a machine learning algorithm and you feed it first differences as training data, it will be extremely difficult for the algorithm to learn the trend as it isn't present in the data it's presented with; the algorithm is much more likely to learn to predict just one step ahead, and thereby "failing."
The above book suggests that this "over-differencing" is one reason why ML on (financial) time series is so often problematic. The book also, tentatively, suggests that this may be the reason why the Efficient Market Hypothesis holds such sway among financial academia, in that removing the "historical memory" from the data logically leads to the conclusion that future prices cannot be predicted from past prices. Any evidence that contradicts this belief is called an anomaly, e.g. momentum. However, fractionally differenced financial data show that trends and momentum do persist, whilst at the same time being stationary.
Comment: Can you please go into some details of how first differences removes "all the long term memory"?
Comment: What are the consequences of removing all the long memory though?


How to get properties of object in python

Question: class ClassB:
    def __init__(self):
        self.b = "b"
        self.__b = "__b"

    @property
    def propertyB(self):
        return "B"

I know getattr,hasattr... can access the property.
But why don't have the iterattr or listattr?
Expect result of ClassB object:
{'propertyB': 'B'}

Expect result of ClassB class:
['propertyB']

Thanks @juanpa.arrivillaga 's comment.
vars(obj) and vars(obj.__class__) is different!
Comment: To get the attributes of an object, use `vars(obj)`. Note, `property` objects belong to the *class* not the *instance*
Comment: And note, your `property` doesn't know that it will always return `B`.
Comment: @juanpa.arrivillaga if I know the name of property, I can get the value by `getattr`
Comment: whata if your property returns `random.random()`?
Comment: @juanpa.arrivillaga In that case, I think the value shall be same as `getattr(b_object, 'randomProperty')`.
Answer: Use the built-in vars as follows:
properties = []
for k,v in vars(ClassB).items():
    if type(v) is property:
        properties.append(k)

Using a list-comprehension:
>>> [k for k,v in vars(ClassB).items() if type(v) is property]
['propertyB']

Answer: To list propeties of a python Class you can use __dict__
Example
>>> class C(object):
x = 4

>>> c = C()
>>> c.y = 5
>>> c.__dict__
{'y': 5}

See this link for more examples and information - https://codesachin.wordpress.com/2016/06/09/the-magic-behind-attribute-access-in-python/


How can I resize an Android UI element during onLayout?

Question: I have a button class based on a LinearLayout that contains two TextViews, and I want the button always to be square (which I'm doing using onMeasure()), and the upper of the TextViews to resize automatically to fit the button.  I want the lower TextView to have fixed-size text, so it looks roughly like
|---------|
|         |
|  1 8 0  |
|         |
|   foo   |
|---------|

with "180" being as large as possible in the available space.
I'm calling a function in onLayout() called adjustTextSize():
private void adjustTextSize() {

    float height = mHeight - mTitleView.getMeasuredHeight() - 4 * mPadding - getPaddingTop() - getPaddingBottom(); //title text view

    int numberheight = (int) (height * 0.75);
    int extravertpadding = 0;//(int) (height * 0.125);

    mTitleView.setPadding(mPadding, 0, mPadding, mPadding);

    mNumberView.setTextSize(TypedValue.COMPLEX_UNIT_PX, numberheight);
    mNumberView.setPadding(mPadding, mPadding + extravertpadding, mPadding, mPadding + extravertpadding);

    if(mNumberView.getMeasuredWidth() > mWidth) {
        float reduction = mWidth / mNumberView.getMeasuredWidth();
        extravertpadding = (int) ((numberheight - height*reduction) / 2);
        numberheight = (int) (height*reduction);
        mNumberView.setTextSize(TypedValue.COMPLEX_UNIT_PX, numberheight);
        mNumberView.setPadding(mPadding, mPadding + extravertpadding, mPadding, mPadding + extravertpadding);
    }

    mNumberView.setTextSize(TypedValue.COMPLEX_UNIT_PX, numberheight);
    mNumberView.setPadding(mPadding, mPadding + extravertpadding, mPadding, mPadding + extravertpadding);

}

mWidth and mHeight are set in onLayout().
However, I have two initial problems: firstly, setting the text size to a certain pixel value makes the View somewhat bigger than the pixel value.  I want to work out how large to set the text height to fit the available space; three quarters seems to work OK but I would rather have an exact value.
The second problem is that the value of getMeasuredWidth() seems not to be changing after I've changed the text size.  Why not?
Answer: Answer to part 2:
It's necessary to call
mNumberView.measure(
    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
);

to tell the system to measure the view as though there were no constraints on its size.  After this has been called you can find out how large the view would be if space were no object and scale it down accordingly.


How do I go about telling Captcha that my form exists?

Question: I've got a drupal situation where I want to add reCaptcha to a custom form (built in an add-on module).  You can see from the captcha admin page that there is a list of forms that I can dynamically add captcha to... but my problem is that the form I created in the add-on does not appear in this list.
I'm sure I'm missing something (perhaps in the myform_block_info function?)
Does anyone know what hook I'm looking for?  Have a working example?
Answer: This was embarrassingly easy.  See that box at the bottom of the table?  Put your form ID in there.  "myform_form"


Converter letra minúscula em maiúscula sem a utilização da função "toupper()"

Question: Estou trabalhando em uma função para transformar em letra maiúsculas, porém o meu retomo está estranho. No final está dando o resultado abaixo:
Dados de entrada de palavra:

lucas

Programa está retornando:

LUCASÓÓÓÓÓÉð

    #include <stdio.h>
    #include <stdlib.h>

    char convmaiuscula (char texto [10]){
    int i,tam;
     for (i=0;i < strlen(tam);i++)
     {
          texto[i] = texto[i]-32;
     }
     printf("A palavra em maiusculas %s  " ,texto);
     }

     int main()
     {
     char palavra [10];
     printf ("\nDigite uma palavra: ");
     gets (palavra);
     convmaiuscula(palavra);
     }

Answer: Tem vários erros aí, sem falar a organização e nomenclatura ruim e o uso de coisas que não são necessárias.
Já no código principal se não reservar o espaço para o terminador da string vai corromper memória, e o pior que pode acontecer é funcionar, como acontece em vários casos, e vai achar que está certo.
Para pedir dados use scanf() ou fgets(), jamais gets(). Leia Como ler do stdin em C?.
Para verificar o fim da string veja se encontrou o terminador. Leia Sempre que vou varrer um string em C devo usar o "strlen()", certo?.
Esse tam não faz o menor sentido, parece um código aleatório que foi colocado ali.
Não corrigi o erro de não converter certo toda faixa de caracteres que pode ser digitado porque este é um erro conceitual, assim como a função diz que vai converter algo e acaba imprimindo esse algo também.
Mudei o retorno da função para compilar corretamente já que não há retorno. Se fosse para ter um retorno teria que codificar isso e provavelmente deveria tirar o printf(), mas não faz sentido retornar se a conversão é feita inplace no original.
#include <stdio.h>

void convmaiuscula(char texto[11]) {
    for (int i = 0; texto[i] != '\0'; i++) texto[i] -= 32;
    printf("A palavra em maiusculas %s", texto);
}

int main() {
    char palavra[11];
    printf("Digite uma palavra: ");
    scanf("%s10", palavra);
    convmaiuscula(palavra);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Obrigado pelo feedback Maniero, em relação a organização, ordenação e indentação do código acredito que foi por falta de experiencia ao uso do stackoverflow ao postar o código idem ao que esta no codeblock. Mais vou me atentar a isso nas proximas publicações. Obrigado
Comment: @ Maniero, acabei acrescentando no código uma condição onde o usuário corrige o problema de colocar uma letra maiúscula junto na plavra.
'
void convmaiuscula(char texto[11]) {
    for (int i = 0; texto[i] != '\0'; i++)
        if ((texto[i] >= 97) && (texto[i] <= 122)){
            texto[i] -= 32;
        }
    printf("A palavra em maiusculas %s", texto);
}
int main() {
    char palavra[11];
    printf("Digite uma palavra: ");
    scanf("%s10", palavra);
    convmaiuscula(palavra);
}
'
Comment: É uma boa pedida.


Middle 8 Confusion in "Yesterday"

Question: In my understanding the middle 8 should provide contrast to a song with verse/refrain form.  From the titles i've looked at, many middle 8's (and more generally, bridges) end on dominant harmony to welcome the verse section (which likely begins on the tonic) back.
In "Yesterday", not only does the middle 8 (beginning with "why she had to go") end with a ii-V-I progression, but the melody even outlines the tonic triad on the final bar (yes^5-ter-day^1-ay^5-ay-ay^4).
I would like to know the reason this works despite it being a contradiction (in my view) of the functional purpose of the bridge.
Thank you!
-286642
Comment: It does work. The variety might come from the different word-setting in the middle section: it's more emphatic. No quaver-runs. It's also kept alive by its form. The verses are seven bars long, and we're more used to 8-bar structures in pop music, so the "*Why - she -* " bar feels like a bar 8 of the preceding verse. So until we get back to the verse we have no idea whether we are on an even or odd-numbered bar and don't know how it'll turn out. And we probably don't care, but maybe it gives that section some tension that's lacking in the verses.
Comment: What is, in your view, the functional purpose of the bridge? If you placed dominant chord in the last measure of the bridge, the transition would be sharper and less melancholic. The words "now I long for yesterday" would sound more dramatic. Perhaps that wasn't the intention?
Comment: Please explain *1, *5, *4.
Comment: **Yesterday** clearly has a middle eight, so I think it's your working definition of Middle 8 that needs revision. Remember analysis isn't a formula - it's a grammar to give us a means to talk about music.
Comment: Rules are there to be broken. If you do something that's not what would be taught in a songwriting class, but it works, then you've innovated, congratulations!
Comment: @OldBrixtonian - I was thinking the 'why - she' is more like an anacrucis for the middle eight, which would then start on 'went'.
Comment: @Tim You mean start on "had (to go)", yeah?  (Listen to me saying "Yeah"! You'd think I was IN the Beatles!) Yes exactly. But that would mean V.1 had 7 bars and V.2 had 8, middle eight had 7, V.3 had 7... The shape is quite eccentric.
Comment: @OldBrixtonian - yeah yeah yeah. From what I remember. Been to sleep since then! Although I do know it better as 'Scrambled eggs'...
Answer: It obviously does work! What reason could there be that it doesn't? There is nothing in the 'rules' that says there must be a dominant before starting the next verse. True, there often is, but that's no criterion.
In fact, there are several songs where the middle eight/bridge ends on tonic, but the next verse starts somewhere different!
The reason so many songs finish on the dominant is straightforward - that leads the listener to expect a tonic, therefore probably the next verse (which often starts on tonic) will begin. But that's part of the art for songwriters - don't always give the listener what's expected. And that's most likely why those sort of songs stick in the memory.
Comment: Thank you so much, @Tim!  This is an interesting perspective, certainly
Answer: This is a terrific question, and could be stated more broadly: Does a bridge always have to end on the dominant function? If not, and it ends on its tonic, what makes it "work" since it's going against the tried and true formula? And those examples: Something, Help, Hey Jude, Back in the USSR, Love Me Do... let's think about how the "bridge" is being used in these.
The main thought I have, after reviewing these tunes, is that the bridges, while providing substantial contrast, also are acting a bit like a chorus, because of the perfect cadence resolution. For example, the "Something" bridge is highly contrasting and in a wildly different key. The "Yesterday" bridge is less contrasting, and feels like a "follow up" idea. "Help"'s bridge is clearly a chorus.
What I learned from this question, and from attempting to answer it, is that there is a gradation between bridge and chorus, and the masters are aware of this and use it, and I don't and I probably could. Thank you!
Answer: The middle 8 or bridge of a song is there to provide some contrast to the song but it doesn't have to end on a dominant even though it often does. In fact there are no rules governing how a bridge should end, it is up to the composer. In the case of the Beatles bridges end on the tonic fairly regularly:
Something
Help
Hey Jude
Back in the USSR
Love Me Do
I think the reason it works is the same reason consecutive verses that start and end on the tonic work. There is a resolution, it just happens within the section instead of as a lead in to the next one.
Answer: I would say this song doesn't have a middle eight, but that isn't really important, because you really just need a way to look at form.
The important thing to look for regarding traditional form is tonal center and phrase endings.
Let's look at a basic 32 bar song form...

32 Bar Form

A  : I ... V, 8 bars
A' : I ... I, 8 bars
B  : ? ... V, 8 bars (the bridge)
A' : I ... I, 8 bars

The song Over the Rainbow is an example. The A parts use the same basic melody and only the endings change. Ending on V for the first repeat propels the music into the second. When the melodic material is reused like this the technical term is a parallel period. The periodic structure allows for repeating the basic melodic material without it becoming played out.
The B middle eight also uses the period device - it ends on V - but it starts with some harmonic contrast. I indicate that with ? to show it could start from any number of chord. It will often be in a new key. It also is typical for B to get new, contrasting melodic material. With three repeats of the A melody the B section needs to provide something new in the 32 bar form.
So, in 32 bar form periodic structure (the alternate endings on V and I) propels the music forward and the B section provides harmonic and melodic contrast.
Now for the structure of Yesterday...

Yesterday

A :  I ... bVII7 IV I, 7 bars (1 + 2 + 2 + 2)

B : IV ... ii V7 I, 8 bars (4 + 4)

A A B
A B
A B
A coda

Setting aside the famous 7 bar length of the A section, the structure is basically 8 + 8 bars with A starting and ending on the tonic and B moving from some tonally contrasting area back to the tonic. This is a very common form where the two sections often just alternate like ||: A | B :||. Often there is melodic contrast between A and B. Unlike 32 bar form the endings are both on the tonic. But there is some similarity between the forms in that B starts with harmonic and melodic contrast.
You could sort of view this simple form as a kind of modified truncation of 32 bar form...
I (... V, I) ... I, ? (... V, I) ... I
...where the parenthesis show us dispensing with the periodic endings and strong melodic contrast in B. It's just 8 bars repeated where the second part starts on a new harmony and with some change in the melody.
Many songs in this simple 8 + 8 form will have a sort of 4 + 4 bar split of the A section with a pause on V which makes it feel like a miniature of periodic structure. I looked through my songbooks for an example that didn't do this and found the spiritual Steal Away. It's 8 + 8 bars, both A and B end on the tonic, B starts with the contrasting harmony and melody, no internal pauses on V.
In my opinion Yesterday doesn't use a middle 8. It's written in a different form. But it still exhibits the typical elements that delineate sections.
One final observation. The two endings in Yesterday offer a nice contrast even though both end on the tonic. The first one is a kind of "modal" ending using the bVII chord and a plagal cadence. Harmonically that contrasts with the B ending using a traditional ii V I. That's nice way to set the two sections apart but still follow the basic conventions of the form.
Comment: @286642, Old Folks at Home is an example - 8 + 8, both end on tonic, first 8 has a `V` pause in the middle. https://www.loc.gov/item/ihas.200000745/
Comment: Fourth measure, beat one, melody, rhythm, and harmony pause, there's a rest on beat 4 too
Comment: thank you for this answer @michaelcurtis.  Can you please elaborate on or provide an example of that pause on V in the A section you mention?
Comment: and by a V pause, what do you mean?  Pause in the melody?  In the rhythm?  Would you mind pointing me to a particular measure?
Answer: You're confusing 'what a middle 8 often does' with 'what a middle 8 HAS to do'.   Either re-define your private definition of a 'middle 8' or give this one a different label.   Preferably the first.

Middle 8 Confusion in "Yesterday"


Null GLMM Poisson underestimate the mean of the response variable. Is it indicative of poor fitting?

Question: I want to test the fixed and random effects of some covariates on a discrete variable with non negative values. In exploratory analysis I fitted a null Poisson GLM and an null Poisson GLMM. However, the GLMM underestimated the mean value of the response variable even after inclusion of fixed and/or random covariates. I also tried Bayesian approaches, zero-inflated models and negative binomial distributions but the "problem" remains.
Response variable mean: 0.7804
GLM intercept: 0.7803772
GLMM intercept: 0.6595108
Is the estimated intercept of the GLMM an indicative of poor fitting of the model?
summary(banco2$caes)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
 0.0000  0.0000  0.0000  0.7804  1.0000 12.0000

mod1 <- glm(caes ~ 1, poisson, banco2)
Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.2493  -1.2493  -1.2493   0.2381   6.5689
Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept) -0.24798    0.01078  -23.01   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for poisson family taken to be 1)
    Null deviance: 15304  on 11027  degrees of freedom
Residual deviance: 15304  on 11027  degrees of freedom
AIC: 27654
Number of Fisher Scoring iterations: 5

exp(mod1$coefficients[1])
(Intercept)
  0.7803772

(mod2 <- lmer(caes ~ 1 + (1 | setor), poisson, data = banco2))
Generalized linear mixed model fit by the Laplace approximation
Formula: caes ~ 1 + (1 | setor)
   Data: banco2
   AIC   BIC logLik deviance
 13575 13590  -6785    13571
Random effects:
 Groups Name        Variance Std.Dev.
 setor  (Intercept) 0.39817  0.63101
Number of obs: 11028, groups: setor, 559
Fixed effects:
            Estimate Std. Error z value Pr(>|z|)
(Intercept) -0.41626    0.02937  -14.18   <2e-16 ***

exp(fixef(mod2))
(Intercept)
  0.6595108

Answer: First I'll outline the logic behind why the exponentiation of the intercept is not sufficient, then I'll present a simple method of calculating the model estimate of the mean of the series.
When calculating the model-based estimate of the overall mean of the series in the random effects case, you have to not only exponentiate the log of the intercept, but take the variability of the observation-specific means into account. The individual observations do not all have mean equal to $\exp\{\text{intercept}\}$, due to that random effect term.   See for a not-altogether-dissimilar example the mean of the lognormal distribution, which is not just $\exp\{\text{the mean of the log of the lognormal variate}\}$.  The reason for this is that the mean of the transform is not the transform of the mean, unless the transform is linear or you got lucky with the transform, which you haven't with exponentiation.
If the categories are roughly the same size, the variance of the random effects can be used, using the same formula as in the link:
$$\mathbb{E}[\text{caes}] = \exp\{\mu + \sigma^2/2)$$
which translates to $\exp\{-0.41626 + 0.39817/2\} = 0.8048$.
In practice, you can use the predict function to predict the individual values on the response scale, then calculate the mean of the predictions and use that as the basis for your comparison.  That's what I would do.


how to convert string to decimal number while maintaining the decimal places in C#

Question: In C#, I have a custom string "12.10", when I convert it to decimal it is converted as 12.1 but I need it to be 12.10 in decimal also, please help
Below is the code
 string Value = nudEngineeringYears.Value + "." + nudEngineeringMonths.Value;
 selStaff.EngineeringExperience = Convert.ToDecimal(Value);

Comment: Is 12.1 not equal to 12.10?
Comment: I don't understand, a decimal 12.10 is exactly the same as a decimal 12.1
Comment: Leading and trailing zeroes are only a concern for a text representation. When it's in binary form (ie `decimal`) this has no meaning.
Answer: There is no difference between a decimal with value 12.1 or value 12.10.
If you want to display the decimal with 2 decimal place, specify a format string in ToString:
myDouble.ToString("0.00");

Answer: Well, as math stays
12.1 == 12.10 == 12.100 == ...

etc. However, you can change number's representation as a string by formatting:
  12.1.ToString("F2"); // <- return 12.10 (note "2" in formatting string)
  12.1.ToString("F3"); // <- return 12.100 etc.

Answer: There's no decimal 12.10, only 12.1.
What you're talking about when you say 12.10 is a possible representation of that value.
There's no difference between 12.10 and 12.1 when talking about numbers, but there's a difference between the string "12.10" and the string "12.1".
So don't confuse a number with its representation (which typically only matters in the front end).
If you want to format your value, you create a string representation of it. See Standard Numeric Format Strings.
Answer: You seem to confuse the internal/binary representation of a floating point number with its representation when converted to a string.
Internally a float has always about seven places of precission,
a double about 15 places of precission, a decimal even more.
Only when you format such a binary value to a string you may specify the number of places shown. For formatting use .ToString(format) with the format you need. in your case "F2"


List Item Responsive Issue in SAPUI5

Question: I would like to do responsive list item. How can I set the list items side by side. It's been always showing one under the other.
Here is my code;
<code>    <l:Grid
defaultSpan="L6 M6 S12"
class="sapUiNoMargin sapUiNoContentPadding"
hSpacing="5"
vSpacing="5">
<l:content>
    <List>
        <items>
            <!--TodoItem-->
            <CustomListItem type="Active" press="handlePanel3" class="todoListItemContainer">
                <Panel class="todoListItem">
                    <!--Content-->
                </Panel>
            </CustomListItem>

            <!--PlanItem and ActivityItem-->
            <CustomListItem type="Active" press="handlePanel3" class="todoListItemContainer">
                <Panel class="todoListItem">
                    <!--Content-->
                </Panel>
            </CustomListItem>

        </items>
    </List>
</l:content>
</code>

Here is the output image;
How can I put these items side by side. Grid's responsive layout properties is L6 M6 S12 but it's not working. Where I am doing a mistake ? Thanks for your suggestions.
Answer: Within the List the Grid layout will not apply, as the layout applies only on the immediate child controls. You can set the list items side by side in two ways

Remove the List & place the CustomListItem directly in the Grid control.

<code>                <!--PlanItem and ActivityItem-->
                <CustomListItem type="Active" press="handlePanel3" class="todoListItemContainer">
                    <Panel class="todoListItem">
                        <!--Content-->
                    </Panel>
                </CustomListItem>

    </l:content>
</l:Grid>
</code>
Use 2 Lists inside the Grid (As suggested by Marc)
<code><l:Grid
    defaultSpan="L6 M6 S12"
    class="sapUiNoMargin sapUiNoContentPadding"
    hSpacing="5"
    vSpacing="5">
    <l:content>
        <List>
            <items>
                <!--TodoItem-->
                <CustomListItem type="Active" press="handlePanel3" class="todoListItemContainer">
                    <Panel class="todoListItem">
                        <!--Content-->

                    </Panel>
                </CustomListItem>
            </items>
        </List>
        <List>
            <items>
                <!--PlanItem and ActivityItem-->
                <CustomListItem type="Active" press="handlePanel3" class="todoListItemContainer">
                    <Panel class="todoListItem">
                        <!--Content-->

                    </Panel>
                </CustomListItem>
            </items>
        </List>
    </l:content>
</l:Grid>
</code>

List Item Responsive Issue in SAPUI5


Problema ao abrir form dentro de panel

Question: Estou tentando abrir um form dentro de um panel no Delphi, mas aparentemente, o form abre com o mesmo tamanho do panel, mas fora dele.
Fiz assim...
UniForm1.Parent := UniPanel1;
UniForm1.Show;

Comment: Experimente setar a propriedade do form `Position`para `poOwnerFormCenter`
Comment: Não fez diferença...
Answer: Se usares uma Frame em vez de um Form podes fazer o que pretendes.
  tuaFrame:=TUniFrame1.Create(self);
  tuaFrame.Parent:=teuPainel;
  tuaFrame.Align:=alclient;
  tuaFrame.Visible:=true;

Answer: Resolvi com o seguinte código, além de trocar o WindowState de wsMaximized para wsNormal e o Position para poDefaultPosOnly.
UniForm1.Width := UniPanel1.Width;
UniForm1.Height := UniPanel1.Height;

Problema ao abrir form dentro de panel


A question related to the eigenvalues of a shift operator

Question: Suppose $\{e_k\}^{\infty}_{k=1}$ be an orthonormal basis for $\mathcal{H}$ (Hilbert space), and let $T$ be the shift operator defined by
$$Te_k=e_{k+1}$$
for $k=1,2,...$
I have shown that $T$ has no eigenvalues, and I'm currently working on computing the eigenvalues of $T^{*}$ (adjoint of $T$) and $\sigma(T)$ (spectrum of $T$) respectively.
So far, I've managed to show that $T^*$ is simply the operator defined by: $T^{*}e_k=e_{k-1}$, for $k=1,2,...$ with $Te_1=0$.
Also, if $\lambda$ is an eigenvalue of $T^*$ and $\phi$ a corresponding eigenvector such that $\phi=\Sigma^{\infty}_{i=1}\beta_ie_i$, then we can see that $\beta_2=\lambda \beta_1, \beta_3=\lambda^2 \beta_1, \beta_4=\lambda^3 \beta_1,...$
Clearly, $\lambda \neq 0$, for otherwise we get $\phi=0$, which is a contradiction. How can I make use of this information to compute the eigenvalues of $T^*$? Also, how do we compute $\sigma(T)$?
Any help or hint will be extremely useful. Thanks.
Answer: If $|\lambda| <1$ then $x=\sum \lambda ^{k} e_k \in H$ and $T^{*}(x)=\lambda x$. Hence $\lambda$ is an eigen value of $T^{*}$. I will let you check that ther are no other eigen values.
The spectrum of $T$ is the closed unit disk. It is contained in the closed unit disk because $\|T\|=1$. If $|\lambda| <1$ then there is no $x$ such that $Tx-\lambda x =e_1$: indeed, writing $x=\sum a_k e_k$ we get $a_k-\lambda a_{k+1}=0$ for all $k >1$. But then $a_{k+1}=\frac 1 {\lambda} a_k$. Iterating this we see that $\sum |a_k|^{2}=\infty$, a contradiction. This proves that $T-\lambda I$ is not invertible whenever $|\lambda| <1$, so $\sigma (T)=\{\lambda : |\lambda |\leq 1\}$.


Debug c++ no Visual Studio

Question: Instalei o Visual Studio C++ 2010 Express. Criei um projeto utilizando Win32 Console Application, adicionei um New Iten C++ File(.cpp) a esse projeto, mas na hora de rodar aparece o erro:
1>LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Answer: Você pode desabilitar a linkagem incremental para contornar o problema ou pode atualizar para uma versão mais moderna...
Project Properties
   -> Configuration Properties
       -> Linker (General)
          -> Enable Incremental Linking -> "No (/INCREMENTAL:NO)"

Comment: Já fiz isso mas não ta rodando,
Comment: antes aparecia o erro q coloquei na pergunta agora que fiz isso não aparece o erro, mas também não roda, a tela do console aparece e some  rápido
Comment: está aparecendo isso: The program '[736] Aula1.exe: Native' has exited with code 0 (0x0).
Comment: é meu primeiro programa em c++, quero q escreva "hello word"
Comment: #include

int main(int argc, char **argv)
{
    printf("Hello Word");
    return 0;
}
Comment: está assim: #include

int main(int argc, char **argv)
{
    printf("Hello Word");
 int espera;
 cin >> espera;
    return 0;
}
Comment: mas aparece isso: The program '[3924] Aula1.exe: Native' has exited with code 0 (0x0).
Comment: fiz isso: #include

main()
{
 char user[10];
 printf("Digite o nome do usuario: ");
 scanf("%s", &user);
}
Comment: e mostra isso: 'Aula1.exe': Loaded 'D:\Users\Sara\Documents\Visual Studio 2010\Projects\Aula1\Debug\Aula1.exe', Symbols loaded.
'Aula1.exe': Loaded 'C:\Windows\System32\ntdll.dll', Cannot find or open the PDB file
'Aula1.exe': Loaded 'C:\Windows\System32\kernel32.dll', Cannot find or open the PDB file
'Aula1.exe': Loaded 'C:\Windows\System32\KernelBase.dll', Cannot find or open the PDB file
'Aula1.exe': Loaded 'C:\Windows\System32\msvcr100d.dll', Symbols loaded.
The program '[1548] Aula1.exe: Native' has exited with code 0 (0x0).
Comment: Pode adicionar um breakpoint antes do return 0... ao iniciar o debug ele deve parar lá...

Debug c++ no Visual Studio


Insert a value for key into NSMutableArray

Question: I think this could be a very easy question for you.
But I have searched a lot and I don't know if I am very fool or I am using the wrong class (NSMutableArray).
I want to add an object for a specific key so that I can retrieve it later.
For example:
NSMutableArray *grisOcurrencias = [[NSMutableArray alloc] init];

[grisOcurrencias setValue:ocurrencia forKey:[NSString stringWithFormat: @"%f", pixelVal]];

But the array is not getting inserted in the array, if I do something like:
[grisOcurrencias addObject: ocurrencia]

The object is inserted.
Am I doing something wrong?
Other thing... I want to recover the object by its key, what method should I use?
Thanks a lot
Answer: You are looking for NSMutableDictionary, not NSMutableArray. Dictionaries store objects based on a key, whereas arrays store objects based on an index.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];

[dict setObject:something forKey:@"Some Key"];

// ... and later ...

id something = [dict objectForKey:@"Some Key"];

Comment: You are GOD ! Thanks I was getting confused, because a saw a Object with some methods whith the "Key" word like SetValue forKey, well, thanks friend :D
Answer: You want to use an NSDictionary.
NSMutableDictionary *grisOcurrencias = [[NSMutableDictionary alloc] init];

[grisOcurrencias setObject:ocurrencia forKey:[NSString stringWithFormat: @"%f", pixelVal]];

And then to retrieve the object:
id object = [grisOcurrencias objectForKey:[NSString stringWithFormat: @"%f", pixelVal]];

And array is an ordered collection of items, where each item has an integer index. A dictionary is a collection of objects, each of which is set and retrieved according to a key, just like a real dictionary, with the keys being words and the values (objects) being definitions.


javascript not working to create divs inside of another div

Question: I am trying to create 10 divs when a button is clicked, however nothing is happening. I think the issue is with my javascript, but nothing is shown in the console. What am I doing wrong? And what can I do to fix it? Any help would be greatly appreciated.
HTML
<!DOCTYPE html>

        <title>
        Space Invaders
        </title>

        <link href="style.css" rel="stylesheet" type="text/css" />

Start Game

Javascript
var row1 = [];
$(document).ready(function()
{
    $('#startbtn').click(function(){
        for (var i = 0; i<9; i++)
    {
        row1[i] = document.createElement('div');
        row1[i].className = 'grid';
        document.getElementById('game').appendChild(row1[i]);
    }
    });
});

CSS
#startbtn
{
    height: 60px;
    width: 100px;
    border-radius: 5px;
    background-color: #69D2E7;
    text-align: center;
    color: #000000;
    font-family: Arial;
    opacity: 0.5;
    margin: auto;
}
#game
{
    display: none;
    margin: auto;
}
#game2
{
    display: none;
    margin: auto;
}
.grid
{
    display: inline-block;
    background-color: #000000;
    width: 20px;
    height: 20px;
    border-radius: 2px;
}

Comment: Your code works fine. You can't see the added DIVs because `#game` has `display: none`.
Comment: @Barmar if you added that as an answer i would accept it.
Answer: Working example:
JS FIDDLE
why dont you use jquery to create DOM element and append?
var row1 = [];
$(document).ready(function()
{
    $('#startbtn').click(function(){
        for (var i = 0; i<9; i++)
    {
       var div = $("
").addClass("grid");
       div.appendTo($("#game"));
    }
    $("#game").show();
    });
});

CSS
#game
{
    margin: auto;
}

Comment: You're not specifying the class of the new DIVs. Other than that, it's equivalent to the original code, so I don't see how it could fix whatever problem he has.
Answer: You need to unhide the game DIV:
$('#startbtn').click(function(){
    for (var i = 0; i<9; i++) {
        row1[i] = document.createElement('div');
        row1[i].className = 'grid';
        document.getElementById('game').appendChild(row1[i]);
    }
    $("#game").show();
});

DEMO


Why is there a separate symbol for partial derivatives?

Question: The concept of a partial derivative is very simple: for a multivariate function $f$, the partial derivative of $f$ with respect to a single variable $x$ is computed by treating the other variables as constants and differentiating $f$ with respect to $x$.
As a student of Calculus I, I do not fully understand the need for a $\partial y / \partial x$.  As far as I know, the special "partial" $\partial$ does not change the process of the computation.  In addition, I have become confused as the calculus of my physics course increases in difficulty.
Take a three-dimensional position vector $\vec r = \vec x + \vec y + \vec z$ and an electric field vector $\vec E$ that varies with $\vec r$.  If $V$ denotes electric potential, then $\Delta V = -\int \vec E\cdot d\vec r$.
On a review sheet that my teacher created, he expanded this, saying

$$\begin{align}
E_x &= -\partial V / \partial x \\
E_y &= -\partial V / \partial y \\
E_z &= -\partial V / \partial z
\end{align}$$

Given the standard setup of a partial derivative, I see no issue with this.  However, our standard formula chart reads that

$$E_x = -\frac{dV}{dx}$$

and this genuinely confuses me since our calculations of field potential are almost always expanded to multiple dimensions.
What is the need for a $\partial f / \partial x$ notation, and why are sources (at least in physics, the only application of partial derivatives I encounter during the course of the school day) inconsistent?
Comment: [This question](http://math.stackexchange.com/q/320228/81360) seems relevant.
Comment: Using $\partial$ automatically implies there are more than one variable in the differentiated function. It is just helpful.
Comment: @Omnomnomnom I just had a look at the question you have indicated:  the simple example given by Hurkyl is striking.
Comment: I think the only reasonable way to answer this question is to give an example where using $d$ vs. $\partial$ makes a difference.  Unfortunately, I'm having trouble coming up with a "natural" one.  None of the answers so far use examples in this way.
Comment: Thanks so much @Omnomnomnom !!!
Comment: I agree @JeanMarie I left I comment on it
Answer: Alan Turing said:

The Leibniz notation $\mathrm dy/\mathrm dx$ I find extremely difficult to understand in spite of it having been the one I understood best once! It certainly implies that some relation between $x$ and $y$ has been laid down e.g.
  $$ y = x^2 + 3x $$

Whenever the notation $\partial z/\partial x$ is used, there exists some sort of implicit dependency of $z$ w.r.t. $x$, e.g. $z = f(x,y)$. The $\partial$ symbol is used since in this case only the dependency of $z$ w.r.t. $x$ is considered. If there is another implicit dependency $y = g(x)$, $\partial z/\partial x$ does not take that into account (hence the name partial derivative), while $\mathrm dz/\mathrm dx$ does, and it is called the total derivative of $z$ w.r.t. $x$.
Comment: I always thought that *partial* meant that the derivative was partial to a certain direction.
Answer: There is no one forcing you to use $\partial$ for partial derivatives, however it is recommended because it helps avoid confusion in expressions where both partial and ordinary derivatives are present.
Answer: I would just like to add that I've done a bit more research and that the distinction between $\partial t$ and $dt$ seems vital for formulae like
$$d\left( f\left( x,y,\cdots\right)\right) = \frac{\partial f}{\partial x}dx + \frac{\partial f}{\partial y}dy + \cdots$$
and
$$\begin{align}
\frac{dz}{dx} &= \frac{dz}{dy} \frac{dy}{dx} \qquad \mathrm{\left( chain \ rule\right)} \\
\frac{\partial z}{\partial x} &\neq \frac{\partial z}{\partial y} \frac{\partial y}{\partial x}
\end{align}$$
like in Hurkyl's example
$$\frac{\partial z}{\partial x} \frac{\partial x}{\partial y} \frac{\partial y}{\partial z}
= \left( 5\right) \left( -\frac{3}{5}\right) \left( \frac{1}{3}\right)
= -1$$
if $z = 5x + 3y$


Uninstall BIDS 2008

Question: I had successfully installed BIDS 2008 on my machine. I uninstalled it,  and now need to re-install it.
When going through the setup,  Business Intelligence Development Studio has gray check mark in the Feature Selection screen.  Visual Studio 2008 is not installed on my machine.  I don't see any references to BIDS 2008 in the add/remove programs.  Yet the installer seems to think it's there.
Does anyone know how I can COMPLETELY remove BIDS to re-install it?  Is it a registry file somewhere?   Any help is appreciated.
Answer: My attempts to uninstall Business Intelligence Development Studio 2008 from a machine with SQL Server 2008 Express Edition ended with success after following the link:
https://support.microsoft.com/en-us/help/955404/sql-server-2008-installation-fails-when-you-try-to-install-sql-server
and manually running the command:
<code>setup.exe /ACTION=uninstall /FEATURES=BIDS /INSTANCENAME=SQLEXPRESS
</code>
After uninstalling the previous instance of BIDS, the installer allowed me to select/check BIDS and other features.

Uninstall BIDS 2008


AgGrid Excel Export Stripping Leading 0's

Question: I am trying to export a grid to Excel. Values in the model cells are not exported correctly. Instead of exporting as
0001458
0008451
0008451

They display as:
1458
8451
8451

The actual values coming from the API returning the data for model is coming as string, so:
'0001458'
'0008451'
'0008451'

Example: https://stackblitz.com/edit/ag-grid-react-hello-world-r3sjfn?file=index.js
import React, { useState, useEffect, useRef } from 'react';
import { render } from 'react-dom';
import { AgGridReact } from 'ag-grid-react';

import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(
      [
        { make: 'Toyota', model: '0001458', price: 35000 },
        { make: 'Ford', model: '0008451', price: 32000 },
        { make: 'Porsche', model: '0085452', price: 72000 },
      ]
    );
  }, 300);
});

const App = () => {
  const [rowData, setRowData] = useState([]);
  const initData = useRef([]);
  const gridApi = useRef();

  const [columnDefs] = useState([
    { field: 'make' },
    { field: 'model' },
    { field: 'price', editable: true },
  ]);

  const gridReady = (params) => {
    gridApi.current = params?.api;
  }

  useEffect(() => {
    let data = myPromise
      .then((data) => {
        console.log(data);
        setRowData(data);
        initData.current = JSON.parse(JSON.stringify(data));
      });
  }, []);

  const exportExcel = () => {
    gridApi.current.exportDataAsExcel();
  }

  return (

      <button onClick={exportExcel}>Back to original</button>

        <AgGridReact rowData={rowData} columnDefs={columnDefs} onGridReady={gridReady}></AgGridReact>

  );
};

Comment: Please check out the following: https://ag-grid.com/javascript-data-grid/excel-export-data-types/
Comment: Did try that, didnt help unfortunately.
Answer: The answer is https://www.ag-grid.com/react-data-grid/excel-export-data-types/
This is how you can implement Thomas Renger's comment
Define your types
const excelStyles = useMemo(() => [
  {
    id: 'stringType',
    dataType: 'String',
  },
  // ...
]);

Pass as a prop
<AgGridReact
  ref={gridRef}
  rowData={rowData}
  excelStyles={excelStyles}
/>

Define a value getter method (Important)
const valueGetter = (params) => {
  return params.data.model;
};

Modify your column definitions like that
const [columnDefs, setColumnDefs] = useState([
  { field: 'make' },
  {
    field: 'model',
    valueGetter: valueGetter,
    field: 'Model (String)',
    cellClass: 'stringType',
  },
  { field: 'price', editable: true },
]);

Result

Plunker: https://plnkr.co/edit/BK0WN7mLOcm0kzpk?preview


Use Timeago date format for less than 24h ago only

Question: I would like to use the Timeago module as a date format. However, when the time ago has exceeded 24h, I would like it to show another format (e.g. 4 Feb, 2013) much like Twitter or Dribbble use.
I tried to tweak the code, but my skills let me down :/
Is there possibly a better module for this cause? Or do I have to make my own?
I found this code that shows how I want it to work, however I have no idea how to implement this to drupal.
Any help is appreciated, thanks.
Comment: This would be a great feature request for the Timeago module if it's not already been requested.
Comment: @beth I just looked through the issues for the module and it doesn't seem to have been requested. I will create an issue tomorrow (no time for it today) unless you want to do it :)
Comment: What tweaks did you attempt to do to the code? Where is this date appearing on your site?
Comment: @beth I tried to make the code in the jquery.timeago.js file only run if the seconds variable was less than 86400 (24h). However, I have to make the whole module to not run, otherwise it won't show the other formats, because it is still overriding them.
Comment: I created an issue that can be found [here](http://drupal.org/node/1907158)
Comment: This might help - [Display Suite : time since](http://drupal.stackexchange.com/questions/78404/countdown-with-views/78409#78409)
Comment: If I recall correctly, the PrivateMsg module has that feature.
Answer: Do users really sit on a page for a long enough time, that these dates need to be updated via javascript? Most of them will click on something and end up reloading the whole page at some point. So perhaps, a php solution is an option too?
You could achieve the php solution by using the Custom Formatters module.
If you create a new php type custom formatter, with the following code (make sure it's a datestamp type):
<code>$element = array();
foreach ($variables['#items'] as $delta => $item) {
  $unixstamp = $item['value'];
  $time_since = mktime() - $unixstamp;
  if ($time_since < 86400) {
    $date_str = format_interval($time_since);
  }
  else {
    $date_str = format_date($unixstamp, 'custom', 'jS F Y');
  }

  $element[$delta] = array(
    '#type' => 'markup',
    '#markup' => $date_str,
  );
}
return $element;
</code>
When creating the formatter, make sure you select field type 'datestamp'. Once the formatter is created, then in the manage display tab of your content type, set the field to use this formatter.
If you don't have your date stored as a separate field, you might be able to apply the custom formatter to the node modified time, by installing the Display Suite module.
If you don't want to use any of these modules but want to hack some php into your theme or something, you can still use the same logic above with format_interval and format_date functions.
Hope that can help.
Answer: Wherever it is that you are using timeago to show a formatted date, will a snippet like the one below do the trick for you?
<code>// Assume $timestamp has the raw Unix timestamp that I'd like to display using
// the "timeago" date format supposing it is within the last 24 hrs and another date
// format - "my_date_format" otherwise.
$rule = ((REQUEST_TIME - $timestamp) <= 24 * 60 * 60);
$fallback = format_date($timestamp, 'my_date_format');
return ($rule ? timeago_format_date($timestamp, $fallback) : $fallback);
</code>
Comment: Is this supposed to be applied to a .module file? I can't really figure out where to put it.
Comment: You would need to find where in the timeago .module file the new dates are applied and then you could attempt what @Amarnath was suggestion, or something similar, like an if statement wrapping around the actual application of the new dates and the condition being some math saying if the date is greater than 24 hours ago, do this.
Answer: Create A MyCustom Module
myCustom.module contains
<code>/**
 * Implements hook_date_formats().
 */
function myCustom_date_formats() {
  $formats = array('g:i a', 'H:i', 'M j', 'j M', 'm/d/y', 'd/m/y', 'j/n/y', 'n/j/y');
  $types = array_keys(myCustom_date_format_types());
  $date_formats = array();
  foreach ($types as $type) {
    foreach ($formats as $format) {
      $date_formats[] = array(
        'type' => $type,
        'format' => $format,
        'locales' => array(),
      );
    }
  }
  return $date_formats;
}

/**
 * Implements hook_date_format_types().
 */
function myCustom_date_format_types() {
  return array(
    'myCustom_current_day' => t('MyCustom: Current day'),
    'myCustom_current_year' => t('MyCustom: Current year'),
    'myCustom_years' => t('MyCustom: Other years'),
  );
}

/**
 * Formats a timestamp according to the defines rules.
 *
 * Examples/Rules:
 *
 * Current hour: 25 min ago
 * Current day (but not within the hour): 10:30 am
 * Current year (but not on the same day): Nov 25
 * Prior years (not the current year): 11/25/08
 *
 * @param $timestamp
 *   UNIX Timestamp.
 *
 * @return
 *   The formatted date.
 */
function myCustom_format_date($timestamp) {
  if ($timestamp > ((int)(REQUEST_TIME / 3600)) * 3600) {
    return t('@interval ago', array('@interval' => format_interval(abs(REQUEST_TIME - $timestamp), 1)));
  }
  if ($timestamp > ((int)(REQUEST_TIME / 86400)) * 86400) {
    return format_date($timestamp, 'myCustom_current_day');
  }
  if ($timestamp > mktime(0, 0, 0, 1, 0, date('Y'))) {
    return format_date($timestamp, 'myCustom_current_year');
  }
  return format_date($timestamp, 'myCustom_years');
}
</code>
Create myCustom.install & it contains
<code>/**
 * @file
 * Install file for myCustom.module
 */

/**
 * Implements hook_install().
 */
function myCustom_install() {
  // Define default formats for date format types.
  variable_set("date_format_myCustom_current_day", 'g:i a');
  variable_set("date_format_myCustom_current_year", 'M j');
  variable_set("date_format_myCustom_years", 'n/j/y');
}

/**
 * Implements hook_uninstall().
 */
function myCustom_uninstall() {
  variable_del('date_format_myCustom_current_day');
  variable_del('date_format_myCustom_current_year');
  variable_del('date_format_myCustom_years');
}
</code>
Usage :
<code>echo myCustom_format_date(1392532844);
</code>
Comment: Hello. Could you post an explanation? This site is meant for *answers*, not for *code*.
Comment: Yes ofcourse. I will care it for further answer.


What is the $n^\text{th}$ perfect power, $P(n)$?

Question: Let $P(n)$ denotes the $n^\text{th}$ perfect power of natural numbers (in ascending order without repetition).
So, $P(1)=1, P(2)=4, P(3)=8, P(4)=9, P(5)=16, P(6)=25, P(7)=27, P(8)=32, \dots$.
Is there any formula to find $P(n)$  for a natural number $n$? Say what is $P(75)$?
I think there is no explicit formula for $P(n)$ since the sequence $P(1), P(2), P(3), \dots$ has no common difference of any order, has no common ratio, and has no pattern in the slopes.
What I mean is; if we sketch the line graph $y=P(x)$, then $P'(x)$ at $x=n$ is always positive, but not always increasing nor always decreasing.
Any help to find the $n^\text{th}$ perfect power would be appreciated. THANKS!
Comment: https://oeis.org/A001597
Comment: it's always at least $2^x$ when $n\geq T(x)$ where the function is the x-th triangular number.
Answer: In this paper, the author gives the asymptotic formula
$$
P(n) = n^2 - 2n^{5/3} - 2n^{7/5} + \frac{13}{3}n^{4/3} - 2n^{9/7} + 2n^{6/5} - 2n^{13/11} + o(n^{13/11})
$$


String.Contains() vazio retornando verdadeiro

Question: Por que ao utilizar o Contains("") em uma string não vazia retorna verdadeiro?
Exemplo
if ("MinhaString".Contains(""))
{
    Console.WriteLine("String contém vazio");
}

Answer: Podemos dizer que é uma convenção. A ideia é que toda string tem uma string vazia.
Uma string é composta no mínimo de uma string vazia, e provavelmente outros caracteres em adição ao vazio.
Isto deveria ser verdadeiro ou falso?
"" == ""

Imagino que todos aceitam como verdadeiro.
O Contains() pergunta se o "nada" está dentro de uma string e está. Consideramos que todo caractere está empermeado por um "nada". Mesmo que não tenha caracteres o nada está lá presente.
Então:
"abc" == "abc" + ""

Certo?
Ambos retornam que tem nada, porque ambos tem. O primeiro você não vê que tem, o segundo você vê. Só porque você não vê não quer dizer que não está lá.
Poderia perguntar porque não consideraram que nada não existe e nunca está em lugar algum. E eu te perguntaria que ganho espera ter com isto?
Se não tem o que comparar que resultado daria?
Até o null é igual a null. Então seria inconsistente.
Uma coisa é você perguntar se uma string tem um vazio, outra bem diferente é perguntar se ela é toda vazia, então
"abc" != ""

Coloquei no GitHub para referência futura.
Esta pergunta quer saber se todos os caracteres são iguais, até o vazio. E o vazio é igual, mas os outros 3 visíveis só tem em uma string, há pelo menos uma diferença entre as duas strings, isto faz tudo ser diferente.
O == é como se fosse um && em todos os caracteres, já o Contains() é como se fosse um ||. Se ele achar uma ocorrência da agulha no palheiro já é tudo verdadeiro, e o vazio está presente em toda string, por definição, então sempre retornaria verdadeiro.
Comment: Não entendi a sua pergunta de que se ""=="" deve ser verdadeiro ou não. Poderia explicar como isso se encaixa melhor no contexto da minha pergunta? Pois se eu testar "MinhaString"=="" var retornar falso.
Comment: @PabloTondolodeVargas melhorou?
Comment: @Maniero está parecendo mais uma discussão de ordem filosófica ("Só porque você não vê não quer dizer que não está lá."), mas resumidamente eu entendo que: toda string contém "nada" por convenção.
Comment: @PabloTondolodeVargas é meio metafísico :D


Could wordpress theme css/js conflict with Wordpress visual mode posting?

Question: As I understand it when posting using visual mode in wordpress hitting enter inserts a line break, or wraps the previous text in paragraph tags.  Also, you have the added options of highlighting text and select header or pre or paragraph.
The problem I am having is that, in visual mode, when I hit enter or when I select a block of text and select paragraph no tags are being inserted at all.
Example.

sample text

sample text

sample text
sample text

The results of the above are obvious, I get two correctly formatted 'sample texts' and then I see the two lines of text that are supposed to be paragraphs as 'sample textsample text'.  Nothing I have done short of manually adding the tags in the text (html) editor has fixed this.
I am working from a theme that I have built myself so I was wondering if anything I did in the theme could interfere with that.
Additional note: in the content-page.php I am using the_content(); not the_excerpt(); so that is not the issue.
Answer: After more research I found this php function in the underscores base theme that I had built from was stripping the paragraph tags.
remove_filter ('the_content', 'wpautop');

I removed that from functions.php and the formatting returned to normal.


Edit search form with a module

Question: I have made and installed a new module, called searchIcon.
The problem is I want to edit the default value "Search" next to the search form.
I tried the code below, but it does not seem to work.
<?php

/*
 * Implementation of hook_form_alter()
 */

function searchIcon_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'search_block_form') {
        $form['actions']['submit']['#value']= 'TESTSEARCH';
    }
}

?>

How could I change the text "search" to e.g. "TESTSEARCH"?
Comment: Module und theme machine names must only contain lower case letters and underscores.
Comment: Perhaps a stupid question, but you have also enabled the module right?
Comment: That code should work, supposing that it is placed in the *searchIcon.module* file. Are you getting any error?
Comment: It is. However, it doesn't work. FYI. This is in my searchIcon.info.yml :

name: Search Icon
type: module
description: 'This module replaces search value by an icon'
version: VERSION
core: 8.x
configure: searchIcon.form
Comment: Uppercase characters only cause issues with `hook_update_N()`, not other hooks. While it's preferable to avoid uppercase characters, they would not cause issues in this specific case.
Answer: Okay, I think there must have been a typo somewhere or something, but anyway, this setup works:
info yaml:
name: Search Icon
description: This module replaces search value by an icon.

type: module
core: 8.x
core_version_requirement: ^8 || ^9

module:
<?php

/*
 * Implementation of hook_form_alter()
 */

function searchIcon_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'search_block_form') {
        $form['actions']['submit']['#value']= 'TESTSEARCH';
    }
}

Please note that the module does not work as intended yet, the value should be replaced by an html decimal code for the desired icon.

Edit search form with a module


Nest aggregation results are null however there are data in the debugger

Question: I'm working on aggregations in NEST, so far everything has worked well, but now when I try to access nested fields through .children the result is null, however the debugger is showing the data correctly.

If I post this query through postman I get the following results:
{
    "took": 50,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 9,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    },
    "aggregations": {
        "filter#CollarSize": {
            "meta": {},
            "doc_count": 9,
            "nested#VariantsProperties": {
                "doc_count": 53,
                "sterms#CollarSize": {
                    "doc_count_error_upper_bound": 0,
                    "sum_other_doc_count": 0,
                    "buckets": [
                        {
                            "key": "CollarSize",
                            "doc_count": 39,
                            "sterms#banana": {
                                "doc_count_error_upper_bound": 0,
                                "sum_other_doc_count": 0,
                                "buckets": [
                                    {
                                        "key": "15",
                                        "doc_count": 7
                                    },
                                    {
                                        "key": "16",
                                        "doc_count": 7
                                    },
                                    {
                                        "key": "17",
                                        "doc_count": 6
                                    },
                                    {
                                        "key": "18",
                                        "doc_count": 6
                                    },
                                    {
                                        "key": "LAR",
                                        "doc_count": 2
                                    },
                                    {
                                        "key": "MED",
                                        "doc_count": 2
                                    },
                                    {
                                        "key": "SML",
                                        "doc_count": 2
                                    },
                                    {
                                        "key": "X.L",
                                        "doc_count": 2
                                    },
                                    {
                                        "key": "XXL",
                                        "doc_count": 2
                                    },
                                    {
                                        "key": "15.5",
                                        "doc_count": 1
                                    },
                                    {
                                        "key": "16.5",
                                        "doc_count": 1
                                    },
                                    {
                                        "key": "XXXL",
                                        "doc_count": 1
                                    }
                                ]
                            }
                        },
                        {
                            "key": "Colour",
                            "doc_count": 14,
                            "sterms#banana": {
                                "doc_count_error_upper_bound": 0,
                                "sum_other_doc_count": 0,
                                "buckets": [
                                    {
                                        "key": "Blue",
                                        "doc_count": 7
                                    },
                                    {
                                        "key": "White",
                                        "doc_count": 7
                                    }
                                ]
                            }
                        }
                    ]
                }
            },
            "sterms#CollarSize": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": []
            }
        }
    }
}

Is there a way to get inside the child "CollarSize" ? I've tried different combinations with .nested, .children, .terms, .filter however none of these seems to work.
Answer: You can get "CollarSize" terms and "banana" terms for each with
var response = client.Search<object>(/** your query here **/);

var collarSizeSignificantTermsAgg = response.Aggregations.Filter("CollarSize").Nested("VariantsProperties").Terms("CollarSize");

foreach(var bucket in collarSizeSignificantTermsAgg.Buckets)
{
    Console.WriteLine(bucket.Key);

    var bananaSigTerms = bucket.Terms("banana");

    foreach(var subBucket in bananaSigTerms.Buckets)
    {
        Console.WriteLine($"key: {subBucket.Key}, doc_count: {subBucket.DocCount}");
    }
}

which prints
CollarSize
key: 15, doc_count: 7
key: 16, doc_count: 7
key: 17, doc_count: 6
key: 18, doc_count: 6
key: LAR, doc_count: 2
key: MED, doc_count: 2
key: SML, doc_count: 2
key: X.L, doc_count: 2
key: XXL, doc_count: 2
key: 15.5, doc_count: 1
key: 16.5, doc_count: 1
key: XXXL, doc_count: 1
Colour
key: Blue, doc_count: 7
key: White, doc_count: 7

Here's a full example, using InMemoryConnection to stub the response
private static void Main()
{
    var defaultIndex = "my_index";
    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

    var json = @"{
    ""took"": 50,

    ""timed_out"": false,
    ""_shards"": {
        ""total"": 1,
        ""successful"": 1,
        ""skipped"": 0,
        ""failed"": 0

    },
    ""hits"": {
        ""total"": {
            ""value"": 9,
            ""relation"": ""eq""

        },
        ""max_score"": null,
        ""hits"": []

    },
    ""aggregations"": {
        ""filter#CollarSize"": {
            ""meta"": { },
            ""doc_count"": 9,
            ""nested#VariantsProperties"": {
                ""doc_count"": 53,
                ""sterms#CollarSize"": {
                    ""doc_count_error_upper_bound"": 0,
                    ""sum_other_doc_count"": 0,
                    ""buckets"": [

                        {
                        ""key"": ""CollarSize"",
                            ""doc_count"": 39,
                            ""sterms#banana"": {
                            ""doc_count_error_upper_bound"": 0,
                                ""sum_other_doc_count"": 0,
                                ""buckets"": [

                                    {
                                ""key"": ""15"",
                                        ""doc_count"": 7

                                    },
                                    {
                                ""key"": ""16"",
                                        ""doc_count"": 7

                                    },
                                    {
                                ""key"": ""17"",
                                        ""doc_count"": 6

                                    },
                                    {
                                ""key"": ""18"",
                                        ""doc_count"": 6

                                    },
                                    {
                                ""key"": ""LAR"",
                                        ""doc_count"": 2

                                    },
                                    {
                                ""key"": ""MED"",
                                        ""doc_count"": 2

                                    },
                                    {
                                ""key"": ""SML"",
                                        ""doc_count"": 2

                                    },
                                    {
                                ""key"": ""X.L"",
                                        ""doc_count"": 2

                                    },
                                    {
                                ""key"": ""XXL"",
                                        ""doc_count"": 2

                                    },
                                    {
                                ""key"": ""15.5"",
                                        ""doc_count"": 1

                                    },
                                    {
                                ""key"": ""16.5"",
                                        ""doc_count"": 1

                                    },
                                    {
                                ""key"": ""XXXL"",
                                        ""doc_count"": 1

                                    }
                                ]
                            }
                    },
                        {
                        ""key"": ""Colour"",
                            ""doc_count"": 14,
                            ""sterms#banana"": {
                            ""doc_count_error_upper_bound"": 0,
                                ""sum_other_doc_count"": 0,
                                ""buckets"": [

                                    {
                                ""key"": ""Blue"",
                                        ""doc_count"": 7

                                    },
                                    {
                                ""key"": ""White"",
                                        ""doc_count"": 7

                                    }
                                ]
                            }
                    }
                    ]
                }
            },
            ""sterms#CollarSize"": {
                ""doc_count_error_upper_bound"": 0,
                ""sum_other_doc_count"": 0,
                ""buckets"": []

            }
        }
    }
}
";

    var settings = new ConnectionSettings(pool, new InMemoryConnection(Encoding.UTF8.GetBytes(json)))
        .DefaultIndex(defaultIndex);

    var client = new ElasticClient(settings);
    var response = client.Search<object>(s => s);

    var collarSizeSignificantTermsAgg = response.Aggregations.Filter("CollarSize").Nested("VariantsProperties").Terms("CollarSize");

    foreach (var bucket in collarSizeSignificantTermsAgg.Buckets)
    {
        Console.WriteLine(bucket.Key);

        var bananaSigTerms = bucket.Terms("banana");

        foreach (var subBucket in bananaSigTerms.Buckets)
        {
            Console.WriteLine($"key: {subBucket.Key}, doc_count: {subBucket.DocCount}");
        }
    }
}


NameResolutionFailure vs ConnectFailure issue

Question: So a rather peculiar issue, but a pretty bad one nonetheless. When a user enters our app with no internet at all, we get back a NameResolutionFailure as the error message for trying to make a API call via HttpClient. Okay, that's fine. The issue though is, when the user then connects to internet, goes back to app, and attempts to make another API call, we get the same error message. It appears that some kind of DNS caching is happening?
On the flip side, if a user HAS internet access while in app, then loses it, when we try to make an API call we get a ConnectFailure(Network is unreachable) error from the API call. And as soon as the user connects to the internet, they can make API calls instantenously.
The issue I'm trying to figure out is, A) What's the difference between NameResolutionFailure and ConnectFailure ? and B) Is there anything we can do in app to force it to completely retry the API call without using any cache? It's not obvious to me if the DNS is being cached or not, but we have a hinting feeling that's what's happening.
Here's part of the code (if you need more let me know, I figured this is the only code needed)
using(var client = new HttpClient())
{
   client.Timeout = TimeSpan.FromSeconds(MaximumWebRequestTime);
   HttpResponseMessage response = null;
   try
   {
      response = await client.GetAsync(URL);
      if (response.IsSuccessStatusCode) ....

Answer: Just had this issue on iOS too and fixed it by setting the DNS refresh timeout:
System.Net.ServicePointManager.DnsRefreshTimeout = 0;
It's a temporary fix, but works for now.
Haven't tested it on Android yet. Will do that too shortly.
Edit: Android tested successfully.
Comment: Where did you put that line of code? I'm getting a `The type or namespace name 'ServicePointManager' does not exist in the namespace 'System.Net'`
Comment: Wow looks legit. I put it in AppDelegate, since I can't access .Net stuff in XF. And... it worked! At least from the first try. Going to test more, but thanks buddy!
Comment: Yes, you have to place it in the platform code as from X.F you can't access this.
Answer: I just filed a bug on this recently:
http://bugzilla.xamarin.com/show_bug.cgi?id=45383
This is a regression in Xamarin Android version >= 7.0. You can workaround it by downgrading to Xamarin Android 18.104.22.168. And since it is a regression, it should be a priority and get fixed relatively quickly.
Note: I am a MS/Xamarin support engineer
Comment: We're actually seeing this error in iOS. Is it possible there's a larger issue at play that's affecting all platforms?
Comment: It definietely appears to be a bit more of broader issue then just Android (although might be related). I've posted this (https://forums.xamarin.com/discussion/comment/228788#Comment_228788) in the Xamarin forums, and a couple people are having same issue with Xamarin iOS.
Comment: I just confirmed this issue on iOS and in a Mono console project. New bug reports are being filed. I will provide links when done.
Comment: The Android and iOS bug reports have been marked as a duplicate of the Mono bug report as that is where the bug really is, in Mono >= 4.6.0
Comment: Ugh, so frustrating. As good as Xamarin is, there's definitely some room for improvement. But thanks for your help!


UIDatePicker error on dateSheet showInView

Question: I need to show a datePicker when a textField is clicked.
Here is the code:
<code>- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[self setDate];
    return NO;
}

-(void)setDate{

dateSheet = [[UIActionSheet alloc] initWithTitle:Nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];

[dateSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];

CGRect pickerFrame = CGRectMake(0, 44, 0, 0);
UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
[datePicker setDatePickerMode:UIDatePickerModeDateAndTime];
NSDate * maxDate = [NSDate dateWithTimeIntervalSinceNow:(3600 * 24 * 14)];
datePicker.maximumDate = maxDate;
datePicker.minimumDate = [NSDate date];
[dateSheet addSubview:datePicker];

UIToolbar * controlToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, dateSheet.bounds.size.width, 44)];

[controlToolBar setBarStyle:UIBarStyleBlack];
[controlToolBar sizeToFit];

UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

UIBarButtonItem *setButton = [[UIBarButtonItem alloc] initWithTitle:@"Imposta" style:UIBarButtonItemStyleDone target:self action:@selector(dismissDate)];
setButton.tintColor = [UIColor whiteColor];

UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Annulla" style:UIBarButtonItemStyleDone target:self action:@selector(cancelDate)];
cancelButton.tintColor = [UIColor whiteColor];

[controlToolBar setItems:[NSArray arrayWithObjects:spacer, cancelButton, setButton, nil] animated:NO];

[dateSheet addSubview:controlToolBar];
[dateSheet showInView:self.view];
[dateSheet setBounds:CGRectMake(0, 0, 320, 485)];
}
</code>
When showInView is called, a lot of errors are shown in console:
CGContextSetFillColorWithColor: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.
Then the same message with:
CGContextSetStrokeColorWithColor
CGContextSaveGState
CGContextSetFlatness
CGContextAddPath
CGContextDrawPath
CGContextRestoreGState
Why this happens?
Answer: After running your code, I found the problem is caused by the nil title of UIActionSheet.
A workaround is modified as below.
<code>dateSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
</code>
Another good resource for your reference.
Comment: Found related issue [here](http://stackoverflow.com/questions/19011170/invalid-context-error-on-ios-7-when-adding-a-uipickerview-inside-a-uiactionsheet).


Converter String para Decimal preservando todos os números - PHP

Question: Tenho o seguinte exemplo de conversão:
$string = "2.016,24"
$int = (float)$string

O resultado do código acima é = 2.016
Porém preciso resgatar o número completo dess valor, sendo assim, preciso a string para um número completo como: 2.016,24
Comment: Você não vai poder ter `.` (ponto) como separador de milhar, e a `,` (vírgula) separadora das casas decimais tem que virar ponto, resultando em: `2016.24`, dá para fazer com `(float) str_replace(['.', ','], ['', '.'], '2.016,24')`.
Answer: Acredito que maneira mais correta de fazer isso é utilizando a NumberFormatter, disponível na extensão intl do PHP.
Como instalar a extensão intl, caso ainda não a tenha: https://www.dotkernel.com/php-troubleshooting/where-is-the-intl-php-extension-problem-solved/
Com isso a solução será bastante simples. Você primeiro deve criar uma $format indicando o locale:
$format = numfmt_create('pt_BR', NumberFormatter::DECIMAL);

e utilizá-la com sua variável que contém o valor em string que deseja converter. Então:
$converted = numfmt_parse($format, "2.016,24");

a variável converted terá o valor float que precisa. Exemplo do var_dump da variável:
var_dump($converted);

>> (float) 2016.24

Exemplo completo:
$format = numfmt_create('pt_BR', NumberFormatter::DECIMAL);
$converted = numfmt_parse($format, "2.016,24");
var_dump($converted);
>> (float) 2016.24

Referências:
https://www.php.net/manual/pt_BR/class.numberformatter.php
https://www.dotkernel.com/php-troubleshooting/where-is-the-intl-php-extension-problem-solved/
Comment: Gostaria de entender os motivos da negativação da minha resposta. Uma vez que está correta e foi testada.


android.view.InflateException: Binary XML file line #1: Error inflating class linearlayout

Question: I use below code to create dialog with checkbox like that:

Create:
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        LayoutInflater adbInflater = LayoutInflater.from(getContext());
        LinearLayout eulaLayout = (LinearLayout) adbInflater.inflate(R.layout.checkbox, null);
        dontShowAgain = (CheckBox)eulaLayout.findViewById(R.id.skip);

Layout of checbox.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root" android:orientation="horizontal"
    android:layout_height="fill_parent"
    android:padding="10dp">

    <CheckBox
        android:text="Do not show again"
        android:id="@+id/skip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        xmlns:android="http://schemas.android.com/apk/res/android">
    </CheckBox>
</LinearLayout>

Comment: Make `<linearlayout` to `<Linearlayout`
Comment: you forgot to give width to your linearlayout in checkbox.xml
Comment: post ur complete logcat ?
Answer: There's a nested "caused by" exception that would give you more specific reasons for the failure.
But do mind your capitalization. There's no linearlayout but there's LinearLayout. The same applies to CheckBox.
Also your LinearLayout will need a layout_width.


How to interpret this lavaan structural equation model?

Question: I created following structural equation model from iris data set using lavaan package in R:

How do I interpret these numbers. The output (of sem() function of lavaan package) is given below. It did not give any P values:
<code>lavaan (0.5-18) converged normally after  64 iterations

  Number of observations                           150

  Estimator                                         ML
  Minimum Function Test Statistic                   NA
  Degrees of freedom                                -4
  Minimum Function Value               0.0000000000000

Parameter estimates:

  Information                                 Expected
  Standard Errors                             Standard

                   Estimate  Std.err  Z-value  P(>|z|)
Latent variables:
  sepf =~
    Sepal.Length      1.000
    Sepal.Width      -0.469
  petf =~
    Petal.Length      1.000
    Petal.Width       0.507
  lenf =~
    Petal.Length      1.000
    Sepal.Length     -0.177
  widf =~
    Sepal.Width       1.000
  strf =~
    sepf              1.000
    petf              2.084
  bulkf =~
    lenf              1.000
    widf              0.579

Regressions:
  strf ~
    Species           0.842
  bulkf ~
    Species           0.290

Covariances:
  strf ~~
    bulkf             0.065

Variances:
    Sepal.Length      0.361
    Sepal.Width       0.129
    Petal.Length      0.231
    Petal.Width       0.047
    sepf             -0.120
    petf             -0.220
    lenf             -0.179
    widf              0.084
    strf              0.053
    bulkf            -0.025
-----------------------------------------------
Warning messages:
1: In lav_data_full(data = data, group = group, group.label = group.label,  :
  lavaan WARNING: unordered factor(s) with more than 2 levels detected in data: Species
2: In lav_model_vcov(lavmodel = lavmodel, lavsamplestats = lavsamplestats,  :
  lavaan WARNING: could not compute standard errors!
  lavaan NOTE: this may be a symptom that the model is not identified.

3: In lavaan::lavaan(model = model, data = mydf, model.type = "sem",  :
  lavaan WARNING: some estimated variances are negative
4: In lavaan::lavaan(model = model, data = mydf, model.type = "sem",  :
  lavaan WARNING: covariance matrix of latent variables is not positive definite; use inspect(fit,"cov.lv") to investigate.
5: In sqrt(ETA2) : NaNs produced
6: In sqrt(ETA2) : NaNs produced
7: In sqrt(ETA2) : NaNs produced
>
</code>
Do I just take large estimates as signficant? Thanks for your insight.
Comment: @Jens you're completely correct, this model is vastly over-identified and hence it is not unique (therefore, it's likelihood surface has no curvature, and no standard errors can be computed). The model converges to some location, but given some different starting values it will almost certainly converge to an entirely different location that fits equally well. Therefore, do not interpret this model at all, as it is largely meaningless, and lavaan surely printed a warning message saying that the model is probably not identified.
Comment: The dashed lines appear to be fixed coefficients, which are often used for identifying latent variables (setting their metric).
Comment: Might be wrong, but propably the negative degrees of freedoms indicate that your model is underfitted and thus, the proposed model cannot be estimated/ tested. Therefore you cannot make any conclusions based on your model. If this is wrong, please correct me, statistics pros.
Comment: I have added the warnings that came with the output. Can we say if there is a particular latent factor or a particular association is completely wrong and the model should be retried after its removal? Also, there is warning that there are more than 2 levels in a factor (Spc or Species variable). So do I take that more than 2 factors are not allowed and I have to create dummy variables for such factor variables?
Comment: You really can't say anything at all about this model. On top of being completely unidentified it is badly broken (negative variance terms abound). So I would throw this model out and try something completely different.
Comment: What do dashed lines (vs normal lines) indicate? They do not correspond to negative values here. Could you also point me to some good link on how to interpret these models.
Comment: @philchalmers : If you enter your comments as an answer, I will accept it. Also, I tried to find but could not determine why some lines are dashed.
Answer: Moving comments above to an answer:
You really can't say anything at all about this model. On top of being completely unidentified it is badly broken (negative variance terms abound). So I would throw this model out and try something completely different.
Edit:
This model is vastly over-identified and hence it is not unique (therefore, it's likelihood surface has no curvature, and no standard errors can be computed). The model converges to some location, but given some different starting values it will almost certainly converge to an entirely different location that fits equally well. Therefore, do not interpret this model at all, as it is largely meaningless, and lavaan surely printed a warning message saying that the model is probably not identified


Exercise 4.9, Chapter I, in Hartshorne

Question:
Let $X$ be a projective variety of dimension $r$ in $\mathbf{P}^n$ with $n\geq r+2$. Show that for suitable choice of $P\notin X$, and a linear $\mathbf{P}^{n-1}\subseteq \mathbf{P}^n$, the projection from $P$ to $\mathbf{P}^{n-1}$ induces a birational morphism of $X$ onto its image $X'\subseteq \mathbf{P}^{n-1}$.

My way: W.L.O.G., assume that $X\setminus U_0\neq\emptyset$. Since $X$ is a projective variety, then $K(X)\cong S(X)_{(0)}$, which implies that $K(X)=k(x_1/x_0,\dots,x_n/x_0)$. Since $\dim X=r$, by Theorem 4.8A and Theorem 4.7A on page 27 in Hartshorne, then W.L.O.G., we can assume that $x_1/x_0,\dots,x_r/x_0$ is a separating transcendence base for $K(X)$ over $k$, which implies that $x_{r+1}/x_0,\dots,x_{n}/x_0$ are separable over $k(x_1/x_0,\dots,x_r/x_0)$. By Theorem 4.6A on page 27 in Hartshorne, $K(X)=k(x_1/x_0,\dots,x_r/x_0)[y]$, where $y$ is a $k(x_1/x_0,\dots,x_r/x_0)$-linear combination of $x_{r+1}/x_0,\dots,x_n/x_0$. Now I do not how to continue.
Comment: Now let $P = [0 : 0 : \cdots : 1]$. The projection $\pi$ away from $P$ is given by the rational map $$[x_0 : x_1 : \cdots : x_{n-1} : x_n] \longmapsto [x_0 : x_1 : \cdots : x_n]$$ which induces an inclusion of function fields $K(X') \hookrightarrow K(X)$, where $X'$ is the image of $X$ under the projection. $K(X') \hookrightarrow K(X)$ is actually an equality of fields since $x_1/x_0,\ldots,x_r/x_0,y \in K(X')$, and so $\pi$ is birational.
Comment: @TakumiMurayama Do you mean $[x_0:x_1:\cdots:x_{n-1}:x_n]\mapsto[x_1:\cdots:x_n]$, or others? Thanks. What's the hyperplane? $Z(x_{r+1})$ ?
Comment: I think the projection should map to $[x_0:\cdots:x_{n-1}]$; apologies for the typo. The hyperplane projected to is indeed $Z(x_{n+1})$.
Comment: @TakumiMurayama I am confused about $Z(x_{n+1})$. Do you mean $Z(x_{r+1})$? In this case, maybe we should change $P$ to $e_{r+1}=[0,\cdots,1,\cdots,0]$. Also where do we use the condition $n\geq r+2$?
Answer: I have rewritten this answer. We actually need a stronger version of Hartshorne's Theorem 4.6A (the theorem of the primitive element).
Theorem 4.6A$^\star$. Let $L$ be a finite separable extension field of a field $K$, and suppose that $K$ contains an infinite subset $S$. Then, there is an element $\alpha \in L$ which generates $L$ as an extension field of $K$. Furthermore, if $\beta_1,\beta_2,\ldots,\beta_n$ is any set of generators of $L$ over $K$, then $\alpha$ can be taken to be a linnear combination
$$\alpha = c_1\beta_1 + c_2\beta_2 + \cdots + c_n\beta_n$$
of the $\beta_i$ with coefficients $c_i \in S$.
Proof. This follows from the proof of [Zariski–Samuel, Ch. II, §9, Thm. 19], which uses Kronecker's "method of indeterminates," but we rewrite their proof below.
Consider the field extension
$$L \subseteq L(X,X_1,X_2,\ldots,X_n)$$
of $L$, where $X,X_1,X_2,\ldots,X_n$ are a set of indeterminates, and consider the subfields
\begin{align*}
  K^\star &= K(X_1,X_2,\ldots,X_n)\\
  L^\star &= L(X_1,X_2,\ldots,X_n)
\end{align*}
in $L(X,X_1,X_2,\ldots,X_n)$. Then, $L^\star = K^\star(\beta_1,\beta_1,\ldots,\beta_n)$, and $L^\star$ is a finite separable extension of $K^\star$ since the $\beta_i$ are separable over $K$, and hence also separable over $K^\star$ (see [Zariski–Samuel, Ch. II, §5, Lem. 2]). Consider the element
$$\beta^\star = X_1\beta_1 + X_2\beta_2 + \cdots + X_n\beta_n \in L^\star.\tag{1}\label{eq:zs1}$$
Let $F(X)$ be the minimal polynomial of $\beta^\star$ in $K^\star[X]$. The coefficients of $F(X)$ are rational functions of $X_1,X_2,\ldots,X_n$ with coefficients in $K$; let $g(X_1,X_2,\ldots,X_n) \in K[X_1,X_2,\ldots,X_n]$ be a common denominator of these rational functions. Then,
$$g(X_1,X_2,\ldots,X_n) \cdot F(X) = f(X,X_1,X_2,\ldots,X_n) \in K[X,X_1,X_2,\ldots,X_n],$$
and we have
$$f(\beta^\star,X_1,X_2,\ldots,X_n) = 0.\tag{2}\label{eq:zs2}$$
Let
$$G(X_1,X_2,\ldots,X_n) = f(X_1\beta_1+X_2\beta_2+\cdots+X_n\beta_n,X_1,X_2,\ldots,X_n).\tag{3}\label{eq:zs3}$$
Then, $G(X_1,X_2,\ldots,X_n)$ is a polynomial in $X_1,X_2,\ldots,X_n$ with coefficients in $L$, and \eqref{eq:zs2} says $G(X_1,X_2,\ldots,X_n) = 0$. Thus, all partial derivatives $\partial G/\partial X_i$ are zero for $i \in \{1,2,\ldots,n\}$. By \eqref{eq:zs3}, we then have
$$\beta_i \cdot f'(\beta^\star,X_1,X_2,\ldots,X_n) + f_i(\beta^*,X_1,X_2,\ldots,X_n) = 0\tag{4}\label{eq:zs4}$$
for every $i \in \{1,2,\ldots,n\}$, where
\begin{align*}
  f'(X,X_1,X_2,\ldots,X_n) &= \frac{\partial f(X,X_1,X_2,\ldots,X_n)}{\partial X},\\
  f_i(X,X_1,X_2,\ldots,X_n) &= \frac{\partial f(X,X_1,X_2,\ldots,X_n)}{\partial X_i}.
\end{align*}
The left-hand side in each equation \eqref{eq:zs4} is a polynomial in $L[X_1,X_2,\ldots,X_n]$ by \eqref{eq:zs1}, and hence is the zero polynomial. Thus, the equations \eqref{eq:zs4} remain valid if we substitute for $X_1,X_2,\ldots,X_n$ any elements of $K$. On the other hand, we have
$$f'(X,X_1,X_2,\ldots,X_n) = g(X_1,X_2,\ldots,X_n)\,F'(X)$$
where $F'(X) = dF/dX$, and hence
$$f'(\beta^\star,X_1,X_2,\ldots,X_n) \ne 0,$$
since $\beta^\star$ is separable over $K^\star$ and therefore $F'(\beta^\star) \ne 0$. Thus, $f'(\beta^\star,X_1,X_2,\ldots,X_n)$ is a nonzero polynomial in $L[X_1,X_2,\ldots,X_n]$. Since $S \subseteq L$ and $S$ is an infinite subset, we can find elements $c_1,c_2,\ldots,c_n \in S$ such that $(c_1,c_2,\ldots,c_n)$ is not a zero of that polynomial [Zariski–Samuel, Ch. I, §18, Thm. 14]. Setting
$$\beta = c_1\beta_1 + c_2\beta_2 + \cdots + c_n\beta_n,$$
we have that
$$f'(\beta,c_1,c_2,\ldots,c_n) \ne 0\tag{5}\label{eq:zs5}$$
and
$$\beta_i \, f'(\beta,c_1,c_2,\ldots,c_n) + f_i(\beta,c_1,c_2,\ldots,c_n) = 0\tag{6}\label{eq:zs6}$$
for every $i \in \{1,2,\ldots,n\}$. The equation \eqref{eq:zs6} and the inequality \eqref{eq:zs5} imply that $\beta_i \in K(\beta)$, and since $\beta \in L$, we therefore see that $L = K(\beta)$. This completes the proof of the theorem. $\blacksquare$
We now prove Hartshorne's exercise, which we restate below.
Exercise [Hartshorne, Ch. I, Exer. 4.9]. Let $X$ be a projective variety of dimension $r$ in $\mathbf{P}^n$, with $n\geq r+2$. Show that for a suitable choice of $P \notin X$, and a linear $\mathbf{P}^{n-1} \subseteq \mathbf{P}^n$, the projection from $P$ to $\mathbf{P}^{n-1}$ induces a birational morphism of $X$ onto its image $X' \subseteq \mathbf{P}^{n-1}$.
Proof. Let $k$ denote the ground field over which $X$ is defined. After permuting coordinates, we may assume without loss of generality that $X\cap U_0\neq\emptyset$. Then, the images of the rational functions $x_i/x_0$ generate $K(X)$ over $k$. Since $k$ is algebraically closed, we see the extension $K(X)/k$ is separably generated by [Hartshorne, Ch. I, Thm. 4.8A]. Since $\dim X = r$, after possible permutation of coordinates, we have that $x_1/x_0,x_2/x_0,\ldots,x_r/x_0$ form a separating transcendence basis for $K(X)$ over $k$ by [Hartshorne, Ch. I, Thm. 4.7A] to give the chain
$$k \subseteq k(x_1/x_0,x_2/x_0,\ldots,x_r/x_0) \subseteq K(X)$$
of field extensions.
Next, by setting $S = k$ in the theorem of the primitive element (Theorem 4.6A$^\star$ above), we see that $K(X)$ is generated by
$$\alpha = \sum_{i=r+1}^n c_i\frac{x_i}{x_0}$$
where $c_i \in k$ for every $i$. After a linear change of coordinates, we may assume that $\alpha = x_{r+1}/x_0$.
Now consider the map
\begin{align*}
  \mathbf{P}^n &\dashrightarrow \mathbf{P}^n\\
  [x_0:\cdots:x_{n-1}:x_n] &\mapsto [x_0:\cdots:x_{n-1}:0]
\end{align*}
This is the projection away from the point $P = Z(x_0,x_1,\ldots,x_{n-1})$ to the hyperplane $Z(x_n)$. Restricting the codomain to $Z(x_n) \simeq \mathbf{P}^{n-1}$, we obtain the rational map
\begin{align*}
  \pi\colon \mathbf{P}^n &\dashrightarrow \mathbf{P}^{n-1}\\
  [x_0:\cdots:x_{n-1}:x_n] &\mapsto [x_0:\cdots:x_{n-1}]
\end{align*}
which we claim induces a birational map $\pi\rvert_X\colon X \dashrightarrow \pi(X)$.
Let $X'$ denote the image of $X$ through this map $\pi$. Then, $K(X')$ is generated by the rational functions $x_i/x_0$ for $1 \le i \le r+1$. The map on function fields corresponding to $\pi$ is
\begin{align*}
  K(X') &\hookrightarrow K(X)\\
  x_i/x_0 &\mapsto x_i/x_0
\end{align*}
Since $x_i/x_0$ for $1 \le i \le r+1$ generate $K(X)$, we see that $K(X') = K(X)$, and so the map $\pi$ is birational. $\blacksquare$
We note that to prove Exercise 3.14 with this method, we can perform the operation above $n - (r+1)$ times to find a birational map between $X$ and a hypersurface in $\mathbf{P}^{r+1}$. In the notation of the proof above, composing all of these projections from points can be described as the linear projection
\begin{align*}
  \mathbf{P}^n &\dashrightarrow \mathbf{P}^n\\
  [x_0:\cdots:x_n] &\mapsto [x_0:\cdots:x_{r+1}:0:0\cdots:0]
\end{align*}
away from the $(n-r-1)$-plane $Z(x_1,x_2,\ldots,x_{r+1})$ to the $(r+1)$-plane $Z(x_{r+2},x_{r+3},\ldots,x_n)$; see for example [Shafarevich, Ex. 1.27]. Restricting the codomain to the $(r+1)$-plane $Z(x_{r+2},x_{r+3},\ldots,x_n) \simeq \mathbf{P}^{r+1}$, this gives a rational map $\pi\rvert_X\colon X \dashrightarrow \mathbf{P}^{r+1}$ that is birational onto its image.
Comment: Thank you for your great answer! Yet could you explain more on which point $P$ and plane $Sigma$ you chose to make the projection? Since in the exercise, it is required to project to some $\mathbb{P}^{n-1}$, I hope to make sure if you chose this demanding plane as plane $Z(x_j)$ for any $j=r+2, ... n$? Sorry for commenting on such an old post.
Comment: To be more explicit, I don't know how to understand the sentence "This is the projection away from the $(n-r-1)$-plane $Z(x_1/x_0,\ldots,x_r/x_0,\alpha)$ to the plane $Z(x_{r+2}/x_0,\ldots,x_{n}/x_0)$." So sorry for commenting on such an old post. Thank you for your excellent answer!
Comment: Dear @HetongXu, Thank you for the nice comments! I had to correct the answer a bit using the extra strength of the statement of the theorem of the primitive element in Hartshorne, but I hope this might make things a little clearer. In the notation of the proof, the projection $\pi$ can be described by projecting away from the point $Z(X_0,\ldots,X_{n-1})$ to the hyperplane $Z(X_n)$, then $Z(X_0,\ldots,X_{n-2})$ to the hyperplane $Z(X_{n-1})$, etc., until you finally project away from $Z(X_0,\ldots,X_{r+1})$ to the hyperplane $Z(X_{r+2})$.
Comment: Thank you for your comments, now I can understand what Hartshorne means in the remark of this question! With your comments, it seems that we can get another proof of the Proposition I.4.9, which seems difficult to prove regarding the similar method of Exercise 11.23 of Joe Harris's *Algebraic Geometry - A First Course*. Thank you so much your your great answers! Yet I'd like to ask a little bit more on this, i.e. can your description of the projection $\pi$ be reformulated as a projection from a **single point** to a plane? It seems difficult to do this.
Comment: And by reading the post, I think it is a doubt whether we can really find a SINGLE point and a HYPERplane to do the projection or not, which Hartshorne required us to do in the exercise.
Comment: Dear @HetongXu, I worked through the exercise again and hopefully it is a bit clearer (the point is that the proof of the theorem of the primitive element gives something stronger than what Hartshorne states; this resolves [this comment of Javier Linares](https://math.stackexchange.com/questions/396576/on-an-exercise-from-hartshones-algebraic-geometry-ch-i-sect-4#comment6270109_396576) from a related question, I believe).
Comment: I should add that I have not yet shown that $P \notin X$; maybe you have some ideas?
Comment: Thank you for your update, it has become much clearer! Sorry for the late reply! I tried a lot on how to change the point or taking affine charts at the same time without loss of generality. Yet failed once again. I was inspired by another solution quoted in the question https://math.stackexchange.com/questions/3774090/hartshornes-exercise-i-4-9-what-is-the-desired-projection-explicity, which I raised serveral days ago.
Comment: ...... Going back to your great answers here, it seems that the key point is the condition on the dimension of $X$, i.e. $r \leq n-2$. I went through your updated solution yet haven't figure out where you used this condition. However, we may not embed the variety $X$ in $\mathbb{P}^{n-2}$ by just knowing the dimension condition. (For example, the twisted cubic curve.) So maybe here is the key trouble.
Comment: ...... For once we can embed this variety in $\mathbb{P}^{n-2}$, then we can both assume **WLOG** that the point $P$ is not in $X$ and at the same time assume that $X \cap U_0 \neq \emptyset$. Then we are done.

Exercise 4.9, Chapter I, in Hartshorne


Find the probability of $P(B|-A)$ given $P(B)$, $P(A|B)$, $P(A|-B)$?

Question: $A,B,C$ not independent
I've found $P(-A)$, $P(-B \cap A)$, $P(A \cap B)$
$P(A)$ = $P(-B \cap A)$ + $P(A \cap B)$
Bayes Rule isn't helping me find $P(-A \cap B)$ or $P(B|-A)$  as far as I can see.
Edit: Added $P(A)$
Comment: What is $-A$? ${}{}{}$
Comment: It is $\Omega - A$.
Answer: Assuming that $-A$ denotes the complement of $A$ we have by Bayes rule that $$P(B|A^c)=\frac{P(A^c|B)P(B)}{P(A^c)}=\frac{\left(1-P(A|B)\right)P(B)}{1-P(A)}$$ which should be given according to the exercise (except for $P(A)$ which you have found as you say).


How to get submitted values on $formstate['values'] instead of $formstate['input']?

Question: I was generating a simple form with below fields, but i am wandering why my field values are not storing in the $formstate['values'], but its in the $formstate['input'].. please have look into below code and correct me if i am doing something wrong.
function create_entry_form($form, &$form_state){
    $form['entry']['password'] = array(
      '#type' => 'password',
      '#required' => TRUE,
      '#default_value' => '',
      '#maxlength' => 15,
    );

    $form['entry']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('OK'),
      '#weight' => 100,
    );
    $form['entry']['emailid'] = array(
      '#type' => 'textfield',
      '#required' => TRUE,
      '#default_value' => '',
      '#maxlength' => 25,
    );

    $form['entry']['reqbtn'] = array(
      '#type' => 'button',
      '#value' => t('Request'),
      '#weight' => 106,
      '#executes_submit_callback' => TRUE,
      '#submit' => array('request_site_password'),
      '#limit_validation_errors' => array(),
    );

  return $form;
}
function request_site_password($form, &$form_state) {
    echo '
';print_r($form_state);exit;
  }

Comment: just curious, it appears you are building a custom password retrieval... why not use Drupal's and why use a custom submit function rather than Drupal's built in submit handler (which would have been create_entry_form_submit)?
Answer: If you want to get $formstate['values'] or $form_state['input'] values .You have to write like below.
    function create_entry_form($form, &$form_state){
        $form['entry']['password'] = array(
          '#type' => 'password',
          '#required' => TRUE,
          '#default_value' => '',
          '#maxlength' => 15,
        );

        $form['entry']['submit'] = array(
          '#type' => 'submit',
          '#value' => t('OK'),
          '#weight' => 100,
        );
        $form['entry']['emailid'] = array(
          '#type' => 'textfield',
          '#required' => TRUE,
          '#default_value' => '',
          '#maxlength' => 25,
        );

        $form['entry']['reqbtn'] = array(
          '#type' => 'submit',
          '#value' => t('Request'),
          '#weight' => 106,
          '#submit' => array('request_site_password'),
          );

      return $form;
    }
   function request_site_password(&$form, &$form_state) {
    drupal_set_message('
' . print_r($form_state['input'], TRUE) . '
');
  }

You missed '&$form' in this function request_site_password(&$form, &$form_state)
Comment: The question is about why the values are empty but the input is not, not how to get it.
Comment: I have changed the code based on your comment now you can get the values