Verificação vencedor jogo da velha Jquery

Question: Criei uma função para verificar linhas na horizonal, vertical e diagonal, pra ver qual é o vencedor, mas quando chamo a função ela mostra vencedor logo no primeiro clique.
Alguem pode me ajudar no que alterar no codigo pra que a logica funcione?
Segue o codigo que ja tenho aqui:

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

            <button id="btn1" name="btn1" class="btn btn-default botao"></button>
            <button id="btn2" name="btn2" class="btn btn-default botao"></button>
            <button id="btn3" name="btn3" class="btn btn-default botao"></button>
            <button id="btn4" name="btn4" class="btn btn-default botao"></button>
            <button id="btn5" name="btn5" class="btn btn-default botao"></button>
            <button id="btn6" name="btn6" class="btn btn-default botao"></button>
            <button id="btn7" name="btn7" class="btn btn-default botao"></button>
            <button id="btn8" name="btn8" class="btn btn-default botao"></button>
            <button id="btn9" name="btn9" class="btn btn-default botao"></button>

            É a vez do jogador 1

    >

Answer:

var vez = 1;
var vencedor = "";

$(document).ready(function() {

  function casasIguais(a, b, c) {
    var casaA = $("#btn" + a);
    var casaB = $("#btn" + b);
    var casaC = $("#btn" + c);
    var bgA = $("#btn" + a).text();
    var bgB = $("#btn" + b).text();
    var bgC = $("#btn" + c).text();
    if ((bgA == bgB) && (bgB == bgC) && (bgA != "none" && bgA != "")) {
      if (bgA.indexOf("X") >= 0)
        vencedor = "1";
      else
        vencedor = "2";
      return true;
    } else {
      return false;
    }
  }

  function verificarFimDeJogo() {
    if (casasIguais(1, 2, 3) || casasIguais(4, 5, 6) || casasIguais(7, 8, 9) ||
      casasIguais(1, 4, 7) || casasIguais(2, 5, 8) || casasIguais(3, 6, 9) ||
      casasIguais(1, 5, 9) || casasIguais(3, 5, 7)
    ) {
      $("#resultado").html("
O jogador " + vencedor + " venceu!
");
      $(".casa").off("click");
    }
  }

  $(".btn").click(function() {
    var bg = $(this).text();
    if (bg == "none" || bg == "") {
      var fig = vez.toString();
      if (vez == 1) {
        $(this).text("X");
        jogador = 2;

      } else {
        $(this).text("O");
        jogador = 1;

      }
      $("#jogador").text("É a vez do jogador " + jogador);
      vez = (vez == 1 ? 2 : 1);
      verificarFimDeJogo();
    }

  });

});
.botao {
  width: 32%;
  height: 100px;
  font-size: 70px;
  font-weight: bold;
  border-radius: 0px;
}
#jogador {
  font-size: 38px;
}

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

      <button id="btn1" name="btn1" class="btn btn-default botao"></button>
      <button id="btn2" name="btn2" class="btn btn-default botao"></button>
      <button id="btn3" name="btn3" class="btn btn-default botao"></button>
      <button id="btn4" name="btn4" class="btn btn-default botao"></button>
      <button id="btn5" name="btn5" class="btn btn-default botao"></button>
      <button id="btn6" name="btn6" class="btn btn-default botao"></button>
      <button id="btn7" name="btn7" class="btn btn-default botao"></button>
      <button id="btn8" name="btn8" class="btn btn-default botao"></button>
      <button id="btn9" name="btn9" class="btn btn-default botao"></button>

      É a vez do jogador 1


Tabela com barra de rolagem na horizontal

Question: Montei uma tabela com CSS, porém estou tendo um problema quando os relatórios são abertos em celular ou tablet. A tabela fica achatada, ou dados ficam confusos.
Tem como colocar uma barra de rolagem na horizontal, e evitar que os dados fiquem achatados?
Segue a tabela como esta:

