How do I get a user's email address (with permission) on iPhone?

Question: Typing on iPhone is tedious; I'd like to prompt my users for their email address without requiring them to actually type it.
Ideally they'd receive a dialog saying: "This app would like to use your email address.  Don't Allow / Allow"
If the user tapped "Allow," it would auto-fill their email address (the one they have configured in Mail.app) in a text field.
Is this possible?
Comment: If I picked "Allow" which one of my email addresses would it use? quixoto's answer is good because it also bypasses that problem.
Answer: Nope. But you can load up the contact picker interface and ask the user to select themselves from it-- that's much more friendly than making them type it in.
More info here:
http://developer.apple.com/iphone/library/documentation/ContactData/Conceptual/AddressBookProgrammingGuideforiPhone/200-QuickStart/QuickStart.html
Comment: Adding this comment because most assume one thing in this approach (that the email is verified, which is not the case).
Answer: Yes it is possible, have a look at ABGetMe for iOS. Note that you would have to write the allow/don't allow dialog yourself. Also, make sure to read and understand the Limitations section of the README.


How to prove a function from R to R^2 is a manifold

Question: Consider the function $\gamma : \mathbb R → \mathbb R^2 $ defined by $\begin{pmatrix}
\sin(t)\\
\sin(2t)
\end{pmatrix} $
$M$ = {$z= \gamma (t)$for some $t $ $\epsilon$ $ (0,1)$}
How do I show that this is a manifold without using the parameterization method.
I understand how to prove it is a manifold using the parameterization but how would I go backwards to use the implicit function theorem?
Comment: I don't know what you mean. The implicit function theorem applies to maps with surjective differential, which $\gamma$ does not have.
Comment: exactly where my confusion is! I have to solve the problem in 2 different ways, so I solved it using the parameterization. What other method should I use and how?
Answer: You may apply the preimage theorem. Since $\sin(2t)=2\sin t \cos t$ and $\cos t>0$ when $t\in (0,1)$, we have $\sin(2t)=2\sin t \sqrt{1-\sin^2 t}$. Plug in $x=\sin t, y=\sin (2t)$, we see that the manifold is determined by equation $2x\sqrt{1-x^2}-y=0$.
Consider map $f=2x\sqrt{1-x^2}-y:(0, \sin 1)\times \mathbb R \to \mathbb R$. Since
$\partial f/\partial y=-1$, $0$ is a regular value of $f$ and hence $f^{-1}0=M$ is a
manifold.


Cohomology ring of a product