.tab_dados {
    width: 100%;
    border-collapse: collapse;
    text-align: center;
}
.tab_dados a {
    color: #484848;
    text-decoration: none;
}
.tab_dados th {
    background: #0091FF;
    color:#FFFFFF;
    font-style: italic;
}
.tab_dados tr {
    height: 50px;
    border-bottom: 1px solid #D5D5D5;
}
.tab_dados tr:nth-child(odd) {
    background: #F7F7F7;
}
.tab_dados tr:nth-child(even) {
    background: #FFFFFF;
}
.tab_dados tr:hover {
    background: #F1F1F1;
}
tfoot tr td{
    border:0;
    height: 40px;
}
.tfoot{
    width: 100%;
}

                CÓDIGO
                NOME
                CIDADE
                CIDADE
                CIDADE
                CIDADE
                CIDADE
                ESTADO

                25
                HUGO
                BOA ESPERANÇA
                BOA ESPERANÇA
                BOA ESPERANÇA
                BOA ESPERANÇA
                BOA ESPERANÇA
                MG

                25
                HUGO
                BOA ESPERANÇA
                BOA ESPERANÇA
                BOA ESPERANÇA
                BOA ESPERANÇA
                BOA ESPERANÇA
                MG

                25
                HUGO
                BOA ESPERANÇA
                BOA ESPERANÇA
                BOA ESPERANÇA
                BOA ESPERANÇA
                BOA ESPERANÇA
                MG

                25
                HUGO
                BOA ESPERANÇA
                BOA ESPERANÇA
                BOA ESPERANÇA
                BOA ESPERANÇA
                BOA ESPERANÇA
                MG

Comment: Aumentar a largura `tab_dados` para 200% nas resoluções que tu quer não te ajudaria?
Answer: Você precisa botar uma div fora da tabela, contendo a tabela. Exemplo:

(conteúdo...)

E por as seguintes classes:
div.table {
    overflow-x: scroll;
}
th, td {
    min-width: 50px; /* width/largura das células à escolha */
}

Você precisaria de um mínimo de conhecimento em Media Queries para aplicar somente aos dispositivos desejados.
Answer: Você deveria colocar uma div como o colega @Leon Freire falou, só que você coloca em css o tamanho da div assim como também o tamanho da tabela, logo após isso, você utiliza o comando overflow em css.

#caixa_tabela{
        width: 150%; /* aqui pode ser auto ou 100%*/
        overflow-x: auto;
    }
    .tab_dados {
        width: 100%;
        border-collapse: collapse;
        text-align: center;
    }
    .tab_dados a {
        color: #484848;
        text-decoration: none;
    }
    .tab_dados th {
        background: #0091FF;
        color:#FFFFFF;
        font-style: italic;
    }
    .tab_dados tr {
        height: 50px;
        border-bottom: 1px solid #D5D5D5;
    }
    .tab_dados tr:nth-child(odd) {
        background: #F7F7F7;
    }
    .tab_dados tr:nth-child(even) {
        background: #FFFFFF;
    }
    .tab_dados tr:hover {
        background: #F1F1F1;
    }
    tfoot tr td{
        border:0;
        height: 40px;
    }
    .tfoot{
        width: 100%;
    }

            CÓDIGO
            NOME
            CIDADE
            CIDADE
            CIDADE
            CIDADE
            CIDADE
            ESTADO

            25
            HUGO
            BOA ESPERANÇA
            BOA ESPERANÇA
            BOA ESPERANÇA
            BOA ESPERANÇA
            BOA ESPERANÇA
            MG

            25
            HUGO
            BOA ESPERANÇA
            BOA ESPERANÇA
            BOA ESPERANÇA
            BOA ESPERANÇA
            BOA ESPERANÇA
            MG

            25
            HUGO
            BOA ESPERANÇA
            BOA ESPERANÇA
            BOA ESPERANÇA
            BOA ESPERANÇA
            BOA ESPERANÇA
            MG

            25
            HUGO
            BOA ESPERANÇA
            BOA ESPERANÇA
            BOA ESPERANÇA
            BOA ESPERANÇA
            BOA ESPERANÇA
            MG

Answer: Olá,
A forma mais simples que encontrei foi colocar a tabela dentro de uma div.
No exemplo, defini a altura máxima em 600px e a largura em 100%. Ajuste como for mais adequado ao seu caso!
Boa sorte!

Sua tabela aqui

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Answer: Na metodologia Material Design o componente Table trata muito bem nessa questão de responsividade para a melhor exibição tanto na web quando mobile.
Para a resoluções menores eles invertem as colunas para linhas e linhas para colunas deixando a primeira coluna fixa.
Utilizando @media query no css para especificar uma resolução para mobile você pode tratar com este mesmo casso.
Vejo um exemplo de Responsive Table com a framework Materialize.
Comment: Qual a utilização do `@keyframes` para essa resolução? Você quis dizer `@media`?
Comment: Isso mesmo, desculpe o engano, são os @media query.

No site go Material Design especifica bem as resoluções usadas em mobile.

https://material.io/guidelines/layout/responsive-ui.html#responsive-ui-breakpoints


Proper way of saving and loading pictures

Question: I am making a small app where the user can create a game profile, input some data and a picture that can be taken with the camera.
I save most of that profile data with the help of NSUserDefaults, but a friend discouraged me from saving the profile image in NSUserDefault.
What's the proper way to save and retrieve images locally in my app?
Answer: You should save it in Documents or Cache folder. Here is how to do it.
Saving into Documents folder:
NSString* path = [NSHomeDirectory() stringByAppendingString:@"/Documents/myImage.png"];

BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path
          contents:nil attributes:nil];

if (!ok)
{
    NSLog(@"Error creating file %@", path);
}
else
{
    NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
   [myFileHandle writeData:UIImagePNGRepresentation(yourImage)];
   [myFileHandle closeFile];
}

Loading from Documents folder:
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
UIImage* loadedImage = [UIImage imageWithData:[myFileHandle readDataToEndOfFile]];

You can also use UIImageJPEGRepresentation to save your UIImage as a JPEG file. What's more if you want to save it in Cache directory, use:
[NSHomeDirectory() stringByAppendingString:@"/Library/Caches/"]

Comment: @José and Rafal: `NSSearchPathForDirectoriesInDomains` is better because it will not break if Apple decides to change their directory structure. In general, the less you have to hard-code, the better. If a specific API function exists for what you want to do, use it. A clean way to get this path would be: `NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *path = [NSString pathWithComponents:[NSArray arrayWithObjects:dir, @"myImage.png", nil]];` (too bad it's so verbose though!)
Comment: Do not use `[NSHomeDirectory() stringByAppendingString:...]`. Use `[[NSSearchPathForDirectoriesInDomains(..., NSUserDomainMask, YES) objectAtIndex:0]` with `NSDocumentDirectory` or `NSCachesDirectory`.
Comment: oops, just found a nicer way to express the second statement of my example: `NSString *path = [dir stringByAppendingPathComponent:@"myImage.png"];`
Comment: Why one should not use `[NSHomeDirectory() stringByAppendingString:...]`? Can you explain it?
Comment: @reecon Indeed you wouldn't find everything written in documentations. And the statement I making are based on some profiling results (using Xcode Instruments). Also I not saying it will take a lot of memory when called once or twice or a bit more, but, let say, try calling it for every time your tableview cell loads. It will eventually show some allocation spikes. In my case it was reaching up to 300 Mb, which I have managed to reduce to few Kb.
Comment: I ended up using [NSHomeDirectory() stringByAppendingString:...] , using Anomie's version gave me errors. I still don't know why I shouldn't according to Anomie.
Comment: Why use `UIImagePNGRepresentation` ? Isn't easier (and faster ?) to directly use `imageData = [[NSData] initWithContentsOfURL: url]` and then `[imageData writeToFile:filePath]` ?
Comment: Too many NSHomeDirectory() calls will cause lots of memory Allocations. You may call NSHomeDirectory() at the time of app launch and keep the path in shared variable. And wherever you need the path, use your shared variable value. It will reduce the memory allocations.
Comment: @Ansari, can you please provide me with a link to documentation that states this. I checked everything I could find about `NSHomeDirectory` and it does not say anything about issue you are writing about. It would be strange if calling this function would cause memory allocations spike.
Answer: One way to do this is use the application's document directory. This is specific to a application and will not be visible to other applications.
How to create this:
Just add a static function to App Delegate and use the function  where ever the path is required.
- (NSString )applicationDocumentDirectory {
    /
     Returns the path to the application's documents directory.
     */
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

Hope it Helped..
Answer: I think this("iphone-user-defaults-and-uiimages") post addresses your issue. Don't save blobs to a property list such as NSUserDefaults. In your case I would write to disk directly instead.


How to predict survival time in Cox's Regression Model in R?

Question: I have a modeled a problem using Cox's regression and now want to predict the estimated survival time for an individual. The model has a list of covariates on which the survival time depends. This tells us how to calculate P(T>t) which is basically the survival Function (1-CDF) for a given individual.
I want to predict something which is slightly different. Given values for the covariates that have been used, I want to predict the the estimated number of days that the person would live. This, according to me, is similar to sampling from the pdf. How can I do this using the survival package in R? Below is a summary of the fit using Cox's regression model.
Call:
coxph(formula = Surv(Time, death) ~ variable1 + variable2 + variable3 +
variable4 + variable5 + variable6 + variable7 + variable8 + variable9,
data = DataTest, method = "breslow")

n= 23756, number of events= 23756

          coef exp(coef) se(coef)      z Pr(>|z|)
variable1  0.02494   1.02526  0.02375  1.050  0.29354
variable2 -0.20715   0.81290  0.02395 -8.650  < 2e-16 ***
variable3  0.12940   1.13814  0.02263  5.717 1.08e-08 ***
variable4  0.02469   1.02500  0.02289  1.079  0.28077
variable5  0.13165   1.14070  0.02235  5.891 3.84e-09 ***
variable6  0.22286   1.24965  0.01534 14.526  < 2e-16 ***
variable7 -0.10513   0.90021  0.02035 -5.167 2.38e-07 ***
variable8  -0.12215   0.88501  0.02243 -5.447 5.13e-08 ***
variable9  -0.04930   0.95189  0.01827 -2.698  0.00697 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

      exp(coef) exp(-coef) lower .95 upper .95
variable1    1.0253     0.9754    0.9786    1.0741
variable2    0.8129     1.2302    0.7756    0.8520
variable3    1.1381     0.8786    1.0888    1.1898
variable4    1.0250     0.9756    0.9800    1.0720
variable5    1.1407     0.8767    1.0918    1.1918
variable6    1.2496     0.8002    1.2126    1.2878
variable7    0.9002     1.1109    0.8650    0.9368
variable8    0.8850     1.1299    0.8470    0.9248
variable9    0.9519     1.0505    0.9184    0.9866

Concordance= 0.543  (se = 0.002 )
Rsquare= 0.022   (max possible= 1 )
Likelihood ratio test= 516.5  on 9 df,   p=0
Wald test            = 503.1  on 9 df,   p=0
Score (logrank) test = 505.1  on 9 df,   p=0

Comment: This is really a question about statistics, not about programming. Try looking here: http://stats.stackexchange.com/questions/79362/how-to-get-predictions-in-terms-of-survival-time-from-a-cox-ph-model
Comment: "Estimated number of days that the person would live" is just "life expectancy". It's not the sample from the survival function but rather the integral over time of the survival function. A lower bound up to the last death can easily be calculated from the results of `predict`. Since you have complete observations (no censoring), this is not a problem for you.
Answer: Due to the censored nature of survival data, it is usually more useful to compute a median survival time instead of a mean expected survival time. You can very easily recover the median survival time for each person in your data by running the following:
survfit(cox.ph.model,newdata= DataTest)
Comment: I agree with you. One of the most important use cases of the Cox model should be to build a survival curve for each person according to their respective covariates. It looks like at one time,the `survfit` function allowed for the parameter `print.mean=T` in order to retrieve the mean residual life by person. I am guessing that you will now need to estimate it by estimating the death function from the survival curve and integrating. There might be a function that does this in the `emplik` library. It looks to be a bit of a pain to get. However, I still do think the median is a better here.
Comment: Thanks! That does point out the median. Two points : 1. My data has no censoring. In that case, is there a better way? 2. The link that MrFlick suggested says that survival times for particular individuals is not appropriate use of this tool. I do not see why. Shouldn't that be one of the most important uses of such a tool?
Comment: Okay. From what I read and found out, I think that estimation of the survival time is probably not a good idea with Cox's proportional Hazard model, since the baseline hazard is implicit. I think that if one is making the proportional hazard assumption. then it is probably better to consider a distribution (Weibull, exponential etc.) and then estimate the survival time.
Comment: The Cox PH is more robust as it doesn't make any assumptions about the distribution of the baseline hazard (it is a non-parametric estimate). I have actually found that the Cox PH model is much more robust than the AFT models. You can always use the `strata` call if you want mulitple baseline hazards for different groups in your data.
Answer: I do not think you can estimate the survival time of a single observation using Cox Proportional Hazards model. The model outputs hazard ratio as the output and is well suited understanding the effects of covariates on survival as it does not make any assumptions of the baseline hazard function. If you want to estimate the survival time for a single observation, you are better off using distributions such as Weibull or Exponential which will allow you to do that and which are a part of the Survival package.
Thanks,
Comment: The first sentence is just wrong ( since what was requested was not survival time of a single observation but rather for a single set of covariates.) ...and the rest of the answer is not an answer.


Using Zorn's Lemma, for a function $f: X \to Y$, show that the poset of partial sections of $f$, $((A, u), ≤)$, is non-empty.

Question: I was reading the book Sets, Models and Proofs and I'm now stuck at the part where they prove that Zorn's Lemma implies AC. In particular, this part:
"Proof.
We assume that Zorn's Lemma is true.
Suppose given a surjective function $f : X → Y$. A partial section of $f$ is a pair
$(A, u)$ where $A$ is a subset of $Y$ and $u : A → X$ a function such that $f (u(y)) = y$ for
each $y ∈ A$. Given two such partial sections $(A, u)$ and $(B, v)$, put $(A, u) ≤ (B, v)$
iff $A ⊆ B $ and u is the restriction of v to A. Let P be the set of partial sections (A, u)
of f ; then with the relation ≤, P is a poset, as is easy to see.
P is nonempty; this is left to you. . ."
What I'm confused about is this: Doesn't the existence of (A, u) require the Axiom of Choice? Because you have to choose an u for which f(u(y)) = y. For each y ∈ A, you have to pick an u(y) = x. I honestly don't see how I can prove that P is nonempty without using the Axiom of Choice or by using Zorn's Lemma, which is defined in the book as:
"Definition 1.3.4
Zorn's Lemma is the following assertion: if (P , ≤) is a poset with
the property that every chain in P has an upper bound in P, then P has a maximal
element.
Note that if P satisfies the hypothesis of Zorn's Lemma, then P is nonempty. This
is so because the empty subset of P is always a chain. However, checking that every
chain has an upper bound in P usually involves checking this for the empty chain
separately; that is, checking that P is nonempty."
Any help would be much appreciated.
Edit:
For anyone that comes here after me, Do We Need the Axiom of Choice for Finite Sets? was also really helpful.
Comment: Welcome to MSE! Please use MathJax! As written your post is unreadable. Putting $ signs in between math formulas may help.
Comment: Let $a\in X$ and $b=f(a)$. Then $(A,u)\in P$ if $A=\{b\}$ and $u(b)=a$. This shows that $P\neq\varnothing$ and we did not use AC.
Answer: No, in the proof, the author is just saying what means that a pair $(A, u)$ is a partial section of $f$, it doesn't say anything about if such a pair exists for any given $A\subseteq Y$, the important thing is that the set of ALL partial sections of $f$ is not empty, but this is easy to check, just take any $y\in Y$, since $f$ is surjective there exists $x\in X$ such that $f(x)= y$ and if you define $u : \{y\} \rightarrow X$ as $u(y):=x$ then the pair $(\{y\}, u)$ is a partial section of $f$.
Comment: @bowieschoonderbeek It is no problem to make  a **single choice** or **finitely many choices**. The axiom of choice is only needed if we want to make infinitely many choices. Here you choose a single $y \in Y$ and then a single $x \in f^{-1}(y)$.
Comment: But doesn't this mean you still just **choose** an _x_ so that $f(x) = y$ for any $( {y} , u)$ ? Because for every $y∈Y$ there might be multiple _x_ for which $f(x) = y$.


Find $A$ if $2\sin(4A)=1$ ($A$ lies between $0^{\circ}$ and $180^{\circ}$)

Question: I approached this problem like this:
$$\begin{aligned}2\sin(4A)=&\ 1\\
\sin(4A)=&\ 1/2 \\
4A=&\ 30^{\circ}\\
A=&\ 7.5^{\circ}
\end{aligned}$$
But answer says there are two possible values i.e., $7.5^{\circ}$ and $30^{\circ}.$
Please help me out, how is it $30$ degrees?
Comment: $4A$ could also be $150^\circ$. But $A$ cannot be $30^\circ$.
Comment: Just first consider values of $x$ such that $0\leq x\leq \pi$ and $\sin(x)=\frac{1}{2}$. Try graphing the sine wave on this interval.
Comment: @Dave sorry but I am still in 10th grade. Can you share an alternate method which only involves degrees and not radians?
Answer: $2\sin(4A^\circ)=1$ implies $\sin(4A^\circ)=1/2$, which implies
$$
4A\in\{30+360m,150+360n\}
$$
which means
$$
A\in\{7.5+90m,75+90n\}
$$
Because $A\in[0,180]$, we have $m,n\in\{0,1\}$, which indicates that
$$
A\in\{7.5,97.5,75,165\}
$$

But answer says there are two possible values i.e., 7.5 and 30.

I doubt the correctness of this answer
Comment: Can you please clarify how did you define that 4A∈{30+360m,150+360n}?
Comment: Generally, if we say $x\in\{a,b,c\}$ then $x$ should be one of $a$, $b$, or $c$.
Comment: Sorry but I think you didn't get me. I wanted to ask how and why did you express 4A as a linear combination(30+360m and 150+360n).
Comment: @Dhairya Sine is a periodic function with a period size of 360, so $\sin(30^\circ+360^\circ m)=\sin(30^\circ)$ where $m$ is some integer