Question: I am trying to calculate $H^*(\mathbb{R}P^3 \times \mathbb{C}P^5,\mathbb{Z})$ as a cohomology ring.
I know that
$$H^*(\mathbb{R}P^3,\mathbb{Z}) = \frac{\mathbb{Z}[\alpha,\beta]}{(2 \alpha, \alpha^2,\beta^2,\alpha \beta)}$$
with $\alpha$ the generator of $H^2(\mathbb{R}P^3)$ and $\beta$ generating $H^3(\mathbb{R}P^3)$
and
$$H^*(\mathbb{C}P^5) = \frac{\mathbb{Z}[\gamma]}{(\gamma^6)}$$
with $\gamma$ the generator of $H^2(\mathbb{C}P^5)$
Initially I thought the cross-product would just give an isomorphism, but the presence of the $\mathbb{Z}/2\mathbb{Z}$ term in the cohomology of $\mathbb{R}P^3$ kills that idea.
Now I could calculate the cohomology groups since both space have a nice CW structure, it would be possible to use
$$H^n(X \times Y) = \sum_{i+j=n}H^i(X) \otimes H^j(Y) \oplus \sum_{p+q=n+1} \operatorname{Tor}(H^p(X),H^q(Y))$$
but how can we deduce the ring/cup product structure?
(I am guessing the answer is to somehow use the cross product, but I just can't see it)
Answer: Hatcher has as Theorem $3.16$ that the cross product is an isomorphism if $X$ and $Y$ are CW complexes and $H^k(Y)$ is finitely generated free for all $k$.  So, you should still be able to apply it.
Comment: @Qwirk but $H^*(\mathbb{C}P^5;\mathbb{Z})$ is.
Comment: The theorem tells you the resulting cohomology ring is the tensor product of the two cohomology rings you mentioned, which is the ring you describe in the comment above. I should add that the isomorphism is not just as rings, but as *graded* rings. It would be good to note the degree of each of $\alpha$, $\beta$, and $\gamma$.
Comment: @wckronholm - oh I completely misread the Lemma! (apologies to Joe)
Comment: So can we simplify $$\frac{\mathbb{Z}[\gamma]}{(\gamma^6)} \otimes
\frac{\mathbb{Z}[\alpha,\beta]}{(2 \alpha, \alpha^2,\beta^2,\alpha \beta)} = \frac{\mathbb{Z}[\alpha,\beta,\gamma]}{(2 \alpha, \alpha^2,\beta^2,\alpha \beta,\gamma^6)}$$ or do I need to check the cohomology groups and resulting product?
Comment: @wrkronholf - thanks again.
Answer: Have you seen this paper? He starts by giving an example showing that the cohomology ring isn't necessarily determined by the integral cohomology rings of the factors, but analyzes conditions under which you can compute the cohomology ring of the product from knowledge of the cohomology of the factors.
Comment: thanks, I tuned out when he started talking about Bockstein homomorphism and cohomology spectrums, but I see in Section 6 there might be some way to do it. (This is from an old problem sheet so it should be relatively do-able)

Cohomology ring of a product


Do I risk ruining my guitar by switching the tuning often?

Question: I'm currently learning a song which needs drop-d tuning.
Since I found myself switching back and forth from drop-d to standard tuning a couple of times a day, I wonder if I'm risking damage to the guitar by doing so.
[It's an acoustic guitar, in case that matters]
Comment: @JDługosz That's generally when shipping the guitar or storing it for a long length of time.
Comment: The only thing I noticed on my oldest guitar is the bottom string groove in the nut did wear down after about 15 years. But I was always retuning that one, and it didn't have a locking nut
Comment: Shouldn't you always relax the strings when storing it anyway?
Answer: It's not going to make much difference. The tension differential is less than 5% overall. If you can manage it, get another guitar and have each in the tuning you need. One always has at least one guitar fewer than one already needs!
Answer: Switching between standard E tuning and drop D tuning is so common that some guitarists use special tuning knobs that flip between the two with a switch. I have a bass guitar version on my Fender Jazz bass. Some guitarists have practiced this retuning so extensively that they can do it by feel with just the regular knob – if you have ever watched a medley of popular riffs on YouTube, you may have seen the performer do this. In short, don't worry about it!
Comment: +1 for reminding of that idea. It's a good option - almost as good as having a 5 string!
Answer: I would say only when you actually tune up do you risk hurting the guitar but who does that anyway? Drop tuning may affect the intonation of the guitar but that is in no way breaking the guitar, and can be fixed relatively easily.
Answer: Not at all, I've used many, many guitars throughout the years. All of which could hold tone, and had relatively decent intonation. I would (and still do) switch between tunings. Standard to Drop D, Drop D to Drop C#, back up to Standard.
Now it can overtime give your tuning pegs more wear and tear, but thats the nature of playing guitar.
Also changing and using alternate tunings is a great way to learn more chord structures, and is great practice for those who like to focus on progressions.
Answer: I would also add to the very good answers, that in the past string tension was unfairly blamed for issues with humidity. Guitars are often damaged because of dryness (like winter weather or desert heat, or simply a dry house environment) or proximity to heat. The issues this low humidity causes falsely makes the strings look like the perpetrator.
And of course, if you try hard enough, with a weird enough tuning you can cause damage. For example if you fully loosen the four bottom strings, and tighten the top two strings to an extreme and leave the guitar that way for weeks or months... well then maybe you could cause the neck might to develop a twist.
Comment: Also consider that when you think about the strength of wound strings, The core of the string is thinner than the string it's self. Without getting specific, the thinnest wound strings are similar in tensile strength as the non-wound strings. I am saying that in some light string sets the fourth string may be prone to breaking as much as or similarly to the sixth.
Comment: I should also add that some tunings are prone to broken strings.
Comment: About prone-ness to broken strings, which strings are most affected (thick vs thin ones), and how many semi-tones do you think are safe to tune up?
Comment: @heltonbiker I think that there is a complicated answer to your follow up question, but the simple one is that physics puts the highest tension on the thinnest strings. I find tuning up more than a whole step past open tuning to be useless without customized string selections. One could tune down and capo, to get past such limitations.
Comment: Wow, at the end of the last comment I made I said sixth when I obviously meant first (which is the high string)... Must have been a bad day. Sorry.
Answer: No problem.  The drop-d tuning only changes the total tension about four percent, so it will not do any damage to the guitar.  Your low E string will not last as long, however.


Derivative problem by a windmill

Question: Problem:
The power (in kW) of a windmill is P = 0.35 * v ^ 3. Where v is the wind speed in m/s.
We must use derivatives to calculate the increase of the power, if the wind speed increases from 19 m/s to 20 m/s.
According to the solution, you have to calculate D P (19).  But is the meaning of DP (19) really the increase between 19 and 20?  I would think this is the increase at moment of wind speed 19 m/s.
Comment: This seems a duplicate to your earlier question:  https://math.stackexchange.com/questions/4109765/increase-in-wind-speed-through-derivatives
Answer: You have  $$P(v)=0.35\,v^3$$ Now, close to a reference point $v_0$, by Taylor expansion, you have as an approximation
$$P(v)=P(v_0)+P'(v_0)(v-v_0)+\frac 12 P''(v_0)(v-v_0)^2+\cdots$$
Using your numbers, we then have
$$P(20)=2400.65+379.05+19.95$$
You see how small is the third term and then how good is the linear approximation.
Comment: @WinstonCherf. What you gave  ! $v_0=19$ and $v=20$
Comment: Thanks. What do you use as values for $v_0$ and $v$?

Derivative problem by a windmill


Implicit differentiation of "similar" functions

Question: The graph of the equation $x^2 + y^2 = 1$ gives a circle of radius $1$, centered at the origin:

After we find its derivative:
$$ \frac{dy}{dx} (x^2 + y^2) = \frac{dy}{dx} 1 \\
2x + 2y \frac{dy}{dx} = 0 \\
\frac{dy}{dx} = -\frac{x}{y}
$$
if we graph it on a 3D space we get this shape:

and it does describe the slope of the circle (positive in quadrant II & IV, negative in I & III)
Now let's consider a "similar" equation:
$$ x^3 + xy^2 = x $$
The graph should be same everywhere except when $x = 0$, since it's just the last equation multiplied by $x$ on both sides, and the differentiability of it should be the same except at $x = 0$

However, if we work out the derivative of y with respect to x:
$$ \frac{dy}{dx} (x^3 + xy^2) = \frac{dy}{dx} x \\
3x^2 + y^2 + 2xy \frac{dy}{dx} = 1 \\
\frac{dy}{dx} = -\frac{3x^2+y^2-1}{2xy}
$$
we get a completely different function, and plotting the graph yields this weird shape:

and it doesn't describe the slope of the circle at all. So why does finding the derivative of the first equation works, but not the second?
Comment: On the curve you have $x^2+y^2=1$...
Comment: They're not "similar," though. Your second equation is that of the union of an _ellipse_ and the $y$-axis instead of the unit circle. Try again without that coefficient of $2$ that snuck into the second equation.
Comment: The correct equation $ \ x^3 + xy^2 \ = \ x \ $ was used in OP's calculation of the derivative; they apparently made a typo on the line you refer to.  The graph shown is also for the correct equation.  I have edited a correction to that line.
Answer: The only difference between the two derivatives is entirely due to the introduction of the vertical line $ \ x = 0 \ $ that is combined with the circle.  The derivative for the second "curve" is
$$ \frac{dy}{dx} \ \ = \ \ \frac{1 \ - \ 3x^2 \ - \ y^2 }{2xy} \ \ = \ \ \frac{(\overbrace{1 \ - \  x^2 \ - \ y^2}^{= \ 0}) \ - \ 2x^2 }{2xy} \ \ = \ \ -\frac{ x^2 }{ xy} \ \ . $$
For points on the circle that are not on the $ \ y-$axis, both derivative expressions produce the same result:  for example, at $ \ ( -\frac45 \ , \ \frac35 ) \ , $ we have
$$ \frac{dy}{dx} \ \ = \ \ -\frac{-\frac45}{\frac35} \ \ = \ \ \frac43 \ \ \ \ \text{versus} \ \ \ \frac{dy}{dx} \ \ = \ \ \frac{1 \ - \ 3·\frac{16}{25} \ - \ \frac{9}{25} }{2·\left(-\frac45 \right) ·\frac35} \ \ = \ \ -\frac{\frac{ - 32}{25} }{\frac{24}{25}} \ \ = \ \ \frac43 \ \ . $$
For the circle, we simply find horizontal tangents at $ \ (0 \ , \ \pm 1) \ \ , $ while $ \ x^3 + xy^2 \ = \ x \ \ $ has an indeterminate "value" $ \  -\frac{ 0^2 }{ 0·y} \ $ at all the points on the $ \ y-$axis [it is ambiguous at $ \ (0 \ , \ \pm 1) \ \   $ because there are both horizontal and vertical tangents at those points].


Can batsman hit the ball after the ball cross the stumps?

Question: Can the batsman hit the ball after the ball crossed the stumps?
Comment: http://www.youtube.com/watch?v=z4qaGiWt-bo Like this?
Answer: It is allowed. There is no rule for this.
Brad Haddin once(two times same match) did this on a free hit. Just because you can't get bowled on a free hit and you get more time when you play after the ball passes the stumps.- Video Link.
This has hardly happened in International cricket.
Sometimes Upper cuts, unintentionally are hit after the ball crosses the stumps.
Comment: This does seem unfair on the bowler though. Right?


Same AjaxEventBehavior for multiple components

Question: I add an image and a text component to a WebMarkupContainer as described here:
filter.add(newFilterLabel("textSub", customerText, filtervalue));
filter.add(newFilterImage("imgSub", filtervalue));

For each component, there is an AjaxEventBehavior doing different things. I would like to change it in a way that both do the same thing independent from which component has been clicked on.
private Component newFilterLabel(String id, IModel<String> customText,
    final SourceFilterValue currentValue) {
    final BBLabel label = new BBLabel(id, customText);
    label.add(new AjaxEventBehavior("onclick") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onEvent(AjaxRequestTarget target) {
            doSomething(currentValue,filteredsources, target);
        }
    });
    return label;
}

private Image newFilterImage(String id, final SourceFilterValue filterValue) {
    final Image img = new Image(id, resources.getImage(EXPAND_ICON));
    img.add(new AjaxEventBehavior("onclick") {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onEvent(AjaxRequestTarget target) {
            doSomething(img);
        }
    });
    return img;
}

Do you have any suggestions how to change it or any workaround? I use Wicket 1.5.8.
Answer: An AjaxBehavior can be bound to a single element only. Either add it to a parent in the hierarchy, or just let both behaviors call the same method:
@Override
protected void onEvent(AjaxRequestTarget target) {
    doSomething(filterValue); //filterValue has to be final to be able to access it from the inner class
}


Why arrays cannot be lazy-loaded in a one-to-many assocation?

Question: According to Hibernate documentation :

After observing that arrays cannot be lazy, you can conclude that lists, maps and idbags are the most performant (non-inverse) collection types

So my question is dead simple : why arrays cannot be lazy-loaded in a one-to-many assocation ?
Answer: Lazy load works by the fact that Hibernate uses structures that can be proxied to know when you try to access the data for the first time. When you do this, these structures will tell hibernate that they now need to load the information and Hibernate will then do this on-the-fly, without you knowing what's happening.
Arrays can't be lazy loaded because Hibernate wouldn't have a way to know you are trying to access them for the first time, since you can't proxy the "[]" operator ( the aaload bytecode ), Hibernate would never know when you first tried to access it so it would not be able to load it on the fly.
When using collections, you always have to access them through their methods, so Hibernate can be 100% sure when you're trying to access them for the very first time and then load them.
So, the real reason is that there is no way to hook your code to the array access operator. The same happens on lazy loading for fields, Hibernate can't lazy load a non-collection property with field only access as it wouldn't know when you tried to access the field, they always need to have get/set method access.
As an example of how this is done, you can check the PersistentList collection on Hibernate, on it's indexOf method (and many others) the read method is called:
public int indexOf(Object value) {
    read();
    return list.indexOf(value);
}

And in the end the read method just initializes the collection if it hasn't been lazy loaded yet.
Comment: Yes, but it's an important limitation from the performance standpoint, if array access was a method call it would take at least two operations to do it. It also doesn't make much sense to use an array in this case since you would be adding/removing objects from the hibernate collection and this isn't something simple to be done in an array.
Comment: Thank you very much for your answer. Seems crazy that you cannot use Array just because Hibernate cannot hook the array access operator. So it comes basically from a Java language limitation ?


Como remover lixos nas telas de impressão

Question: Como crio um CSS para remover os lixos como na imagem em anexo.
  Estou usando bootstrap.
Answer: Utilize as seguintes classes do bootstrap

hidden-print: para não mostrar na impressão - será exibido no HTML
visible-print: para mostrar na impressão - não será exibido no HTML

Exemplo:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Não mostra na impressão mas mostra no HTML

  Imprmir

Mostra na impressão mas não mostra no HTML

Mostra em ambos

Você ainda tem a opção de criar estilos que serão usados apenas na impressão, consigo lembrar de duas maneiras
1 - Criando uma folha de estilos somente para a impressão e importando no seu HTML com a tag media="print"
<link href="style.css" media="print" rel="stylesheet" />`

2 - Ou usando a meta tag @media print { } em sua folha de estilos
@media print {
    /* Your styles here */
}

Comment: Ok,Obrigado,utilizei o @media print {.
Comment: Ultilizei o hidden-print mais ai a página toda fica em branco,sem os textos;dentro daquelas tabelas,tenho textos que precisam ser exibidos.
Comment: A classe `hidden-print` irá ocultar todos os elementos filhos do componente que você atribuiu a classe.
Answer: Com CSS puro basta criar em sua folha de estilos um @media print { } ou você também pode ter um arquivo a parte e para isso basta adicionar um link stylesheet no head, como o trecho de código abaixo mostra.
<link rel="stylesheet" type="text/css" href="/print.css" media="print" />

Exemplos:
@media print {
    * {
        background:transparent !important;
        color:#000 !important;
        text-shadow:none !important;
        filter:none !important;
        -ms-filter:none !important;
    }

    body {
        margin:0;
        padding:0;
        line-height: 1.4em;
    }

    header {
        display: none;
    }

    footer {
        display: none;
    }

    .content {
        display: block;
    }

    img {
        max-width: 100%;
    }
}

Explicação:
Como a tela de impressão costuma ser modificada/adaptada para ser melhor visualizada no papel, talvez você queira modificar sua página inteira, então resolvi mostrar alguns exemplos para você.

Com o * você está aplicando os atributos para a página toda e como
alguns estilos já vem carregados por padrão, eu resolvi resetalos
para ter uma tela de impressão limpa.
A mesma coisa acontece com o body, apenas reseto alguns atributos e
aplico uma altura para as linhas.
Agora no Header, Footer e .content eu apenas apliquei o display,
que você usará para controlar o que vai aparecer e o que vai sumir.
Caso seja necessário que um elemento apareça somente na tela de
impressão, você teria que aplicar um display: block; nele dentro da
@media print e um display: none; fora, para que ela apareça
somente quando for impressa.
Também é importante lembrar das imagens, pois dependendo do seu
estilo elas podem ficar para fora da área de impressão, então mostrei
o max-width: 100%; que não deixa a imagem passar da largura da
página.


How to set a limited defined random values in numpy matrix

Question: How to set a limited random values by amount and range in nupmy matrix ?
Means instead :
random_matrix = np.random.rand(5, 5)

[[0.38555213 0.96454126 0.91586422 0.92638243 0.85516641]
[0.64717218 0.2716665  0.70945594 0.74754943 0.48870502]
[0.23381316 0.01992578 0.86749684 0.85797792 0.19308509]
[0.63565231 0.7056163  0.69110815 0.73506642 0.804646  ]
[0.35512519 0.54900446 0.66311323 0.04899527 0.49349834]]

the wanted setting for example is 3 random integers between the range 1-5
in a null matrix :
0,0,0,4,0
0,0,0,0,0
0,1,0,0,0
0,0,0,3,0
0,0,0,0,0

Thanks in advance
Comment: Like this? ```np.random.randint(low=0, high=5, size=(5,5))```
Comment: Thanks , partly . Only limited number of values are random integers by a range and the others are null
Answer: If i understand the question correctly, you want to create a matrix that is zero in all places except for 3 random indices that will have a random value between the range 1-5.
For this i would suggest doing:
null_matrix = np.zeros((5,5), dtype=np.int32)

rng = np.random.default_rng()
x = rng.choice(5, size=3, replace=False)
y = rng.choice(5, size=3, replace=False)

null_matrix[x,y] = rng.choice(np.arange(1,5), 3)
print(null_matrix)

Output:
array([[0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [4, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 2]], dtype=int32)

Comment: Thanks Kevin. It's gives only 4-5 random 1's and 5's and only in the upper matrix line
Comment: Forgot to add the ```np.arange``` in ```rng.choice``` and realized there is no need to combine ```x``` and ```y```.
Comment: Correct , only it should be np.arange(1,6) instead np.arange(1,5) .Thanks again Kevin , have a nice day


Amazon S3 mysterious(unwanted) files

Question: I recently created my first bucket on S3. I had a folder named backups there which when I opened I saw these about 300 small(from few bytes to 4 or so Kbs) in that folder. I hadn't even uploaded anything yet.
I delete those files but they reappear again after some time.
Can anyone please explain what is(might be) going on. The content of those files is something about encryption stuff.
You can see in this screenshot
If i don't delete them they are just gonna multiply and use my space.
Please help
Thank you
Comment: S3 doesn't generate files by itself. It could be something like CloudTrail logs going into the bucket, the bucket could be public and someone is storing something, or you have a process doing it. Check your CloudTrail logs (which are stored in an S3 bucket) to work out how they're getting there. You may need to enable object level logging or something like that, I've never tried it, I think it's a configuration setting on the bucket.
Comment: I checked and made some changes. I will wait till those files are regenerated to see if it was the issue with naming folder name as `backup` which i should have given something like `logs` etc
Comment: @Tim You were right those are logs. Thank you.
Comment: I will post an answer to your question so you can accept it. That prevents others having to come in and have a look.
Answer: Those look like CloudTrail logs to me, or perhaps some other type of log. I think you've configured your account to store logs in that bucket.
Comment: These appear to be [S3 bucket access logs](https://docs.aws.amazon.com/AmazonS3/latest/dev/ServerLogs.html#server-log-keyname-format).   A bucket that writes its logs to itself is a configuration I occasionally see users set up, which isn't a good idea... such a bucket will write logs to itself indefinitely since creation of each new log file creates a log entry, which will result in creation of a future log file, which creates a new log entry...

Amazon S3 mysterious(unwanted) files


erro quando vou pesquisar o cliente

Question: eu fiz esse programa meu problema está sendo em pesquisar o cliente assim que eu pesquiso ele não me da o resultado e encerra o programa, gostaria de saber oque faço para sanar o problema
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>

typedef struct cliente CLIENTE;

struct cliente{
    unsigned long  id;
    char nome[50];
    char telefone[15];
    char cpf[12];
    char email[50];

};

void menu();
void cadastracliente();
void listarCliente();
void pesquisaCliente();

int main(){
    menu();
    return 0;
}

void menu(){

    int escolha;
    do{
        system("cls");
        printf("[1]-cadastra Cliente\n");
        printf("[2]-listar Cliente\n");
        printf("[3]-Pesquisar Cliente\n");
        printf("[0]-Sair\n");
        printf(": ");
        scanf("%d",&escolha);
        switch(escolha){
        case 1:
            cadastracliente();
            break;
        case 2:
            listarCliente();
            break;
        case 3:
            pesquisaCliente();
            break;
        }

    }while(escolha!=3);
}

void cadastracliente(){
    system("cls");
    FILE* arquivo;
    CLIENTE clt;

    arquivo = fopen("cliente.dat","ab");
    if(arquivo ==NULL){
        printf("Problemas na abertura do arquivo");
    }else{
        do{

            fflush(stdin);
            printf("Digite o nome: ");
            gets(clt.nome);
            fflush(stdin);
            printf("Digite o CPF: ");
            gets(clt.cpf);
            fflush(stdin);
            printf("Digite o email: ");
            gets(clt.email);
            fflush(stdin);
            printf("Digite o Telefone: ");
            gets(clt.telefone);

            fwrite(&clt,sizeof(CLIENTE),1,arquivo);

            printf("\nDeseja continuar(s/n)");

        }while(getch() =='s');
        fclose(arquivo);
    }
}

void listarCliente(){
    system("cls");
    FILE* arquivo;
    CLIENTE clt;

    arquivo = fopen("cliente.dat","rb");
    if(arquivo ==NULL){
        printf("Problemas na abertura do arquivo");
    }else{
        printf("---------------CLIENTES---------------\n");
        while(fread(&clt,sizeof(CLIENTE),1,arquivo)==1){

            printf("id: %lu\n",clt.id);
            printf("Nome: %s\n",clt.nome);
            printf("CPF: %s\n",clt.cpf);
            printf("E-mail: %s\n",clt.email);
            printf("Telefone: %s\n",clt.telefone);
            printf("--------------------------------------\n");
        }
    }
    fclose(arquivo);
    getch();

}

void pesquisaCliente(){
    system("cls");
    FILE* arquivo;
    CLIENTE clt;
    char nome[30];

    arquivo = fopen("cliente.dat","rb");
    if(arquivo ==NULL){
        printf("Problemas na abertura do arquivo");
    }else{
        fflush(stdin);
        printf("Digite o nome a pesquisar: ");
        gets(nome);

        while(fread(&clt,sizeof(CLIENTE),1,arquivo)==1){
            if(strcmp(clt.nome,nome)==0){
                printf("id: %lu\n",clt.id);
                printf("Nome: %s\n",clt.nome);
                printf("CPF: %s\n",clt.cpf);
                printf("E-mail: %s\n",clt.email);
                printf("Telefone: %s\n",clt.telefone);
                printf("--------------------------------------\n");
            }
        }
    }
    fclose(arquivo);
    getch();
}

´´´

Comment: Não encontrei problema no seu codigo. Apenas essa linha ```while(escolha!=3);```. so substituir o 3 pelo 0, como indicado no meu.
Comment: muito obrigado.
Answer: A condicao do while está errada, no codigo se você fazer uma pesquisa vai entrar no while e sair do loop
while(escolha!=0);
Só mudar a condicao para 0
Answer: Existem alguns problemas no código que estão fazendo ele se comportar assim.
A primeira coisa, como o Bernardo falou nos comentários é que você precisa trocar o while(escolha!=3) por while(escolha!=0) no loop principal. Isto vai corrigir o fluxo do menu.
A segunda coisa a verificar é que você não dá nenhuma indicação de que o cliente não foi encontrado. Então se você pesquisar por um cliente que não existe, nada acontece e o programa fica parado na tela, travado. Um flag pode resolver isso facinho, facinho.
char encontrado = 0;
while (fread(&clt, sizeof(Cliente), 1, arquivo) == 1) {
    if (strcmp(clt.nome, nome) == 0) {
        exibirCliente(&clt);
        encontrado = 1;
        break;
    }
}
if (!encontrado)
    printf("Cliente %s não encontrado.\n", nome);

Outra coisa é que, tal como está, o cliente só vai ser encontrado se você pesquisar pelo nome exatamente como ele foi cadastrado, levando em consideração letras maiúsculas, minúsculas, espaços e caracreres especiais. Se você prestar atenção, fgets está salvando no arquivo os textos com o caracter \n, então você vai precisar removê-lo dos campos do cliente antes de salvar. Uma função simples para fazer isso pode ser implementada com um loop:
void removerEnter(char* buffer, int size) {
    for (int i = 0; i < size; i++) {
        if (buffer[i] == '\n') {
            buffer[i] = '\0';
            return;
        }
    }
}

void ajustarCliente(Cliente* cliente) {
    removerEnter(cliente->nome, 50);
    removerEnter(cliente->telefone, 15);
    removerEnter(cliente->cpf, 12);
    removerEnter(cliente->email, 50);
}

e chamada antes de salvá-lo:
do {
    printf("Digite o nome: ");
    fgets(clt.nome, 50, stdin);

    printf("Digite o CPF: ");
    fgets(clt.cpf, 12, stdin);

    printf("Digite o email: ");
    fgets(clt.email, 50, stdin);

    printf("Digite o Telefone: ");
    fgets(clt.telefone, 15, stdin);

    ajustarCliente(&clt);
    fwrite(&clt, sizeof(Cliente), 1, arquivo);

    printf("\nDeseja continuar(s/n)\n");

} while (getch() == 's');
fclose(arquivo);

Uma implementação completa com todas estas correções ficaraia mais ou menos assim:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct cliente {
    unsigned long id;
    char nome[50];
    char telefone[15];
    char cpf[12];
    char email[50];
};
typedef struct cliente Cliente;

void menu();
void cadastracliente();
void listarCliente();
void pesquisaCliente();

void exibirCliente(Cliente* cliente) {
    printf("id      : %lu\n", cliente->id);
    printf("Nome    : %s\n", cliente->nome);
    printf("CPF     : %s\n", cliente->cpf);
    printf("E-mail  : %s\n", cliente->email);
    printf("Telefone: %s\n", cliente->telefone);
}

void removerEnter(char* buffer, int size) {
    for (int i = 0; i < size; i++) {
        if (buffer[i] == '\n') {
            buffer[i] = '\0';
            return;
        }
    }
}

void ajustarCliente(Cliente* cliente) {
    removerEnter(cliente->nome, 50);
    removerEnter(cliente->telefone, 15);
    removerEnter(cliente->cpf, 12);
    removerEnter(cliente->email, 50);
}

int main() {
    menu();
    return 0;
}

void menu() {
    int escolha;
    do {
        system("cls");
        printf("[1]-cadastra Cliente\n");
        printf("[2]-listar Cliente\n");
        printf("[3]-Pesquisar Cliente\n");
        printf("[0]-Sair\n: ");
        fscanf(stdin, "%d%*c", &escolha);
        switch (escolha)
        {
        case 1:
            cadastracliente();
            break;
        case 2:
            listarCliente();
            break;
        case 3:
            pesquisaCliente();
            break;
        }
    } while (escolha != 0);
}

void cadastracliente()
{
    system("cls");
    FILE* arquivo;
    Cliente clt;

    arquivo = fopen("cliente.dat", "ab");
    if (arquivo == NULL)
    {
        printf("Problemas na abertura do arquivo");
        return;
    }

    do {
        printf("Digite o nome: ");
        fgets(clt.nome, 50, stdin);

        printf("Digite o CPF: ");
        fgets(clt.cpf, 12, stdin);

        printf("Digite o email: ");
        fgets(clt.email, 50, stdin);

        printf("Digite o Telefone: ");
        fgets(clt.telefone, 15, stdin);

        ajustarCliente(&clt);
        fwrite(&clt, sizeof(Cliente), 1, arquivo);
        printf("\nDeseja continuar(s/n)\n");

    } while (getch() == 's');
    fclose(arquivo);
}

void listarCliente()
{
    system("cls");
    FILE* arquivo;
    Cliente clt;

    arquivo = fopen("cliente.dat", "rb");
    if (arquivo == NULL) {
        printf("Problemas na abertura do arquivo!");
        return;
    }

    printf("---------------CLIENTES---------------\n");
    while (fread(&clt, sizeof(Cliente), 1, arquivo) == 1) {
        exibirCliente(&clt);
        printf("--------------------------------------\n");
    }
    fclose(arquivo);
    getch();
}

void pesquisaCliente()
{
    system("cls");
    FILE* arquivo;
    Cliente clt;
    char nome[30];

    arquivo = fopen("cliente.dat", "rb");
    if (arquivo == NULL) {
        printf("Problemas na abertura do arquivo");
        return;
    }

    printf("Digite o nome a pesquisar: ");
    fflush(stdin);
    fgets(nome, 30, stdin);
    removerEnter(nome, 30);
    char encontrado = 0;
    while (fread(&clt, sizeof(Cliente), 1, arquivo) == 1)
    {
        if (strcmp(clt.nome, nome) == 0) {
            exibirCliente(&clt);
            encontrado = 1;
            break;
        }
    }
    if (!encontrado)
        printf("Cliente %s não encontrado.\n", nome);
    fclose(arquivo);
    getch();
}

Espero ter ajudado.
Bons estudos!
Comment: Ajudou muito obrigado
Comment: Imagina... é um prazer.
Se tiver sanado sua dúvida, você poderia marcar a minha resposta como a correta? Valeu!
Comment: Como poderia fazer um cotador para ID do cliente?,para cliente ter um ID diferente do outro

erro quando vou pesquisar o cliente


How to read apache header in NGINX?

Question: I've set up nginx to bypass ajax requests (wich have header):
set $accel "0";
if ($http_x_requested_with) {
   set $accel "1";
}
proxy_cache_bypass $accel;

It works fine, but I want be able to cache SOME ajax requests. And I want to be able to set cache time in PHP. I'm trying to use X-Accel-Expires for that and i'm trying to rewrite bypass settings, if X-Accel-Expires header present.
set $accel "0";
if ($http_x_requested_with) {
   set $accel "1";
}

if ($http_x_accel_expires) {
     set $accel "0";
}
proxy_cache_bypass $accel;

But it doesn't work.... Seems like nginx doesn't get Apache header X-Accel-Expires in $http_x_accel_expires variable.
Comment: have you got an nginx config that ignores them? check for directive: ```proxy_ignore_headers```
Comment: I ignore  proxy_ignore_headers  "Cache-Control" "Expires";
Answer: The X-Accel-Expires header is a response header sent by the PHP, and nginx only populates request headers into $http variables.
You should move the caching logic entirely into PHP. If you don't want to cache some responses from Ajax, you add X-Accel-Expires: 0 in PHP.
This way you don't need to do any tricks in nginx.

How to read apache header in NGINX?


Migrating from TFS to VSTS - Reducing TPC Database Size

Question: We are planning a migration from an on-premises TFS instance to VSTS very shortly. Ahead of the migration, we run the pre-requisite Validation task and obtained the following output report on the TPC database size:
"The database is currently 191GBs. This is above the recommended size of 150GBs to use the DACPAC import method. The largest table size is currently 172GBs. This is above the recommended size of 20GBs to use the DACPAC import method.
Validation completed 'Validate Collection Database Size' with result Warning, message The largest table size is currently 172GBs. This is above the recommended size of 20GBs to use the DACPAC import method."
We are therefore keen to reduce the size of the TPC database and have two main considerations:

Shrink the Database and generate the DACPAC from the resultant output.

Delete any of the following objects which are unused or redundant:
a) Older Workspaces
b) Build Results
c) Redundant Team Projects
d) Unused Files
e) Test Attachments created during test runs
f) XAML Builds

Would therefore appreciate some advice or feedback on the pros and cons of either approach and which would be recommended.
Answer: Most up-to-date version of this guidance is on my blog: Clean up your Team Project Collection prior to migrating to VSTS. The guidance is still pretty much spot on for recent versions of Azure DevOps Server.

Given that you need to reduce your largest table by 150GB, I wonder whether DACPAC is every going to be an option. That said, it's always a good idea to clean up your TFS instance. Your first step won't help a lot until you've managed to strip enough data to actually get any benefit out of a shrink.
Your identified actions would indeed help, most are already documented here. Queries that can aid in detecting where your space is allocated are also found in this recent support ticket.
Delete old workspaces
Deleting workspaces and shelvesets can reduce your migration and upgrade times considerably. either use the tf commandline or leverage a tool like the TFS SideKicks to identify and delete these.
Build results
Not just build results, but often overlooked the actual build records can take up a considerable amount of data. Use tfsbuild destroy (XAML) to permanently delete the build records. In the past, I've encountered clients who had 1.8 million "hidden" builds in their database and removing them shaved off quite a considerable amount of data. These records were kept around for the warehouse.
Old team projects
Of course, destroying old team projects can give back a lot of data. Anything you don't need to send to azure helps. You could also consider splitting the collection and to leave behind the old projects. That will give you the option to detach that collection and store it somewhere, should you ever need that data again.
Redundant files
Deleted branches are a very common hidden size hog. When deleting things in TFVC, they are not actually deleted, they're just hidden. Finding deleted files and especially old development or feature branches can give you back a lot of data. Use tf destroy to get rid of them.
You may also want to look for checked in nuget package folders, those can quickly rack up a lot of space as well.
Test Attachments
Ohh yes, especially when you use test attachments, these can grow like crazy, depending on your TFS version either use the built-in test attachment cleanup features or use the Test Attachment Cleaner from the TFS power tools.
XAML Builds
The build definitions themselves won't take a lot of db space, but the build results may. But those have been covered in a previous section.
Git Repositories
You may have data in your git repositories that are no longer accessible due to force pushes or deleted branches. It's also possible that certain data in Git could be packed more efficiently. To clean your repositories you have to clone them locally, clean them up, delete the remote repo from TFS and push the cleaned copy to a new repository (you can use the same name as the old one). Doing this will break references with existing build definitions and you will have to fix these up. While you're at it, you could also run the BFG repo Cleaner and convert the repositories to enable Git-LFS support to handle large binary files in your repositories more elegantly.
git clone --mirror <<repo>>
# optionally run BFG repo cleaner at thi s point
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git repack -adf
# Delete and recreate the remote repository with the same name
git push origin --all
git push origin --tags

Work item (attachments)
Work items can gather up a considerable amount of data, especially when people start attaching large attachments to them. You can use witadmin destroywi to delete workitems with unreasonably large attachments. To retain the work item, but delete its attachments you can delete the attachments from the current work item and then clone it. After cloning, destroy the old work item to allow the attachments to be cleaned up.
Old work items that you no longer need (say the sprint ites from 6 years ago) can also be deleted. My colleague Rene has a nice tool that allows you to bulk-destroy by first creating the appropriate work item query.
Be sure to run the cleanup jobs
TFS often doesn't directly prune data from the database, in many cases it just marks stuff as deleted for latest processing. To force the cleanup to happen immediately, run the following stored procedures on your Project Collection database:
EXEC prc_CleanupDeletedFileContent 1
# You may have to run the following command multiple times, the last
# parameter is the batch size, if there are more items to prune than the
# passed in number, you will have to run it multiple times
EXEC prc_DeleteUnusedFiles 1, 0, 100000

Other useful queries
To identify how much data is stored in each section, there are a few useful queries you can run. The actual query depends on your TFS version, but since you're preparing for migration I suspect you're on TFS 2017 or 2018 at the moment.
Find the largest tables:
SELECT TOP 10 o.name,
SUM(reserved_page_count) * 8.0 / 1024 SizeInMB,
SUM(CASE
WHEN p.index_id <= 1 THEN p.row_count
ELSE 0
END) Row_Count
FROM sys.dm_db_partition_stats p
JOIN sys.objects o
ON p.object_id = o.object_id
GROUP BY o.name
ORDER BY SUM(reserved_page_count) DESC

Find the largest content contributors:
SELECT Owner =
CASE
WHEN OwnerId = 0 THEN 'Generic'
WHEN OwnerId = 1 THEN 'VersionControl'
WHEN OwnerId = 2 THEN 'WorkItemTracking'
WHEN OwnerId = 3 THEN 'TeamBuild'
WHEN OwnerId = 4 THEN 'TeamTest'
WHEN OwnerId = 5 THEN 'Servicing'
WHEN OwnerId = 6 THEN 'UnitTest'
WHEN OwnerId = 7 THEN 'WebAccess'
WHEN OwnerId = 8 THEN 'ProcessTemplate'
WHEN OwnerId = 9 THEN 'StrongBox'
WHEN OwnerId = 10 THEN 'FileContainer'
WHEN OwnerId = 11 THEN 'CodeSense'
WHEN OwnerId = 12 THEN 'Profile'
WHEN OwnerId = 13 THEN 'Aad'
WHEN OwnerId = 14 THEN 'Gallery'
WHEN OwnerId = 15 THEN 'BlobStore'
WHEN OwnerId = 255 THEN 'PendingDeletion'
END,
SUM(CompressedLength) / 1024.0 / 1024.0 AS BlobSizeInMB
FROM tbl_FileReference AS r
JOIN tbl_FileMetadata AS m
ON r.ResourceId = m.ResourceId
AND r.PartitionId = m.PartitionId
WHERE r.PartitionId = 1
GROUP BY OwnerId
ORDER BY 2 DESC

If file containers are the issue:
SELECT CASE WHEN Container = 'vstfs:///Buil' THEN 'Build'
WHEN Container = 'vstfs:///Git/' THEN 'Git'
WHEN Container = 'vstfs:///Dist' THEN 'DistributedTask'
ELSE Container
END AS FileContainerOwner,
SUM(fm.CompressedLength) / 1024.0 / 1024.0 AS TotalSizeInMB
FROM (SELECT DISTINCT LEFT(c.ArtifactUri, 13) AS Container,
fr.ResourceId,
ci.PartitionId
FROM tbl_Container c
INNER JOIN tbl_ContainerItem ci
ON c.ContainerId = ci.ContainerId
AND c.PartitionId = ci.PartitionId
INNER JOIN tbl_FileReference fr
ON ci.fileId = fr.fileId
AND ci.DataspaceId = fr.DataspaceId
AND ci.PartitionId = fr.PartitionId) c
INNER JOIN tbl_FileMetadata fm
ON fm.ResourceId = c.ResourceId
AND fm.PartitionId = c.PartitionId
GROUP BY c.Container
ORDER BY TotalSizeInMB DESC

Comment: Thanks ever so much for your contribution @jessehouwing. Really appreciate it.


Using XDocument.Descendants with a coalesce operator ?? and nullable types

Question: Compiler:  Visual Studio 2019
Framework: .Net 2.1
Given a XML file like this:
<root>
  <data>
        <AdditionalOrderInfo>
            <AdditionalInfoItem key="{4567B566-A0A2-4214-B7E7-814FE179CDFC}" value="ScanItDental"/>
            <AdditionalInfoItem key="GlobalOrderID" value="EDC531BE6A0D4DC5BFEA0C6081D9F26B"/>
            <AdditionalInfoItem key="CreatedIn" value="22.214.171.124"/>
        </AdditionalOrderInfo>
    </data>
</root>

I need to get AdditionalInfoItem only for certain key values.
To avoid null errors I'm trying to use nullable types and coalesce operator ??
var additionalOrderInfo = document.Descendants(ns + "AdditionalOrderInfo").First();
var value = additionalOrderInfo.Descendants(ns + "AdditionalInfoItem")?.Where(el => el.Attribute("key").Value == "SomeKey")?.First()?.Attribute("value")?.Value ?? "";

But if key doesn't exists it returns:

Sequence contains no elements.

I've ended using a foreach loop in this way:
var additionalOrderInfo = document.Descendants(ns + "AdditionalOrderInfo").First();
foreach (var item in additionalOrderInfo.Descendants(ns + "AdditionalInfoItem"))
{
    switch (item.Attribute("key").Value)
    {
        case "SomeKey1":
            Order.SomeKey1 = item.Attribute("value").Value;
            break;
        case "SomeKey2":
            Order.SomeKey2 = item.Attribute("value").Value;
            break;
    }
}

Is there a way to avoid the foreach loop and read the value using a single line of code?
Comment: _If_ I'm understanding correctly, why would the `foreach` be needed if `additionalOrderInfo` is `null`? IOW, if there is no orderinfo, why would there be items to loop into?
Answer: Try use FirstOrDefault instead of First only after Where selector:
var value = additionalOrderInfo.Descendants(ns + "AdditionalInfoItem")?
                               .Where(el => el.Attribute("key").Value == "SomeKey")?
                               .FirstOrDefault()? // <--- Here
                               .Attribute("value")?.Value ?? "";

If Where(el => el?.Attribute("key")?.Value == "SomeKey") return 0 elements, you getting Sequence contains no elements exception, so you can't get First element of it. FirstOrDefault returns null instead, so next nullcheck ? goes forward.


Realm reset schema version

Question: I'm currently in the process of writing an app that uses Realm as a database. As I'm still writing it my models have invariably changed from what I initially designed. Unfortunately every time this happens I need to update a migration block.
Is there anyway to 'reset' my Realm so that until it's actual in 'production' I don't need to worry about Migration blocks at all? It's particularly a pain with some unit tests, I do actually delete all the tables when the tests run, but I'm assuming there must be a best practice to handle this
Specifically I am working in an iOS/Swift app.
Answer: Yes, there is very useful solution, just type:
<code>var config = Realm.Configuration()
config.deleteRealmIfMigrationNeeded = true
</code>
Comment: Is there something similar to .NET and C#?
Comment: this is pretty much c# ...

RealmConfiguration config = new RealmConfiguration(realm_db_name);
                config.ShouldDeleteIfMigrationNeeded = true;

                var realm = Realm.GetInstance(config);
Comment: Is it a good idea to use this in tests? It solves the problem of migrations. If not please suggest how to handle migrations in tests?
Comment: You shouldn't rely on real database in tests but on mock conforming to database protocol instead

Realm reset schema version


How to send file parameter to Cloudinary post request in angular2

Question: I am uploading image file to cloudinary with their image upload API.
I am implementing it like this,
Html code
<input type="file" ng2FileSelect [uploader]="uploader"/>
<button class="btn btn-primary" (click)="uploadImages()">Upload</button>

Typescript Code
  public uploader: FileUploader = new FileUploader({});

  uploadImages() {
    const params = this.createUploadParams();
    this.upload(params)
      .subscribe(data => {
        console.log("response", data);
      })
  }

  private createUploadParams() {
    return {
      file: this.uploader.queue[0].file,
      upload_preset: env.CLOUDINARY_UPLOAD_PRESET,
      pulic_id: 'PUBLIC_ID'
    }
  }

  upload(params) {
    return this.http.post(`${this.apiLink}/image/upload`, JSON.stringify(params))
      .map(data => data);
  }

But it is giving me the following error
"{"error":{"message":"Missing required parameter - file"}}

I am using ng2-file-upload to upload the files in angular2.
Answer: You need to add the file and upload preset thru a FormData object, and add headers to the request as follows:
Import Http and Headers from @angular/http:
import { Http, Headers } from '@angular/http';

Update the code that uploads the files:
uploadImages() {
  const params = this.createUploadParams();
  this.upload(params)
    .subscribe(data => {
      console.log('response', data);
    });
}

private createUploadParams() {
  let formData: FormData = new FormData();
  formData.append('upload_preset', env.CLOUDINARY_UPLOAD_PRESET);
  formData.append('file', this.uploader.queue[0]._file);
  return formData;
}

upload(params) {
  let headers = new Headers();
  headers.append('X-Requested-With', 'XMLHttpRequest');
  return this.http.post(`${this.apiLink}/upload`, params, {headers})
  .map(data => data);
}

You can find an additional example of using ng2-file-upload here


Adding 3rd party jQuery code to our Rails RTF text box

Question: I am adding a 3rd party feature into an existing rails app. The 3rd party gave me a piece of code which I am supposed to drop into my codebase but I'm confused as to where this should be posted.
Posted is the 3rd party which I am supposed to add to my codebase:

Posted is the existing code in my app for the form.
_post_form.html.erb

    Body
    <textarea id="textbox">
        <%= @post.body %>
    </textarea>
    <%= form.hidden_field :body, :id => 'body_hidden_input' %>
    <%= errors_for_field :body %>

Where should this be posted? Does it go in a separate .js file or can I paste it right into the embedded ruby? Any insight would be great.
Answer: Make a .js file in your /app/assets/javascripts folder.
make sure your "application.js" file has //= require_tree . at the end.


Upload zip file by Nusoap in PHP and C#

Question: I want to upload file with C# client app and Nusoap webservice. How i can do this? I use Nusoap webservice for insert in database but for upload files i don't have any idea. Please help me.
Thanks.
Answer: As I haven't any experience with NuSOAP, I shall answer with the best of my knowledge of uploading a file to a server running PHP, without using NuSOAP.
The following code will POST the contents of a given file to a PHP page, as if it was sent via a standard HTML form.
public void UploadFile(string path) {
    WebClient wc = new WebClient();
    wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
    Int64 numBytes = new FileInfo(path).Length;
    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);
    Byte[] data = br.ReadBytes(Convert.ToInt32(numBytes));
    br.Close();
    fs.Close();
    wc.UploadData("http://127.0.0.1/upload.php", "POST", data);
}

Edit: Here is the PHP that I used for this a while ago. It is potentially insecure and will always overwrite the same file every time a new one is being uploaded. You could try to work some dynamic-ness into this, along with some file checks for security sake... but you should also be able to use a modified PHP file intended for standard uploads (from a web form).

<?php
    $fp = fopen('snap.jpg', 'wb');
    fwrite($fp, file_get_contents('php://input'));
    fclose($fp);
?>

Comment: Hi and thanks about your answer. But whats content of upload.php? Is it similar to any upload form or not?
Comment: Can you help me about uploading file in PHP ?
Comment: Sorry, I was sleeping. I have edited my answer with the PHP that I used to store the file. Note that there are securer and better ways of doing this.

Upload zip file by Nusoap in PHP and C#


É possível trabalhar com Enumeradores em Javascript?

Question: Comumente usados em diversas linguagens os Enumeradores facilitam a vida dos desenvolvedores quando se necessita criar uma "lista" de valores contantes dentro de uma aplicação. Dentro do Javascript é possível usar essa estrutura ?
Answer: O Javascript não possui enumeradores nativamente mas é algo que consegue implementar com relativa facilidade.
Exemplo:

const corSemaforo = {
  VERDE: 0,
  AMARELO: 1,
  VERMELHO: 2
};

let cor = corSemaforo.VERDE;

if (cor == corSemaforo.VERDE) {
  console.log("O semaforo está verde");
}

Até pode melhorar esta ideia e atribuir strings com valores mais expressivos em vez de números.
const corSemaforo = {
  VERDE: "Verde",
  AMARELO: "Amarelo",
  VERMELHO: "Vermelho"
};

Assim se escrever o valor de um semaforo algures terá a representação do mesmo em texto:
console.log(corSemaforo.VERDE); //Verde

Imutabilidade
Apesar de ter sido declarado como const apenas a referência ao objeto é constante o seu conteúdo pode ser modificado. Isto faz com que o programador possa inadvertidamente alterar o enumerado acrescentando, removendo ou alterando propriedades.
Veja o problema:

const corSemaforo = {
  VERDE: "Verde",
  AMARELO: "Amarelo",
  VERMELHO: "Vermelho"
};

corSemaforo.AZUL = "Azul"; //agora já tem mais uma cor
delete corSemaforo["VERDE"]; //removeu o verde

console.log(corSemaforo); //agora sem VERDE e com AZUL

Para evitar este problema podemos utilizar a função freeze de Object que impede o objeto de ser alterado:

const corSemaforo = {
  VERDE: "Verde",
  AMARELO: "Amarelo",
  VERMELHO: "Vermelho"
};

Object.freeze(corSemaforo); //impede futuras alterações

corSemaforo.AZUL = "Azul"; //já não adiciona
delete corSemaforo["VERDE"]; //já não remove

console.log(corSemaforo);
Comment: Esta resposta merece uma recompensa.


metric $d(a,b)=2\frac{|a-b|}{a+b},a,b>0$ satisfies triangle inequality

Question: How to show that metric $d(a,b)=2\frac{|a-b|}{a+b},a,b>0$ satisfies triangle inequality? That is,
$$d(a,b)+d(b,c)\geq d(a,c)$$
for $a,b,c>0$
My thought: $a$ and $c$ are symmetric, and we can assume $a<c$. Discuss the following three cases respectively:

$b<a<c$
$a<b<c$
$a<c<b$

In each case, we can strip off the absolute symbol and use brute force method to show the inequality holds.
Is there any elegant way to prove this equality?
Comment: Don't know that you'll find too elegant a way to prove it. See [What is this distance about?](https://mathoverflow.net/questions/229989/what-is-this-distance-about/230005) and the posted links on MO.
Answer: Let $a\geq b\geq c$.
Hence, $$\frac{a-c}{a+c}-\frac{b-c}{b+c}=\frac{2c(a-b)}{(a+c)(b+c)}\geq0$$ and
$$\frac{a-c}{a+c}-\frac{a-b}{a+b}=\frac{2a(b-c)}{(a+b)(a+c)}\geq0.$$
Thus, it's enough to prove that
$$\frac{a-b}{a+b}+\frac{b-c}{b+c}\geq\frac{a-c}{a+c}$$ or
$$\sum_{cyc}\frac{a-b}{a+b}\geq0$$ or
$$\frac{(a-b)(a-c)(b-c)}{\prod\limits_{cyc}(a+b)}\geq0,$$ which is obvious.


Network topology

Question: I am writing a network application that has several machines that serve separate clients, but machine themselves need to communicate with each other frequently. Let's say multiple chat servers for example. How do I accomplish the server to server communication in terms of network architecture. I don't want each server to have a connection open with all other servers. Any ideas, pointers or suggestions would help. As a client developer, I am brand new to any of these. Thank you!
Answer: Why don't you want each server to have a connection open with all other servers?  You could always install 2 NICs in each server.  One NIC would serve clients and the other NIC would be used for server-to-server communication.  Another option would be to create VLANs but I still don't understand why don't you want each server to have a connection open with all other servers?
Comment: Thanks, I meant I don't want to use server to server socket connections for all servers; is not scalable to have each server have a socket open to every other server. How do I set up VLANs may be is a more appropriate question?

Can I have something like this?

where each node is a server connected to another server, whereas the leaf nodes serve clients, the tree nodes route packets between destinations.

Does it need to be in software? Or can be accomplished with hardware.
Comment: This graph type solution is software based, where each tree server forwards packets from one leaf src to another leaf dst. If accomplished with h/w this can be delegated to DNS resolution. Is that correct?
Answer: If the communication does not need to be instantaneous you could just use a central database server to store the messages (or whatever is being communicated) and then the other servers can pick them up when they are ready.
An alternative would be to use a central server to act as an exchange, basically sitting waiting for messages then forwarding them to daemons on other servers as required. Doing it this way would be a lot more complex than the db option tho' as you would have to have methods in place to ensure that messages are actually passed on and some sort of retry mechanism for when they cannot be forwarded.

Network topology


Use the Lagrange multiplier method to find the maximum possible volume for a rectangular box inscribed in the ellipsoid $2x^2 + 3y^2+4z^2=12$

Question: I know I have the correct value of $x, y, z$ but I get a different value for the volume.
My workings:
$$ f=xyz, g=2x^2+3y^2+4z^2-12, \psi=f+\lambda g $$
$$ \psi_x = yz+4\lambda x=0 $$
$$\psi_y = xz+6\lambda y=0 $$
$$\psi_z = xy+8\lambda z=0$$
$$2x^2+3y^2+4z^2=12$$
Solving the simultaneous equations gives,
$$ x=\sqrt2, y=\frac2{\sqrt3}, z=1$$
I know this bit is correct but when I try to calculate the volume my answer is incorrect
$$f(\sqrt2,\frac2{\sqrt3},1) =\frac{2\sqrt6}{3} $$
but they give the answer as
$$ \frac{16\sqrt6}{3} $$
which is clearly 8 times my answer
I did a similar question and once again I got the correct x,y,z but the volume was 8 times my answer, but I cant see why they are multiplying by 8
Comment: The length of the edges are $2x$, $2y$ and $2z$. Hence, the volume is $8xyz$.
Comment: The coordinates for the corners are $(\pm x, \pm y, \pm z)$
Comment: How do you know the length of the edges are 2x, 2y and 2z?
Comment: Draw a picture, the box is centred at $(0,0,0)$.
Answer: The formula you have for the volume ($V=xyz$) is the volume of the portion of the box in the first octant. But there are 8 octants, each symmetric to the first, so the volume should really be calculated as
$$V=8xyz$$
Updating your solution with the new objective function, it is clear that $x,y,z$ do not change--only the lagrange multiplier $\lambda$ will be 8 times its previous value.
Plugging in the $x,y,z$ you found, we get that the volume is $\frac{16\sqrt{6}}{3}$, as the given solutions indicate.

To help with the intuition surrounding this problem, we can reduce it to the 2D case. Consider the (poorly drawn) image below, and let $(x,y)$ be the coordinates of the upper right corner of the red box.

Then you have that the area of the red box is $A=xy$, but the acutal area of the insctibed rectangle is the orange box, given by $A=4xy$, doubling once for each dimension.
In the 3D case, there are 3 dimensions in which the volume needs to be doubled, but the concept is the same.


Galaxy Note 4 CSS Pixels

Question: Does anyone know what the CSS pixel resolution for the Galaxy Note 4 is?  I can't seem to find this or the device pixel ratio anywhere.
A couple places I've looked that I thought would have this information but don't:
<code>http://viewportsizes.com/
http://www.devicepixelratio.com/
http://en.wikipedia.org/wiki/Samsung_Galaxy_Note_4
http://www.samsung.com/global/microsite/galaxynote4/note4_specs.html
</code>
Comment: Are you specifically asking about the hw pixel to css pixel ratio in the browser? Because the hw resolution is 515 ppi according to [a quick Google](http://www.gsmarena.com/samsung_galaxy_note_4-6434.php).
Comment: I'm not sure what hw resolution is but I don't think we are talking about the same thing. Here is an article that explains what CSS pixels are. http://www.quirksmode.org/blog/archives/2010/04/a_pixel_is_not.html
Answer: I think it is 360x640 with a density of 4.
Answer: According to this its 640x360 with a DPR of 4.
http://www.canbike.org/CSSpixels/

Galaxy Note 4 CSS Pixels


What does "versus" mean in the context of a graph?

Question: Say you have a graph of say $y=mx+b$, with $x$ on the horizontal axis and $y$ on the vertical axis. You need to give the graph a title, would you say:
This is a graph of "$y$ versus $x$?"
or
This is a graph of "$x$ versus $y$?"
Is the independent variable always first like $independent$ versus $dependent$, when you say versus or, the other way around?
Tried general searching, and doing a CTRL+F for "versus" on graphing related Wikipedia pages but couldn't find anything on this, hopefully im not the only one who has been confused by this?
To clarify, the problem im stuck on because of this, and from other encounters with this terminology, the side of "versus" a variable is on, is related to which variable is the independent variable and which is the dependent variable. That is the relationship i am asking about. Not whether $y$ is a function of $x$ or vice versa.
Comment: In my experience that terminology isn't really used, so if no one else is confused by it, it's probably because of that.  Personally, I'd be inclined to say 'independent versus dependent', but don't really know why I'm inclined towards that.
Comment: I can honestly say i don't think i have heard the "versus" terminology used in math courses, but i hear it and see it used all the time in other sciences courses, chemistry, physics, etc. Ive wondered about it for so long but am finally stuck on something, where the interpretation is makes or breaks the answer. And i just cant tell at all from context, any hints to how the "versus" is being used...
Comment: Logically, I'd say "$x$ versus $y$" since you're seeing what $y$ results from a given $x$.
Answer: In physics, this is usually used as dependent versus independent as in a velocity versus time or position versus time graphs. See Motion graphs and derivatives as well as from Line chart we have "The chart can then be referred to as a graph of 'Quantity one versus quantity two, plotting quantity one up the y-axis and quantity two along the x-axis.' "

Some other references - Physics from University of Kentucky, the same question on English Stack Exchange, Astrophysics from University of Chicago. Nothing that would be considered a primary source if you are doing a research paper but enough to support dependent versus independent.
Comment: I would agree with the rule "[dependent] versus [independent]." The word "versus" can mean "compared with," and it more frequently makes sense to compare a dependent value with its associated independent value, because well, the independent variable doesn't really "care" about the existence of the dependent variable, but the converse relationship is by definition.
Comment: Not to nitpick, but on the page http://en.wikipedia.org/wiki/Line_chart , the Structure section doesn't have any references, nor does the Example section below it. Something i guess more authoritative or definitive would be helpful?
Answer: I have always interpreted "y vs. x" as y = f(x) with y the dependent variable and x as the independent variable and will continue to do in my mathematics and physics lectures.
Answer: The answer (as is often the case) come from Latin.  "versus" simply means against and is used in the sporting context as well.  We say that in some contest "Team A versus team B", meaning team A is against team B.  The graph is the same - one variable is plotted against (or versus) another.  From the same cognate root we also get the English "adversary".


View an image in ASP.NET MVC 5

Question: I can view an image in index file like this :
    @*@Html.DisplayFor(modelItem => item.ImagePath)*@//Instead of this, I use the line below

But In details file I have this :
@Html.DisplayFor(model => model.ImagePath)

How can I view the image in details file when there is a model not item? I have done several attempts but failed all of them. Thanks.
Comment: what is the text coming ``Model.ImagePath``?
Comment: Possible duplicate of http://stackoverflow.com/questions/15986980/how-to-display-image-from-path-in-asp-net-mvc-4-and-razor-view
Answer: You can use custom template and dataannotations
http://msdn.microsoft.com/en-us/library/ee308450(v=VS.100).aspx
http://www.codeproject.com/Tips/720515/Custom-HTML-Helper-for-MVC-Application
Comment: Thank you but how do those links answer my question?
Answer: The answer should be like :

Answer: This razortag string " @Html.DisplayFor(model => model.ImagePath) " is calling the DB, getting the path and then presenting the path string as its output. In the Index view " item.ImagePath " is a variable that has been populated and currently contains the path ready for output. In the Details view, there are no variables, and the ImagePath is empty because the function has not run. Well technically it ran once but since it delivered its output to the view it is again empty by the time you try to use it. To get the ImagePath as your img src call the whole function where you are placing the image and it will run again and its output will be the ImagePath used for the img src.
This also will work in the Index view as well. The codeproject.com link in the above answer provides some relevant ideas.
" model.ImagePath)"

View an image in ASP.NET MVC 5


public int Continue() : (Not all code paths return a value)

Question: I have written this function to use it into another class, but code generates an error and says,
Not all code paths return a value.
I also tried to search the solution regarding this problem and most of the answers were irrelevant to the actual problem.
Hoping to bump into the logical understanding for this kind of same errors.
using System;

namespace Practice
{
    class ContinueAgain
    {
        public int Continue()    //    (Not all code paths return a value)
        {
            rerun:
            try {

                char chAgain;

                //  user guiding message and then taking input
                Console.WriteLine("\nAgain? (y/n)\n");
                chAgain = char.Parse(Console.ReadLine());

                //  filtering the condition if the user wants to continue or not
                //  exiting out of the method if user selects 'Y'/'y'
                if (chAgain == 'y' || chAgain == 'Y')   //  if block begins
                {
                    return 1;
                }

                //  exiting out of the method if user selects 'N'/'n'
                else if (chAgain == 'n' || chAgain == 'N')
                {
                    Console.WriteLine("\nThank you for using :)\n");
                    return 0;
                }

                // printing user message if user enters any input apart from the asked input
                if(chAgain!='y' || chAgain!='Y' || chAgain!='n' || chAgain!='N')
                {
                    Console.WriteLine("\nThis input in invalid\n");
                    goto rerun;
                }
                #endregion if block 4 - ends
            }   //  try block ends

            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

Would like to know what's causing or triggering this error event.
Comment: tip 1: ***do not*** use goto. just don't. ever. tip 2: go through your code line by line and think about what's happening. when an exception happens, you go to your catch-block, write a line, and end the method _without returning anything_
Comment: also: it seems what your method does is decide _whether or not_ something should happen. please use ***boolean*** for binary choices, not numeric datatypes. that's what booleans are made for.
Comment: You should completely review and improve this code and likely this will also fix your isse. As example, this if will always be true: if(chAgain!='y' || chAgain!='Y' || chAgain!='n' || chAgain!='N'). It seems you don't think about the difference between || and &&
Answer: You need to return a value inside the catch block and at the end of the try block.
Answer: There are 2 missing return statements in your code - after the last if statement and in the catch block


block of code that won't work. fopen function and %d

Question: I am
trying to open multiple files with the 'j+1' counter and the '%d'
but won't work.
here is the piece of code.
#include <stdio.h>
#include <alloc.h>

FILE *string;
int j=0;

int main(void)
{
    for (j=0;j<10;j++)
    {
        string = fopen(("C:\\playlist%d.txt",j+1),"w+t");
        fclose(string);
    }
    return 0;
}

Answer: You need to use an array to create the file name using sprintf and use the array in the call to fopen.
int main(void)
{
   char filename[100]; // Make the array large enough
   for (j=0;j<10;j++)
   {
      sprintf(filename,"C:\\playlist%d.txt",j+1);
      string = fopen(filename,"w+t");
      fclose(string);
   }
   return 0;
}

Answer: EDIT This question originally had the C++ tag.

FILE* string;
...
string = fopen(("C:\\playlist%d.txt",j+1),"w+t");

It seems you wanted to build a filename string with an integer value embedded inside.
(BTW: The choice of "string" as the name of the FILE* variable is not very helpful, I'd suggest using something more meaningful...)
Since this question is tagged with [c++], you may want to use a convenient string class for that, with its overloaded operators, and the std::to_string() helper function to convert an integer to a std::string, e.g.
std::string fileName = "C:\\playlist";
fileName += std::to_string(j+1);
filename += ".txt";

FILE* file = fopen(filename.c_str(), /* other params */);

PS In addition to C's FILE*, in C++ there are specific file stream classes available for file management, like std::fstream and related ones.
Answer: EDIT: The question was originally tagged with C++
As this is tagged as C++ you can do this with std::string and std::fstream
int main()
{
    std::string filename = "C:\\playlist";
    std::fstream file;
    for (int i = 0; i < 10; i++)
    {
        file.open(filename + to_string(i) + ".txt");
        // do stuff
        file.close();
    }
    cin.get();
    return 0;
}


Ansible: copy file depending on hostname or role

Question: What's the best way to copy over a file depending on a hostname?
I need to copy over files with different content but with the same filename to several machines.
I have several files:
file.role1
file.role2
file.role3

Depending on hostname and/or role, I'd like like to copy file.roleX and rename it to file
Thanks.
Answer: There are many ways to do this. Simplest:
- name: Copy file.role1 to host1
  copy: src=file.role1 dest=/somewhere/file
  when: inventory_hostname == "host1"
- name: Copy file.role2 to host2
  copy: src=file.role2 dest=/somewhere/file
  when: inventory_hostname == "host2"

Alternative, more compact:
- name: Copy file to host
  copy: src=file.{{ inventory_hostname }} dest=/somewhere/file

Or, using a template:
- name: Copy file to host
  template: src=file dest=/somewhere/file

where the template can be something like this:
{% if inventory_hostname == "host1" %}
{% include "file1" %}
{% endif %}
...

If you want different files in different roles, why don't you simply put this:
- name: Copy file.role1 to file
  copy: src=file.role1 dest=/somewhere/file

in each role's code?
There is no preferred way to do it - it depends on what you are actually trying to accomplish.
Comment: bonus points for [TIMTOWTDI](https://en.wikipedia.org/wiki/There%27s_more_than_one_way_to_do_it)!
Comment: Thanks -- I was actually for a different apt.sources file depending on OS & architecture without creating a mess or having too many roles/a big inventory file. I went for a variable behind the hostname in the inventory file: sources_list=debian and that causes sources.list.debian to copy to sources.list.


How do I reopen MDI forms that were open during last application run?

Question: Is there any standard method to save and restore the state(which forms were open and where on screen), when using MDI forms?
Yes, i can save the values from MdiChildren to a file and restore them on application start.
That is not what I am looking for.
Is there a standard way to do this?
If you have a method that is better than serializing values from MdiChildren, do post it.
Comment: It's configuration, so it can be stored, as you mentioned 1) serialized in files 2) in database 3) in registry. Choose the way that serves you best of all.
Answer: After searching quite a bit, here is the conclusion:
No, there is no standard solution.
Writing the parts of data you need to restore the window and its state is really easy.
Just serialize and write to a file on the Closed event on the MdiParent.
(Events like Application.Exit are too late to serialize. Forms are already closed).
Read it back, populate whatever you want and then Show the the child forms on Load of the MdiParent.
I will accept this as the answer, cause it is what I used and I don't like leaving around unanswered questions.


Construct a complete metric on $(0,1)$

Question: Can anyone construct a complete metric on $(0,1)$ which induces the usual subspace topology on $(0,1)$ ?
Comment: Hint: What complete metric space is $(0,1)$ homeomorphic to?
Comment: What is the obvious space $(0,1)$ is homeomorphic to? What have you tried and where are you stuck?
Comment: @TedShifrin : I see that $\mathbb{R}$ should be the choice.. I mean $\mathbb{R}$ is complete and homeomorphic to $(0,1)$.. Now... what should be the next step :O
Comment: @TedShifrin : Sir, look at this.... May day... May day... :)
Comment: Sorry. I missed your earlier response. Yes, it's right. Write down a homemorphism $f$ from $(0,1)$ to $\Bbb R$ and use $f$ and the metric on $\Bbb R$.
Comment: @TedShifrin : Thank you sir.. I got it :)
Answer: The map
$$
f:(0,1)\to\mathbb{R}:x\mapsto\tan\pi\left(x-\frac{1}{2}\right)
$$
is a bijection which allows you to define the metric
$$
d(x,y)=|f(x)-f(y)|
$$
which makes $((0,1),d)$ complete. Since $f$ maps intervals to intervals then both topologies are equivalent.
Answer: Define the function $f$ on $X=(0,1)$ by
$$f(x)=\dfrac{2x-1}{x(1-x)}=\dfrac1{1-x}-\dfrac1x,
$$
for every $x$ in $X$, and use $f$ to define a metric $d$ on $X$ by $$d(x,y)=|f(x)-f(y)|,$$ for every $x$ and $y$ in $X$. Then the metric space $(X,d)$ is complete, and its topology is the usual one.
Every function $f:X\to\mathbb R$ would do as soon as $f$ is continuous, increasing, and has limits $-\infty$ at $0$ and $+\infty$ at $1$.
Answer: More generally, if $O$ is an open subspace of a Polish space $X$, then $O$ is a Polish space. An argument is to consider the inclusion $$\left\{ \begin{array}{ccc} O & \to & X \times \mathbb{R} \\ x & \mapsto & \left( x, \frac{1}{d(x,X \backslash O)} \right) \end{array} \right..$$
Then $O$ is closed in $X \times \mathbb{R}$ (roughly speaking, $\partial O$ is "pushed to the infinity" in $X \times \mathbb{R}$) and $X \times \mathbb{R}$ is completely metrizable using the distance $$((x_1,y_1),(x_2,y_2)) \mapsto \max (d(x_1,x_2), |y_1-y_2|).$$
For the specific example $X= \mathbb{R}$ and $O= (0,1)$, it gives the distance $$(x,y) \mapsto \max \left( |x-y| , \left| \frac{1}{\min(x,1-x)}- \frac{1}{\min(y,1-y)} \right| \right).$$

Construct a complete metric on $(0,1)$


Most efficient way to modify xml

Question: I'm writing an app that needs to modify xml documents.  More precisely it need to add attributes and add/delete nodes.  These documents are relatively small, 30-50K at most.  From what I'm reading the best way to read XML is use the SAX parser, but does that apply to modifying XML as well?  The DOM parser seems to be the easiest to manipulate XML with, but, obviously, uses more battery and memory.
Just looking for the most efficient way (uses the least battery/memory) to manipulate XML on an Android device.
Answer: I suggest XOM - It is very memory efficient and support dual streaming/tree-based API.
Answer: The most efficient way to modify XML is to use VTD-XML(http://vtd-xml.sf.net)...it is the only way to do so called incremental update..

Most efficient way to modify xml


Apple Store Connect Api http request returns error 404 not found

Question: I'm having some issues establishing a connection with this API, in concrete https://api.appstoreconnect.apple.com/v1/salesReports. But I'm receiving the error 404 not found as a response to my request. The real problem is that this same code, with the same parameters, was working yesterday.
I have been reading, and sometimes this API stops working, but I found here https://developer.apple.com/system-status/ that, this cannot be.
I also have thought that, as I'm using tokens to establish this connection, maybe they have expired (but I haven't been able to find any info related to this).
Any idea why this is happening?
I leave here my code, just to verify, that this is not the problem.
First the token generation function code (I'm hiding some parameters for privacy reasons)
public static string GenerateAppStoreJwtToken(string privateKey)
        {
            var header = new Dictionary<string, object>()
            {
                { "alg", "ES256" },
                { "kid", "XXXXXXXXXX" },
                { "typ", "JWT" }
            };

            var payload = new Dictionary<string, object>
            {
                { "iss", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" },
                { "exp", DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds() },
                { "aud", "appstoreconnect-v1" }
            };

            CngKey key = CngKey.Import(Convert.FromBase64String(privateKey), CngKeyBlobFormat.Pkcs8PrivateBlob);

            string token = JWT.Encode(payload, key, JwsAlgorithm.ES256, header);

            return token;
        }

And here is my function that makes the request. (Also hiding some parameters for privacy reasons)
private async Task GetHttpRequest(string privatekey)
        {

                //We generate the token
                TokenClass token = new TokenClass(privatekey);

                //Configuration of the requesting
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.token);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/a-gzip"));
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                //Init the request
                Stream response = await client.GetStreamAsync("https://api.appstoreconnect.apple.com/v1/salesReports" +
                    "?filter[frequency]=DAILY" +
                    "&filter[reportSubType]=SUMMARY" +
                    "&filter[reportType]=SALES" +
                    "&filter[vendorNumber]=XXXXXXXX");

            }

The error that outputs is:
Unhandled Exception: System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found).
Answer: I find out the issue. This API creates the report each day at specific time, so if you ask for a report that hasn't been created yet, the response would be error 404 (Not Found).
This was my error, but be aware that there are many conditions to use these filters.
Check the following link, all the conditions are explained https://help.apple.com/app-store-connect/#/dev8a5831138 .


correlation between two different variables

Question: I am studying stochastic processes and found the next problem:
Let $A$ and $\Phi $ be two independent random variables such that $E(A) = 0$, $E(A^2) < \infty$, and $\Phi$ is uniformly distributed on $[0, 2\pi]$. Consider the stochastic process
$$X_t =A \cos{(\Phi+λt)}, t≥0$$
where $\lambda$ is a fixed real parameter.
Show that the correlation between two different variables of the process is given by
$$E(X_tX_s)= \frac{1}{2}E(A^2)\cos {\lambda}(t-s)$$
what i have done:
Using the fact that $Cov (X_s, X_t) = E\{ (X_s - EX_s)(X_t - EX_t) \}$, I compute this and found that $Cov (X_s, X_t) = E(A^2)E\{ \cos(\Phi + \lambda s)\cos (\Phi + \lambda t)- A \cos (\Phi +\lambda s)E(A \cos (\Phi + \lambda t )) - E(A \cos (\Phi+\lambda s))A\cos (\Phi+\lambda s) + E(A)E(A)E(\cos (\Phi+\lambda s) \cos (\Phi + \lambda t))  \}$
Using the hipothesis $E(A) = 0$,
I have that
$Cov (X_s, X_t) = E(A^2)E(\cos (\Phi + \lambda s) \cos (\Phi + \lambda t))$
but I don't know how to calculate $E(\cos (\Phi + \lambda s) \cos (\Phi + \lambda t))$, I know that I need to use the fact that $\Phi \sim U_{[0, 2\pi]}$ but I don't know how to do this
(I think that if I can make this, is possible to use the theorem that says $Cov(X,Y)= E(XY)- EXEY$ to solve the problem)
Comment: Use the fact that $\cos(\Phi+\lambda t)\cos(\Phi+\lambda t) = \frac{1}{2}(\cos (\lambda(t-s))+\cos(2 \Phi+\lambda(t+s)))$.
Answer: Note that $$\cos(x) \cdot \cos(y) = \frac{1}{2}(\cos(x-y) + \cos(x+y))$$
i.e. $$\cos(\Phi+\lambda \cdot s) \cdot \cos(\Phi+\lambda \cdot t) = \frac{1}{2} \cdot( \cos(\lambda \cdot (t-s)) + \cos(2\Phi+\lambda \cdot (s+t))$$
Thus $$\mathbb{E}\big(\cos(\Phi+\lambda \cdot s) \cdot \cos(\Phi+\lambda \cdot t)  \big) = \frac{1}{2} \left( \cos(\lambda \cdot (t-s)) + \mathbb{E}\cos(2\Phi+\lambda \cdot (s+t)) \right)$$
Moreover,
$$\mathbb{E}\cos(2\Phi+\lambda \cdot (s+t))  = \frac{1}{2\pi} \int_0^{2\pi} \cos(x+ \lambda \cdot (t+s)) \, dx$$ since $\Phi \sim U(0,2\pi)$. By the periodicity of $\cos$ we conclude $$\mathbb{E}\cos(2\Phi+\lambda \cdot (s+t))=0$$
So we arrive at $$\text{cov}(X_s,X_t) = \frac{1}{2} \mathbb{E}(A^2) \cdot \cos(\lambda \cdot (t-s))$$
By the way, there is a typo in the second line of your computations: Instead of $$\mathbb{E}(A) \cdot \mathbb{E}(A) \cdot \mathbb{E}(\cos(\Phi+\lambda \cdot s) \cdot \cos(\Phi+\lambda \cdot t))$$ it should read $$\mathbb{E}(A) \cdot \mathbb{E}(A) \cdot \mathbb{E}\cos(\Phi+\lambda \cdot s) \cdot \mathbb{E}\cos(\Phi+\lambda \cdot t)$$ (Of course, that doesn't change anything in this case since $\mathbb{E}(A)=0$.)
Comment: Momentary lack of caffeine. Have deleted the comment.
Comment: thank u, I really appreciate your help


Proof: Between two distinct real numbers ther is a rational number.

Question: I found this proof:
If $a<b$, there is a rational $\frac{p}{q}$ with q fixed, and p any integer.
Consider the set of numbers of the form $\frac{p}{q}$ with $q$ fixed, and $p$ any integer.
Assume that there are no such numbers between $a$ and $b$. Let $\frac{p}{q}$ be the number immediately before $a$. Then $\frac{p+1}{q}$ is the number immediately after $b$. We necessarily have
$$\frac{p+1}{q} - \frac{p}{q} \geq b - a \Leftarrow\Rightarrow \frac{1}{q} \geq b-a$$
If we choose q sufficiently large, then the above inequality is wrong. Then there is at least one rational number between $a$ and $b$.
For example:
I have $a=1$ and $b=3$, $\frac{p}{q}= \frac{1}{1}$ and  $\frac{p+1}{q}=\frac{1+1}{q}= \frac{2}{1} $ and $\frac{2}{2} \ngeq 3$.
How is it possible that this works for $a=1$ and $b=3$?
Comment: That statement is false. What if $a=\frac13$, $b=\frac23$, and $q=1$?
Comment: If $q=1$ and $p=1$ then $\frac{p}{q}= \frac{1}{1}=a$, and the next $p=2$ with the same $q$ works: $\frac{p}{q}= \frac{2}{1}=2$ is between $a=1$ and $b=3$.
Answer: The spirit of the proof is this: if you dilate the interval $[a,b]$ by a factor $q$ sufficiently large that $qb-qa>1$, then the interval will contain at least one integer $p$, and the fraction $\dfrac pq$ is a rational in $[a,b]$.
With $a=1,b=3,q=1$, the condition is fulfilled (we have the three rationals $\dfrac11,\dfrac21,\dfrac31$).
Comment: helped thank you
Answer: You have changed the value of $q$ in your example. It should be $\frac{p+1}{q} = \frac{1+1}{1} = 2$ instead of 1. Apart from that mistake, the proof says "If we choose $q$ sufficiently large". Obviously $q=1$ is not large enough.
Comment: But $q=1$ *is* large enough in this case, $2/1$ is between $1$ and $3$.
Comment: But $\frac{p+1}{q}$ should be greater than 3, that's why isn't large enough.
Comment: It shouldn't, just the opposite. "If we choose $q$ sufficiently large, then the above inequality is wrong. Then there is at least one rational number between a and b". *When* $q$ is large enough we do not blow past $b$ when adding $1$ to $p$, and get an intermediate rational.


Pegando o valor da tabela com ckeckbox e passando para o controller com AngularJS

Question: Boa Noite!
Estou com um problema que ainda não encontrei uma solução
Primeiro eu faço uma consulta no banco de dados que me retorna alguns valores e eu jogo dentro de uma tabela com ng-repeat
Tabela

{{contrato.NOME}}
{{contrato.CPF_CONTRATO}}
{{contrato.NUMERO_CONTRATO}}
{{contrato.FISICO}}
<input type="checkbox" />

até ai tudo bem, mas eu preciso fazer com que ao clicar no checkbox eu pegue o NUMERO_CONTRATO e passe para uma function no meu controller
Function
$scope.PegaContrato = function () {

}

Answer: Adicione o argumento ng-click ao seu checkbox:
<input type="checkbox" ng-click="PegaContrato(contrato.NUMERO_CONTRATO)">

Depois modifique a sua função para receber o valor:
$scope.PegaContrato = function (numero_contrato) {
    console.log(numero_contrato);
}

Pronto, assim você já consegue saber qual o contrato foi selecionado.

UPDATE:
Se houver necessidade de remover um contrato selecionado (ação inversa), adicione o argumento ng-checked ao seu checkbox:
<input type="checkbox"
    ng-click="PegaContrato(contrato.NUMERO_CONTRATO)"
    ng-checked="contratos.indexOf(contrato.NUMERO_CONTRATO) > -1">

Altere a sua função:
$scope.contratos = [];
$scope.PegaContrato = function (numero_contrato) {
    //console.log(numero_contrato);
    var index = $scope.contratos.indexOf(numero_contrato);

    // se já selecionou o contrato, então remove (nesse caso o checkbox foi desmarcado)
    if (index > -1)
        $scope.contratos.splice(index, 1);
    // se selecionou um novo contrato, adiciona ao array
    else
      $scope.contratos.push(numero_contrato);

    // print em tela do array com os contratos selecionados
    console.log(contratos);
}

Comment: E tem como passar mais de um contrato ?


Select conversations of user but not the user

Question: I have a database like
<code>User
  UserName
  UserId

Chat
  ChatId
  ChatSubject

ChatUser
  Chat_ChatId
  User_UserId

ChatMessage
  Chat_ChatId
  User_UserId
  Message
</code>
I have the current user id in a variable like : $userId
What i want is find the Chat_ChatSubject an the UserName of the other person in the chat, so i can create a list of conversations where i show the username of the other person and the subject
What i have :
<code>$conversations= Chat::
        Join('ChatUser', 'Chat.id', '=', 'ChatUser.User_UserId')
        ->Join('User', 'User.UserId', '=', 'ChatUser.User_UserId')
        ->Select('Users.UserName', 'Chat.Subject')
        ->OrderBy('ChatUsers.Chat_ChatId','asc')
        ->GroupBy('Chat.ChatId')
        ->get();
</code>
The result of this is a list of Chats but it contains not always the name of the other person. What i want is that User.UserName is the username of the other person so not my own.
(There are always 2 ChatUsers in one Chat
Answer: Assuming you have the relations set up in your models...
<code>$conversations = User::find($userId)
                    ->chats()
                    ->with(array('users' => function($query) use ($userId){
                        $query->where('id', '!=', $id);
                    }))->get();

foreach($conversations as $conversation){
    $conversation->ChatSubject; // get subject
    $conversation->users; // get users collection (current user excluded)
}
</code>


Solving a complex line integral via Stokes' Theorem

Question: I haven't a clue how to set up my double integral to solve this question

The answer, according to the textbook, is:

Since $curl F = 1/(1+y^2)i + 2ze^{x^2}j + y^2k$

Ummm... What? Am I missing something? Where did that come from?!
Comment: Good question +1
Answer: Compare
$$\oint z^2e^{x^2}dx+xy^2dy+\arctan y \, dz$$
with
$$\oint F_x \,dx+F_y \,dy+F_z \,dz$$
to see that the vector field in this case is given by $\vec F = \left( z^2e^{x^2},xy^2,\arctan y\right)$.
Now compute the curl, e.g. via
$$\mbox{curl} \vec F =\begin{vmatrix} \mathbf{i} & \mathbf{j} & \mathbf{k} \\
\tfrac{\partial}{\partial x} & \tfrac{\partial}{\partial y} & \tfrac{\partial}{\partial z} \\
F_x & F_y & F_z
\end{vmatrix}=
\begin{vmatrix} \mathbf{i} & \mathbf{j} & \mathbf{k} \\
\tfrac{\partial}{\partial x} & \tfrac{\partial}{\partial y} & \tfrac{\partial}{\partial z} \\
z^2e^{x^2} & xy^2 &\arctan y
\end{vmatrix} = \cdots$$
Comment: Wow, super obvious now that I look at it. I just hadn't considered that F already "existed" in the given equation
Comment: Sometimes you just don't see it! :)


acceptable quality limit for an audit?

Question: I have been tasked to see if there is a better audit tool than the Acceptable Quality Limit. I believe that this tool is mostly used for defects and I'm not sure if it is an accurate auditing tool for judging people and their cases.
Would it be something as easy as confidence interval? I feel like there should be more than this
The main concern I am having is that
1) not everyone has a case every month; some employees have multiple cases in a month, others do not
2) We only have an average of 20 cases total per month
3) Each case has a lot to audit, so auditing all of them is too time consuming
Answer: I am not sure what your are testing.
If its a product, why don't you use statistical process control?
https://en.m.wikipedia.org/wiki/Statistical_process_control
If you have high dimensional multivariate data, you could use PCA- T2 and PCA-SPE analysis. In this technique, you can set your confidence level.

acceptable quality limit for an audit?


Criação de Pastas Recursivas

Question: O Problema:
Gostaria de saber se existe uma maneira mais prática do que utilizar as estruturas de controle IF/ELSE para criação de pastas recursivamente, baseado nos inputs que o usuário digitou.
Contexto:
Por exemplo, no meu script, eu recebo os dados, valido e sanitizo os posteriormente, e então eu crio pastas com os dados do campos informados, até ai tudo bem, mas o problema é que alguns campos não são obrigatórios de serem digitados, portanto se eu tiver, por exemplo 4 campos:
Nome, Empresa, Cidade, Estado
Eu gostaria de saber se existe outra maneira além do IF/ELSE:
$dir = "uploads/{$nome}/{$empresa}/{$cidade}/{$estado}/";
    if(!is_dir($dir)):
            mkdir($dir, 0777, true);
    endif;

De criar as pastas com os dados que foram digitados, ignorando os campos vazios para evitar erros
Comment: E o que deve acontecer se houver algum campo vazio?
Comment: Ele deve ignorar o campo da variável $dir, caso o campo nome esteja vazio: `$dir="uploads/{$empresa}/{$cidade}/{$estado}/";` e assim sucessivamente até verificar todos campos
Answer: Uma maneira prática (poucas linhas) é criar um vetor com os valores das variáveis e filtrá-los com a função array_filter. Depois, pode unificar os valores restantes com a função implode. Veja o exemplo:
$nome    = "";
$empresa = "";
$cidade  = "foo";
$estado  = "bar";

$dir = 'uploads/' . implode('/', array_filter([$nome, $empresa, $cidade, $estado]));

var_dump($dir); // string(15) "uploads/foo/bar"

Como nativamente uma string vazia é analisada como falso pelo PHP, a função array_filter elimina todos os valores vazios, depois os restantes são concatenados através da função implode.
Pode ver o código funcionando aqui ou aqui.

Criação de Pastas Recursivas


Why would we need to lock a process's address space in RAM?

Question: http://linux.die.net/man/2/mlockall

mlockall() locks all of the calling process's virtual address space into RAM, preventing that memory from being paged to the swap area.

why is this important in real time systems?
Comment: Also please have a look at Herb Sutter's article at http://www.nwcpp.org/Downloads/2007/Machine_Architecture_-_NWCPP.pdf ....it tells you more about Memory latency issues.....u could consider these while designing a real time system....
Answer: It ensures the memory is always in RAM and never moved to the swap disk. This makes accessing those memory locations much faster as disks are extremely slow compared to RAM.
In a realtime system (linux is NOT a RTS btw!) you need extremely low latencies so a memory access resulting in a disk access is usually not acceptable inside time-critical code.
Comment: @AnishaKaul: It means that the process will always run with better performance since all the pages associated with that process remain in the RAM.However note that when using `mlockall()` if there is not enough physical memory, memory allocation calls in other processes would fail.
Comment: Okay, yes, thanks for bolding that statement. So, this means that non-important tasks won't get any place in the ram till this real time thing is active?
Answer: It can be used in real-time applications or high-security data processing for instance.
This is a quote from mlockall() documentation:

Real-time applications require deterministic timing, and, like
  scheduling,
         paging is one major cause of unexpected program execution delays.  Real-time applications will usually also switch to a
  real-time scheduler with sched_setscheduler(2).   Crypto‐
         graphic  security  software often handles critical bytes like passwords or secret keys as data structures.  As a result of paging,
  these secrets could be transferred onto a per‐
         sistent swap store medium, where they might be accessible to the enemy long after the security software has erased the secrets in
  RAM and terminated.  (But  be  aware  that  the
         suspend mode on laptops and some desktop computers will save a copy of the system's RAM to disk, regardless of memory locks.)
Real-time  processes  that  are  using mlockall() to prevent delays on page faults should reserve enough locked stack pages before
  entering the time-critical section, so that no
         page fault can be caused by function calls.  This can be achieved by calling a function that allocates a sufficiently large
  automatic variable (an array) and writes to the  mem‐
         ory  occupied  by  this array in order to touch these stack pages.  This way, enough pages will be mapped for the stack and can be
  locked into RAM.  The dummy writes ensure that
         not even copy-on-write page faults can occur in the critical section.
Comment: thanks much. My fault, I should have read the doc properly before asking.
Answer: With real time processing the key ingredient is the real time component - i.e. you cannot afford to have to wait from memory to swapped in/out.


Can old batter heads be used as resonant heads?

Question: Is it possible to use old worn-out drum batter heads as resonant heads? I have a couple of heads that have dents in them, and are sounding pretty crap, and I'm wondering if it's worth using them as resonant heads, when those wear out. Will the dents reduce the resonance quality? If so, in what way?
Answer: I would advise against doing so.
I expect that you intend to exchange both heads of your drum, to save some money. I've done that, once or twice, because I had to (very bad dent on the batter head, no spare available, and I had to play).
First, it supposes that you use the same model head on both sides of you toms, which is often seen but in no way a requirement. If you have different weights on both sides, you will get a very different sound.
Second, if you think that the batter head has a crappy sound, chances are the head is worn, and you will find it difficult to tune your tom to get a nice sounding sound, with that head on the resonnant side: the batter head suffers from higher physical stress, and a worn batter head is often more stretched that its resonnant counterpart.
Finally, your tom might not be perfectly built. It is not recommended to rotate a head once it's been seated on the tom (the seating is when you initially overstretch the head a bit so that it fits the geometry of the tom), because the geometry of the contact surface of the head and the tom will be affected. The same goes for switching sides.
My advice is to keep your resonnant head where it stands, and get a new batter head: the resonnant head is in place, well seated. It needs changing from time to time, but at a much lower frequency than the batter head. If you switch heads, you'll get to buy 2 new heads fairly soon.
You may want to read the Drum Tuning Bible which gives some very useful advice on drum heads and shells.
Answer: I would strongly advise against it. The resonant head is supposed to resonate. If you have beaten your batter head to a point where it should be changed as a batter head, it really means it should be changed. It's beyond the point of optimal resonance and thus using it as a resonant head will not produce a good sound.
Batter and resonant heads don't necessarily need to be the same. In fact, it's fairly common to use a thicker (2-ply) batter head with a thinner (1-ply) resonant head. You can also use the same heads for both, but in that case thinner 1-ply heads are usually preferred.
What really matters is how your heads work together. They don't need to be the same pitch, even though that is the common way. More often than not same tuning, or tuning resonant head slightly higher is what you want, though.
Whatever heads you have, make sure they are in good condition. Heads wear out over time and this is why it's recommended that you always change them before studio. Old, beaten, worn out heads simply do not resonate enough to produce a good sound.


O que é um chrome?

Question: Note que chrome está em minúsculo, não estou falando do navegador. O que significa o termo chrome na programação? Quando é apropriado usá-lo?
Answer: Chrome é o nome que se dá para os elementos que formam a janela da aplicação. Estamos falando só da "borda" dela, não o miolo da janela. É o que circunda o conteúdo. O termo completo seria user interface chrome para ficar menos ambíguo do que se se trata.
Pode incluir o menu, barra de rolagem, botões de navegação e comandos, título, caixa de comunicação com o conteúdo. Ele é o oposto do conteúdo, o que não são os dados do usuário. É uma maneira de dar um nome genérico para os vários elementos de controle da aplicação que roda que não é o foco principal.
Não precisa ser em uma janela do sistema operacional, pode ser em uma página de internet. É possível ter um chrome do navegador (não confundir com o Chrome) e pode ter o chrome da página que está acessando, por exemplo o rodapé faz parte do chrome da página.
Por exemplo, a barra de ferramentas, geralmente embaixo da tela, com o botão iniciar e outros elementos ali é o chrome do Windows.
Coloquei no GitHub para referência futura.

O que é um chrome?