Why does my program prompt for input over and over?

Question:
You will write a Java program to play the game of Pico, Fermi, Bagel. Here are the rules of the game:
The computer will generate a "secret" three digit number at random. The first number will not be 0, and all the digits will be different. The user tries to guess the number. If the user guesses correctly, then the game is over.
If not, the computer gives a hint and the player tries again. The hints:

For each digit that matches the secret number in the proper place, the computer prints "Fermi"
For each digit that matches, but not in the proper place, the computer prints "Pico"
If none of the digits match, the computer prints "Bagels"

The program will have a main class and a Bagels class. The bagels class will call 3 other methods to
1) generate the secret number
2) determine whether the current guess is a winner
3) evaluate the current guess and print hints

My issue: When I run my program, it asks me to enter a 3 digit number, but then it just repeatedly asks me to enter 3 digits over and over. I'm pretty sure the problem has something to do with the methods in my Bagels class. My compiler is saying that the generateSecretNumber and printHint methods are unused. The only thing is that I'm not sure how to go about making it so they are used.
Main class
package assignment.iii;

import javax.swing.JOptionPane;
import java.util.Scanner;

public class AssignmentIII {

    public static void main(String[] args) {
        int playagain = JOptionPane.showConfirmDialog(null, "Would you like to play?", "Message", JOptionPane.YES_NO_OPTION);

        while (playagain == JOptionPane.YES_OPTION) {
            Bagels myBagels = new Bagels();
            myBagels.playGame();
            myBagels.randNumber = 0;
            playagain = JOptionPane.showConfirmDialog(null, "Would you like to play again?", "Message", JOptionPane.YES_NO_OPTION);
        }
    }
}

Bagels class
package assignment.iii;

import java.util.Random;
import javax.swing.JOptionPane;

public class Bagels {
    public int randNumber;
    private int Guess;
    private int Rand1, Rand2, Rand3;
    private int Guess1, Guess2, Guess3;
    private int guessCount;

    public void playGame() {
        if (Guess1 == 0 || Guess1 == Guess2 || Guess2 == Guess3 || Guess1 == Guess3);
        JOptionPane.showMessageDialog(null, "Please enter another number" +
                "the first digit can't be 0 and no digits can repeat");

        do {
            Guess = Integer.parseInt(JOptionPane.showInputDialog("Enter a three digit number"));
        } while (Guess != randNumber);

        if (Guess == randNumber)
            System.out.println("It took you " + guessCount + " guesses.");
    }

    private int generateSecretNumber() {
         Random randN = new Random();
         return randN.nextInt(999)+1;
    }

    private void printHint(String guess) {
        if (randNumber == Guess)
            System.out.println("Correct");
        else {
            Guess1 = (Guess) / 100;
            Guess2 = (Guess % 100) / 10;
            Guess3 = (Guess % 100) % 10;
        }

        if (Guess1 == Rand1) {
            System.out.println("Fermi");
        }
        if (Guess2 == Rand2) {
            System.out.println("Fermi");
        }
        if (Guess3 == Rand3) {
            System.out.println("Fermi");
        }
        if (Guess2 == Rand1) {
            System.out.println("Pico");
        }
        if (Guess3 == Rand1) {
            System.out.println("Pico");
        }
        if (Guess1 == Rand2) {
            System.out.println("Pico");
        }
        if (Guess3 == Rand2) {
            System.out.println("Pico");
        }
        if (Guess1 == Rand3) {
            System.out.println("Pico");
        }
        if (Guess2 == Rand3) {
            System.out.println("Pico");
        } else if(Guess1 != Rand1 && Guess1 != Rand2 && Guess1 != Rand3 &&
            Guess2 != Rand1 && Guess2 != Rand2 && Guess2 != Rand3 &&
            Guess3 != Rand1 && Guess3 != Rand2 && Guess3 != Rand3) {
            System.out.println("Bagels");
        }
        guessCount++;
    }
}

Comment: Your should not start an variable or field name with an upper-case character.  It is a violation of a core Java style rule.
Answer:
generateSecretNumber and printHint methods say they are unused.

Yep, that's the core issue.
You initialize the number to be guessed to zero
myBagels.randNumber = 0;

and then never set it to another value, so your loop
while (Guess != randNumber);

will go on until someone guesses 0.

Only thing is I'm not sure how to go about making it so they are used.

There are many options.  One option is, at the beginning of playGame(), to invoke it
randNumber = generateSecretNumber();

Comment: Thanks. How would i go about fixing the loop so it gets set to another value? Also how do I add the printHint part in so it gets used?
Comment: With my suggestion, a new random number will be set every time `playGame()` is called.  Surely you don't want to change the number after every guess?  You can call `printHint()` right after `Guess = Integer.parseInt(JOptionPane.showInputDialog("Enter a three digit number"));`
Comment: No i don't want it to change after every guess. But then how do i make it so it won't go on until someone guesses 0? Also how exactly do i call another method? I tried return.printHint(); but its not working (illegal expression)


Why does this calculation result in this matrix?

Question: The following basis is given to me:
$|L\rangle =
\begin{bmatrix}
    1       \\
    0
\end{bmatrix}$
$|R\rangle =
\begin{bmatrix}
    0       \\
    1
\end{bmatrix}$
and I am told that
$(|LL\rangle \langle LL| + |RR\rangle \langle RR|)$=
\begin{bmatrix}
    1       & 0 & 0 & 0 \\
    0       & 0 & 0 & 0 \\
    0       & 0 & 0 & 0 \\
    0       & 0 & 0 & 1 \\
\end{bmatrix}
I guess that if $|L\rangle =
\begin{bmatrix}
    1       \\
    0
\end{bmatrix}$ then
$\langle L| =
\begin{bmatrix}
    1 & 0
\end{bmatrix}$, same for $R$
Could someone explain to me how they got that matrix ?
Comment: The $|LL\rangle$ notation is likely the tensor product: $|LL\rangle=|L\rangle\otimes|L\rangle$. That's the piece you're missing, I think.
Answer: The notation $|LL\rangle$ denotes the tensor product $|L\rangle\otimes |L\rangle$, which we can compute the matrix form of by using the Kronecker product.
Using this allows you to compute the expressions for $|LL\rangle$ and $|RR\rangle$, where $\langle LL|$ and $\langle RR|$ are the transposes as you mentioned in your question. Then just compute to get the matrix.


Abrir um modal com um botão noutro modal?

Question: Eu tenho um modal do bootstrap onde tem um botão que fecha o modal mas queria que mal fechasse o modal, abrisse outro. Já tentei meter um id no botão para ao clickar abrir o modal de novo mas não está funcionando.
Este é o que tenho

            <button type="button" class="btn btn-success" id="open">Inscrever-me nesta aula!</button>
                <button type="button" class="btn btn-info" data-dismiss="modal">Fechar</button>

    //Texto complementar com divs

Para abrir o primeiro modal, eu abro carregando num event do FullCalendar, e o outro externamente.
$("#open").click(function(){
    $("#fullCalModal2").modal();
});

Comment: Por que você não ele abrir o outro modal ao clicar no fechar?
Comment: Esse calendar tem o botão fechar com id ou class?
Comment: @adventistaam O que supostamente abre outro modal é só se o utilizador se quiser inscrever e o outro é apenas para fechar o modal
Comment: @adventistaam No fullCalendar, está assim ` $('#fullCalModal').modal();`
Comment: @adventistaam Peço desculpa o código postado estava desatualizado, veja agora
Comment: no `fullCalModal2` tem os botoes identificados? ID ou Class?
Comment: @adventistaam Você tem razão, foi apenas um erro. Existiam dois botões com o mesmo id e eu estive sempre a alterar o botão errado. Publique a sua resposta que você está correto.
Comment: @I_like_trains é para abrir o segundo modal a partir do evento click de algum botão, ou após fechar o primeiro abre o segundo?
Answer: Verifique se no fullCalModal2 tem os botoes identificados? ID ou Class?
Dá uma olhada nesse exemplo:

$('.btn-info').on('click', function(){
  $('#myModal').modal('show');
});

$('.btn-botao').on('click', function(){
  $('#myModal1').modal('show');
});
#myModal:nth-of-type(even) {
    z-index: 1042 !important;
}
#myModal-backdrop.in:nth-of-type(even) {
    z-index: 1041 !important;
}

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

<button type="button" class="btn btn-info btn-lg" >Open Modal</button>

        <button type="button" class="close" data-dismiss="modal">×</button>

Modal Principal

Some text in the modal.

        <button type="button" class="btn btn-primary btn-botao">Abri outro Modal</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        <button type="button" class="close" data-dismiss="modal">×</button>

Modal Secundário

Some text in the modal secundario.

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Você pode ver outro exemplo aqui
Comment: Bom eu entendi isso rs
Comment: @VirgilioNovic A sua imagem foi a minha reação ao ver o que tinha de errado
Comment: Eu não sabia que era assim... legal.
Comment: Assim como? rs.
Comment: é para abrir o segundo modal logo em cima? a partir do evento do botão? é isso !!!
Answer: Pelo que eu entendi, se abre um modal, e logo após o seu fechamento, abre outro modal, se for isso, resolvi fazer um exemplo:

jQuery(document).ready(function() {
  $("#open").click(function() {
    $("#fullCalModal").modal();
  });
  $("#btnopen").on('click', function (e) {
    $("#fullCalModal2").modal();
  })
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

        <button type="button" id="btnopen" class="btn btn-success" data-dismiss="modal">Inscrever-me nesta aula!</button>
        <button type="button" class="btn btn-info" data-dismiss="modal">Fechar</button>

        <button type="button" class="btn btn-info" data-dismiss="modal">Fechar</button>

<button class="btn btn-success" id="open">Abrir Modal</button>


Does Scala have modulo in the standard library?

Question: I'm assuming the answer is no because I can't find it, but it wouldn't be the first time I'd be wrong about that. Meanwhile I usually define it like this:
implicit class IntWithMod(x: Int) {
  def mod(y: Int) = x%y+(if (x < 0) y else 0)
}

Is there a scala library (ideally the standard library, external works too though if it's not huge) that defines this? If not, is there some easy way to add this to all integral types (doing this manually for each one is kinda tedious).
Answer: % is modulo.  Scala does not have the zero-or-positive version that you wrote above.
You could write the code generically using scala.math.Integral, but it would be so slow that you wouldn't want to use it.
Just write it all out.  It should take you only slightly longer than it did to ask this question.
Comment: No its not. `%` is the remainder operation, which may be similar to modulo but isn't the same thing.
Comment: (mod n) is an equivalence relation on integers. The modulus operation is supposed to pick _one_ representative per equivalence class. One of the properties of modulus is that (Z mod n;+(mod n)) forms a group, which, amongst other things, means that x+1=y+1 => x=y. (-1)+1 (mod n) = (n-1)+1(mod n) = 0, i.o.w. -1 = n-1 (mod n). If % was the modulus operation it should pick the same representative if two numbers are equal mod n, but it doesn't.
Comment: @Cubic - Evidence?  In favor of `%` being modulo: http://en.wikipedia.org/wiki/Modulo_operation
Comment: @Cubic - I agree it's a poor choice mathematically.  I wish programming language designers would not use the same term to mean something that isn't quite what the mathematical term is (vector is particularly painful).  But this is a valid modulo in computer science, so if you want to communicate clearly you can specify that you want a modulo operation that forms a group.  Anyway, the answer is the same regardless of what you call it: no, it's not there.
Answer: You can use the Java standard library modulus function:
http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floorMod-int-int-
scala> java.lang.Math.floorMod(-7, 4)
res4: Int = 1

scala> java.lang.Math.floorMod(7, -4)
res5: Int = -1


What needs to be achieved before site launch?

Question: The idea of this question is to start to focus on proactive things that we, as a community, can do to get the site more polished and ready for the official launch this is hopefully coming. Many of these are tasks that will continue beyond the beta period, but it seems like it would be good to get into as good a shape as possible before then.

Update the FAQ At the moment, we have a fairly generic welcome page that details the basics of how to use an SE site. Should we have details on issues more specific to economics.SE (such as our policy on homework questions -- see below)? Is it a good idea to have a one-stop FAQ page, or should we have one general "how to use the SE" FAQ and another one dealing with the question of what is on topic at econ.SE? We should also think about common reasons why people's questions/answers get put on hold or down-voted and try to provide some guidance on resolving this.
Agree official guidelines on homework questions This issue comes up again and again (see, for example, here, here, here). My impression is that we have converged on something like a consensus around the approach that homework questions are allowed but must show effort and must not be too specific so as to be of no interest to future visitors. But if this is really the consensus then perhaps we should codify it somewhere.
Think about whether there are other areas where guidelines are needed One facet of this was briefly discussed here. But are there common problems people see coming up, and is there a useful way that we can construct a policy for dealing with them?
Update the comment templates Here are some template comments that can be used in response to questions that need improvement. But it would be better if they all pointed to some appropriate page (such as the FAQ) where people can find information about why their question is being put on hold/down voted and what they can do about it.
Compile a community wiki listing common newbie questions I'm not sure whether we have enough material to do this yet, but it might be a good idea to start to put together canonical questions (much as FooBar has started to do) that are likely to speak to a lot of newcomer's queries. Having identified such questions, we could (a) put a lot of effort into getting some really high-quality answers posted and up-voted, and (b) compile a list of where to find these basic questions and their answers.
Agree what the Econ.SE should look like Once SE sites get out of beta, they get a proper customised site design that reflects the subject matter of the site. What should the econ.SE site/logo look like? This was briefly discussed here, but the discussion didn't go very far.
Continue the work of organising our tags Including merging duplicates (and voting on proposals to do so), and deleting redundant tags. Also, if you visit our tag page you will see that each tag has a tag wiki with details on what the tag means and when it should be used. It would be great if the community could see that most of our tags have a wiki. Here are some guidelines on wiki authoring.

I am making this post into a community wiki. My suggestion is that anyone who has a task to contribute to the above list goes ahead and adds it into this post. "Answers" below can be used for suggestions on how any of the above issues should be handled (or why they should not be handled!)
Comment: @Jamzy I have no inside information. My guess would be, alas, no. Some of the sites currently in beta have been in that state for four years! But this is endogenous: the more we work at building an active community around a refined platform, the closer we will be to that goal.
Comment: Are we remotely close to coming out of Beta?
Comment: Does the FAQ simply live in the meta page? Is there a way to sticky it or something?
Answer: I agree with everything being said. I think Foobar trying to get some basic questions excellent answers is definitely worthwhile.
For me, the biggest issue we are having at the moment is that we are getting a lot of low quality questions. Too big a proportion of first time posters have their questions closed out straight away. Of that, a lot of them are asking high-school level questions which could be answered by themselves with a small amount of effort. I think this community is aiming at a much higher level than that.
An updated FAQ and improved guidelines can help make it clearer to new users what will and what won't get closed. I'd be happy to help on that.
Answer: The new (2015) SE policy on graduation from Beta can be read here. The positive criterion is very simple, and it reads:

"When a site starts to consistently receive 10 questions/day, we'll consider it for graduation."

For the last three months (May-June-July) we are fluctuating around 5 questions per day, which is good, but which also says that it is going to take a while (at least a few months if not more) to reach a state where there will be "10 questions per day, consistently". Essentially we are half the distance (and I hope that the other half does not follow growth's theory model of slowing convergence!).
But it is exactly at such a point, where the site is not a "few good men"-case anymore, where pro-active policies such as those proposed by the OP should be undertaken.
Concentrating on the FAQ issue, my proposal is: one-stop FAQ page, but with specific "what's off-topic / what's on-topic in economics.SE" put first. This is the logical way: first a new visitor needs to now what is on-topic here (and certainly what is not), and then, if he still wants to go on and ask, he needs to know how to ask.
And here is a proposed text on the matter: - I am posting it as a work-in-progress, and editing by any other member is of course part of the process:

Welcome to Economics.SE, the free, community-driven Questions and
  Answers site for economists, econometricians, students of economics,
  and anyone who wants to understand why and how economic activity makes
  the world go round.
Not all questions with some economic-financial content are on-topic
  here. A few guidelines to help you choose wisely and allocate your
  time-resources efficiently:
Personal finance (off-topic): if you have an issue with your loan, or pondering what down-payment to accept for your new car, or how much
  marketing expense you should incur for your new business venture, we
  won't be able to answer your question. True, your situation requires
  knowledge of certain aspects of the Economics discipline, but it is
  also true that any serious answer should take into account many data
  particular to your situation, which would turn it into professional
  consulting services -and such an acitvity is definitely off-topic here. You could try
  the SE site Personal Finance & Money.
Econometrics (on-topic): definitely. In case your question does not find an answer here, you could ask that it be migrated to the good people over at Cross-Validated SE site, that deal with all Statistics.
Financial Economics (on-topic, but): This is definitely part of Economics discipline, but there is also a dedicated SE site for Quantitative Finance. You should determine where your question has a greater chance of being answered usefully for you.
Accounting (not-really-on-topic): Don't take us wrong, we all respect the scientific discipline of Accounting, and we rely on Accounting for reliable data on what businesses actually do in this life. But Accounting is indeed a separate scientific discipline, and even though some members here may have actual experience and theoretical knowledge of the Principles of Accounting, we cannot really guarantee expert answers to your questions, as the SE motto goes. So please, spare us the embarrassment.
Corporate Finance/Business Economics (on-topic, in principle): Corporate Finance/Business Economics is usually either really simple Economics, or horribly complex applied micro-macro-economic-o-metrics (and then some). Fire away and ask though, and we will see what happens. It is  expected that some Accounting concepts and tools may surface here and be needed, and we will do our best.
Software questions (on-topic): Questions related to software used in economics and econometrics, are on-topic here, but this does not
  mean that a very technical, programming-level question will find an
  answer.
Literature/books requests (on-topic): Economics is not "a few everyday rules of thumb". If you think that it is, sorry but with all
  due respect, you are off-topic here. If you don't, and seek to
  understand the complex economic interactions of our world through
  studying what the professional scholars have to say on the matter, go
  ahead and ask.
Queries for Data (on-topic): Theories should be tested against real-world data. So queries for Data sets and data in general are on-topic here. You can also try the Open Data SE site.
Homework/Self-study question (quasi-on-topic): always a hot issue in SE sites, and always difficult to commit to a very specific policy.
  You may see your such question getting just hints, or quick answers, or very long educational answers, or simply
  being closed as "off-topic" -if the members of this community feel
  that you want them to do your homework for you. To avoid that, you
  have at least to present in the question what part of the question you
  do understand, and where specifically lies your problem.  And a
  friendly advice: don't try to conceal that your question belongs to
  this category -many active members here can spot a homework question
  from miles away. Elaborations on parts of textbooks that you don't
  understand fall in this category.
Too broad questions (off-topic): economic activity permeates so much almost all aspects of modern societies, that it is very easy to
  ask a very broad question, which would be literally unanswerable.
  We are dealing with a scientific discipline here, and science works by initially narrowing
  its focus in order to be able to go deep. Do the same -narrow the
  focus of your question. In social sciences, very rarely do we have
  truly "universal laws", and Economics is no different (of course, abstractions is not the same thing as "universal laws".)
Opinion-requests (off-topic): it is also very natural to want someone to evaluate, or to make a value-judgement on, something that
  preoccupies you: But questions like "Is communism better than capitalism? Is money a
  sin?" are off-topic here. (But, say, "how did the transition of the
  Eastern Europe economies from a centrally planned economy to a market
  economy fared in terms of per capita income?"
  is a perfectly on-topic question, although it would be even better if
  you could narrow your scope to, say, a specific country).   Even
  apparently less politically/philosophically charged questions like "Is
  International Trade good?" (good for whom? Even if,say, it creates
  inequality, who says that inequality is "bad"? Why is it "bad?"), are
  off-topic here. Try to ask something that a member can answer using
  facts, studies, economic theory and reasoning -not
  moral/political/religious/philosophical values (which may unavoidably be present -we know our epistemology-, but that does not mean that we should give them center-stage. We won't.).
Comment: Also, the only main amendment I would suggest is, with `accounting`. It hasn't been discussed in too much detail in meta but i would say any questions dealing with principles of accounting are off-topic. From memory, these usually get closed.
Comment: The different classifications confuse me. For example, Econometrics and Financial Economics seem to be the same ("On-topic here, but there's a dedicated site to it which may deliver better answers"), but one of them is **on-topic**, and one of them is **on-topic, but**. Perhaps these brackets can be standardized? Also, do we have the markup to put the descriptions  into spoiler tags or something, such that one can at the start scroll quickly through everything and then click one something if one wants the description?
Comment: excellent. Should there be something in there regarding the level we are aiming for? I'm not convinced that it is necessary, looks like these rules would filter most of those questions out.
Comment: @Jamzy Thanks for the thumbs-up. I would vote against saying anything about "level" -it will be very difficult not to be misleading, and it is also... "politically charged" !(internally). I agree that Accounting, in the proper scientific meaning of the word, is not really on-topic here. I edited the proposed text on the matter, how does it look now?
Comment: that seems perfect to me. I think this list will be really useful in getting better questions and improve the consistency of questions getting closed.
Comment: @Jamzy I think I am done with it (except if any other suggested edits appear), but apart from that, I leave the matter to the upvote/downvote count, and to the judgement of our moderators.
Comment: @FooBar Cross-Validated is not a site dedicated to Econometrics, far from it. Indicatively, in CV out of 61,000 questions there are currently only 700 questions using the tag "econometrics" (and 235 of them are unanswered). So I don't think the two cases are adequately similar. In any case, any suggested edit? The second part of your comment goes beyond my technical knowledge here. But if it can be done, it would be very good.
Comment: I like this proposal, but my personal preference would be (1) for the text to be more formal/less chatty, and (2) for it to be shorter and more to the point. But I recognise that this is entirely subjective, so I won't make any heavy-handed edits until more people have chimed-in.
Comment: Folding blocks of text is a feature that has been requested (http://meta.stackexchange.com/questions/5199/please-add-the-ability-to-fold-blocks-of-code-in-questions-and-answers), but does not seem to have been implemented yet. But judicious use of the formatting tools we do have should help to increase readability.
Comment: @Ubiquitous The command used to "hide" text in puzzle questions? :)
Comment: @Ubiquitous I made it chatty because in my experience, people prefer to read chatty statements rather than "formal" ones.
Comment: @Ubiquitous I agree with "too long". If we can get spoiler tags, it doesnt matter too much, and might be nice to be extensive. At its current form, without spoiler tags, it is too long, and I would even prefer nested bulletins for readability. Are spoiler tags possible? :o
Comment: @Ubiquitous What is that status of this proposal?  I don't mind mine or Foobar's version, or some other, but I believe it would be good to include some version in the FAQ page. The final decision rests with the moderators.
Comment: @AlecosPapadopoulos I think this should be implemented in some form. My personal preference would be for FooBar's version. You are very welcome to make the necessary edits to the FAQ, which is a community wiki.
Comment: @Ubiquitous Please review/edit the FAQ page. And please notify also the other moderators to have a look.
Answer: I took Alecos' text, reorganized the structure, and tried to shorten it. Happy if you change the words, it was quickly written. Also, one might invert the order (On-topic first).

Welcome to Economics.SE, the free, community-driven Questions and
  Answers site for economics. Not all questions with some economic-financial content are on-topic here. Here is a differentiation.
Off-topic

Personal finance: Personal matters of finance and investment are offtopic here. Have a go at Personal Finance & Money.
Accounting: Accounting is a separate discipline, and there is no StackExchange site dedicated to that matter yet. You could propose one.
Too broad questions: We are dealing with a scientific discipline here, and science works by initially narrowing
  its focus in order to be able to go deep. Do the same -narrow the
  focus of your question. In social sciences, very rarely do we have
  truly "universal laws", and Economics is no different.
Opinion-requests: it is also very natural to want someone to evaluate, or to make a value-judgement on, something that
  preoccupies you: But questions like "Is communism better than capitalism? Is money a
  sin?" are off-topic here.Try to ask something that a member can answer using
  facts, studies, economic theory and reasoning -not
  moral/political/religious/philosophical values

On-topic, but not perfectly suited
The following topics belong to economics and are welcome here. However, there may be a different StackExchange community with a more narrow focus, where you might get an answer of higher quality:

Financial Economics: There is also Quantitative Finance.
Corporate Finance/Business Economics: Corporate Finance/Business Economics is usually either really simple Economics, or horribly complex applied micro-macro-economic-o-metrics (and then some). Fire away and ask though, and we will see what happens.

On-Topic

Econometrics: Especially for theoretical questions, have a look at  Cross-Validated.
Software questions: Questions related to software used in economics and econometrics, are on-topic here.
Literature/books requests
Queries for Data: Queries for Data sets and data in general are on-topic here. You can also try the Open Data SE site.
Homework/Self-study question: always a hot issue in SE sites, and always difficult to commit to a very specific policy.
  You may see your such question getting just hints, or quick answers, or very long educational answers, or simply
  being closed as "off-topic" -if the members of this community feel
  that you want them to do your homework for you. To avoid that, you
  have at least to present in the question what part of the question you
  do understand, and where specifically lies your problem.
Comment: That's a good alternative approach. I only disagree with the placement of Econometrics - I would initially place it in the "on-topic" category, and let time decide on the matter.


bootstrap 3 - Inverse nav-justifed

Question: How to make nav-justified to act in reverse order? What I mean is, I want on small (mobile) screens from tabs/pills to be positioned horizontally, and on bigger (desktop) screens to be positioned vertically i.e. to be stacked.
Here's an example for which CSS rules need to be modified (resize its window to see how it would look on both type of screens): http://s.bootply.com/render/1d0Cpp0po1
Does anyone know how to achieve this on the simplest way? Thanks in advance!
Answer: Solved it with this CSS:
.nav-justified-inverse > li {
    float: none;
}

@media (max-width: 768px) {
    .nav-justified-inverse > li {
        display: table-cell;
        width: 1%;
    }
}

Demo: http://s.bootply.com/render/AtQH4rry48

bootstrap 3 - Inverse nav-justifed


Erlang: find word from list and return True

Question: How can I make function to search for a word in list and return true if word in list.
Example :
find(string) ->
    List = ["bye", "hello", "hi"],
    case string in List of
        true ->
            true;
        _ ->
            false
    end.

find("hi there, how are you today?").

And the text is : "hi there, How are you today?"
it should return true cuz hi in list.
Comment: I generally put as much work in an answer as the person puts in the question. What have you tried?
Comment: @NeilLocketz I edited my question. I'm newer in Erlang so I don't know how it'll be the function. thnx.
Answer: 1> F = fun(String) -> List = ["bye", "hello", "hi"], lists:any(fun(S) -> lists:member(S, List) end, string:tokens(String, " ,.?!")) end.
#Fun<erl_eval.6.54118792>
2> F("hi, what did you tried so far?").
true


Can Monty Hall be applied to Among Us?

Question: I came across a video (not sure if I'm allowed to post it because it had some kid was swearing due to the nature of the game's lobbies) where the guy claimed that you can apply Monty Hall to Among Us.
So basically he picks some random guy in his head to be imposter, lets the round take place and then he switches to a different guy - also in his head - after a body is found. He claims that this increases the probability of him finding the imposters by pure statistics. Obviously this works better with more people on board with him.
So I dug into it and I tried to apply Monty Hall to guess the imposter but to the game I couldn't.
The main difference between the 100 doors Monty Hall problem and Among Us is that in the 100 doors game, the game master will eliminate 98 doors for you and you'll be left with one door plus the one you initially chose. Choosing to switch increases your chances of picking the correct door.
However in Among Us, there is no way you're going to be left with one crewmember and an imposter. You'll usually have 1 or 2 dead bodies which is NOT equivalent to the game master eliminating all the n-2 doors.
Is there a way to apply Monty Hall recursively while eliminating n-x doors rather than n-2?
EDIT:
For those who don't know how Among Us is played.
It's usually played with the following settings.
2 imposters and 8 crewmembers on a map. The map has various tasks for the crewmembers to do. If they finish all tasks they win. If the imposters kill them to the point of where their number is greater to or equal to the number of remaining crewmembers, the imposters win.
Each round the imposters usually kill 1-2 crewmembers (it could be more if the crewmembers are that unlucky/bad). Once a body is discovered by a crewmember, the crewmember will report it and all players (imposters and crewmembers) will be given a chance to discuss their whereabouts and people will start accusing each other with one objective, to find the imposters and vote on ejecting them.
The players get to eject only ONE person per round. It could be an imposter or it could be a crewmember. It's only revealed after the game is concluded (or it can be revealed right after the ejection if they create it with the alternate setting).
Comment: This doesn't apply because among the possible dead bodies that could be found, *the initially picked person was also possible*.  This is not equivalent to the Monty hall problem.  Switching without any additional information does not increase the probability.  (*Now... switching because you followed the person around and saw they couldn't have been the killer... that's another story*)
Comment: So switching based on evidence would still count as "Monty Hall"? Because at this point it seems to me that it's like simple process of elimination.
Comment: Also, it's likely that you will die if you "find" the impostor. Of course, I was so strictly following a player last game that they knew he was the killer when I turned up dead.
Answer: Let us look at a far simplified game with two other crewmates and one imposter. (four players including ourselves with us as player $4$)
Let us assume that we are not an imposter and are not the first victim.  Without loss of generality, let us have picked player $1$.
The following six scenarios are equally plausible:

Imposter: Player $1$, Dead: Player $2$, Still living crewmate: Player $3$
Imposter: Player $1$, Still living crewmate: Player $2$, Dead: Player $3$
Still living crewmate: Player $1$, Imposter Player $2$, Dead: Player $3$
Still living crewmate: Player $1$, Dead: Player $2$, Imposter: Player $3$
Dead: Player $1$, Imposter: Player $2$, Still living crewmate: Player $3$
Dead: Player $1$, Still living crewmate: Player $2$, Imposter: Player $3$

It should be plain to see that your initial guess is only right $\frac{1}{3}$ of the time.  If the person you initially guessed happens to have been the first murder victim... then obviously you should switch.  Not switching guarantees you picked the wrong person and switching only gives you $50$-$50$ odds.  Now... given that your initial pick was not the first murder victim, we see that the first four cases are equally likely and not switching versus switching each give the same chance of winning.
The whole point to take away from this is that in the original Monty Hall problem the host would never willingly reveal the door you initially selected before giving you the chance to switch.  The "desire to switch" rather than staying with your original choice which would purportedly increase your chances of winning all effectively got absorbed by the last cases listed where our initially selected player was first killed.
Long story short, no this is not the Monty Hall problem and in this scenario, without additional information (player behaviors, locations, etc...) there is not enough information to justify switching unless the player is dead in which case it is obvious that you need to switch.  This strategy does not provide any benefit whatsoever.

Can Monty Hall be applied to Among Us?


MySQL 8 unusual behavior

Question: The project that I'm working on using database frequently and does heavy procedures.
I'm always monitoring the system. with 16GB of RAM and 8 CPU's system usually works fine and not reaching it's limits but MySQL goes away very frequently with different errors:

Here is MySQL 8 configuration
   [mysqld]
    sql_mode=""
    pid-file        = /var/run/mysqld/mysqld.pid
    socket          = /var/run/mysqld/mysqld.sock
    datadir         = /var/lib/mysql
    log-error       = /var/log/mysql/error.log
    log_bin_trust_function_creators = 1
    join_buffer_size = 256M
    innodb_buffer_pool_size = 16G
    innodb_log_file_size=4G
    innodb_buffer_pool_instances=12
    expire_logs_days=3
    long_query_time=5
    innodb_lock_wait_timeout=100

How can I prevent this? What am I doing wrong?
Here is error log: https://gist.github.com/turalus/d581b46f349aa815ab49f486605c0061
Answer:
The table 'UserKeyword' is full!

Check disk space.

unknown variable 'query_cache_size=0'.

That setting (and similar settings) have been removed from MySQL 8.  Are you using an old my.cnf?  Remove references to query_cache... from the config.

Do you already have another mysqld server running with Mysqlx ?'

Perhaps two instances are running?

innodb_buffer_pool_size = 16G

Not if RAM is 16GB.  Change the setting to 10G.

MySQL 8 unusual behavior


VBA excel nesting data from excel into a table in word (copying excel data into Word table)

Question: I'm trying to paste a table into word from excel with VBA Excel.
I'm pasting it into a cell in a single column table of 4 rows I created in Word. So it is essentially a nested table.
I keep getting,

Run-time error 4605: Method 'PasteAsNestedTable' of object Selection failed

I'm trying to use PastAsNestedTable because otherwise I get the Run-time error about cells not matching as it is trying to merge the two tables.
So I get it is saying PasteAsNestedTable isn't a method of selection but how do I get around this issue?
My updated code goes:
Dim wdApp As Word.Application
Dim wdDoc as Word.Document
Dim tabl1 as Table, tabl2 as Table
Set wdApp = new Word.Application
With wdApp
     .visible = True
     .Activate
     .Document.Add(location)

Set wdDoc=wdApp.ActiveDocument
With wdApp
   Charts("chart1").ChartArea.Copy
     .Selection.GoTo what:=-1,Name:="chart1"
     .selection.Paste
(Then add some more charts)

End With

Sheets("Sheet1").Range("A1:F10").Copy
    Set wdDoc=wdApp.ActiveDocument
    wdDoc.Bookmarks("table").Range.PasteAsNestedTable

With wdApp
(Then repeat above pasting charts + tables)

`
If I made the Range a ListObjects could I somehow copy it in that way?
Comment: Have you read this? https://msdn.microsoft.com/en-us/library/office/ff837670.aspx
Comment: You code can't work since `wdApp` is a new Word Application with a totally empty document. There cannot be a Bookmark "tableplace". And `.Selection.GoTo what:=-1 Name:="tableplace"` lacks a comma between the parameters. So it will not compile.
Comment: @AxelRichter,  I've left out a line where I open a template. The template has a bookmark named "tablespace". I've used the `.Selection.GoTo what:=-1 Name:="tableplace"` format for copying charts to other bookmarks in the word doc and that works fine.
Answer: Don't use Selection.
This here works for me (Word with correct document already opened):
Dim wdApp As Word.Application
Dim wdDoc As Word.Document

Set wdApp = GetObject(, "Word.Application")
Sheets(1).Range("A1:F10").Copy
Set wdDoc = wdApp.ActiveDocument
wdDoc.Bookmarks("tableplace").Range.PasteAsNestedTable

You can of course replace GetObject(, "Word.Application") with your new Word.Application and set wdDoc as wdApp.Documents.Open(pathtoyourdoc).
Then combine with my answer from your other thread, replace wdthere with wdDoc and you should be good to go.
Edit I have changed my code to reflect your current variables and bookmark names:
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim tabl1 As Table, tabl2 As Table

Set wdApp = New Word.Application

With wdApp
     .Visible = True
     .Activate
    Set wdDoc = .Documents.Open(Location)
End With

Charts("chart1").ChartArea.Copy
wdDoc.Bookmarks("chart1").Range.Paste

Sheets("Sheet1").Range("A1:F10").Copy
wdDoc.Bookmarks("table").Range.PasteAsNestedTable

'(Continue like this for other charts + tables)

Note:

Do not use Douments.Add, as this will add a new empty document based on a template. This will not have your bookmarks. Use .Open instead.
Close With blocks properly
Do not set the same object over and over again. Set it once and work with that object
Do not use Selection unless absolutely necessary. Not necessary in this case.
Comment: it kind of works. I need to paste in 3 tables in three different locations. For the first two I get the Runtime error '4605': method 'pasteasnestedtable' of object 'range' failed. But when I hit debug and F5 it pastes it correctly and continues on. However for the third one it says Run-time error '5941': The requested member of the collection does not exist.  I have no idea hot to fix this
Comment: @JoshD Please post the exact line where the error happens. Sheet unknown? Cell range out of bounds? Bookmark name typo or deleted before insert? So many possibilities.
Comment: Ha, was just in the middle of typing. The third paste RE 5941 was my typo. Apologies. The RE 4605 occurs at the line: `wdDoc.Bookmarks("tablespace").Range.PasteAsNestedTable`
Comment: Alright. Bookmarks "tableplace", "tablespace" exist? You speak of 3 paste operations. Got 3 different bookmarks? Addressing them all properly? Let's see code.
Comment: Yeah all good, sheets are labelled correctly, as is the range and there are three different bookmarks, i.e. "tablespace2" and "tablespace3"
Comment: Code or it didn't happen! :-} Plus line of error please.
Comment: `Sheets(1).Range("A1:F10").Copy Set wdDoc = wdApp.ActiveDocument wdDoc.Bookmarks("tableplace").Range.PasteAsNestedTable` . The error occurs on the final line for all three pastes saying Run-time error '4605': method'pasteasnestedtable'of object'range'failed
Comment: Please edit your post to reflect the current code situation. The error could be with any of `Sheet()`, `Range()`, or `Bookmarks()` and cannot be identified without context.
Comment: SO currently I have it set as:
`Dim wdApp As Word.Application
Comment: Ok now I get the RT error: 4605 This command is not available. When coping the first chart in. IE at the `.wdDoc. Bookmarks (......` row. I can't overide it like the old error. However if I drag the fellow arrow past the charts to the table it will past no problem.
Comment: No-brainer: a chart is not a table and can therefore not be pasted as a nested table. Paste it as something else instead: normal paste, bitmap...
Answer: You can set DocVariables in Word.  Google this if you don't know how to do this.  Then, run the script below, from Excel.
Sub PushToWord()

Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
sWdFileName = Application.GetOpenFilename(, , , , False)
Set doc = objWord.Documents.Open(sWdFileName)
'On Error Resume Next

objWord.ActiveDocument.variables("FirstName").Value = Range("FirstName").Value
objWord.ActiveDocument.variables("LastName").Value = Range("LastName").Value
objWord.ActiveDocument.variables("Another").Value = Range("Another").Value

objWord.ActiveDocument.Fields.Update

'On Error Resume Next
objWord.Visible = True

End Sub


Why is there a 40 Gigabit Ethernet (40GbE) standard in IEEE 802.3?

Question: I've been wondering, why is there a 40 Gigabit Ethernet standard? Is there a reason why it's 40GbE and not 50GbE or why is there any step in between from 10GbE to 100GbE?
Unfortunately my own research didn't lead to an answer. The only thing someone wrote in a forum was, that 40GbE was the highest speed, which could be achieved with copper, when this standard was introduced, but as far as I understand 40GbE and 100GbE was proposed at the same time?
Comment: A twisted-pair cable has four pairs of cables. If each pair could do 10Gb/s, ... WARNING: this is an unconfirmed claim I have heard somewhere, don't trust me!
Answer: There are two main reasons, and they are closely related.
One is that the use of four data paths is common and 10Gb PHYs are available. That would make 40GE a natural step.
Another is that it was expected to be common for backplanes to have a 40Gb path that would be broken out in a line card to four 10GE links. A 40GE standard would allow a line card that plugged into that same backplane connection.
Comment: Further, 25 Gb came about because it was cheaper than 4x of the PHYs to make a 100 Gb.  The state of the art single lane will be popular, particularly if it can fit in a RJ45 or SFP form factor.


Base change of flat morphism preserve relative dimension

Question: I have a flat morphism of relative dimension $d$. Is it true that a base change of this morphism is a flat morphism of the same relative dimension? We can assume that all schemes are of finite type over some field and equidimensional.
Comment: Yes, you show this using that if $X$ is a finite type $k$-scheme of pure dimension $n$ (where $k$ is a field), and if $K/k$ is a field extension, then the base change $X_K=X\times_k K$ also has pure dimension $n$. See Vakil's "Foundations of Algebraic Geometry'', Exercise 11.2.J for a series of useful hints if you want to prove this. If you know this statement already, then your statement follows as flatness is also preserved by base change.
Comment: I know the fact about extension of scalars. Can you please elaborate how the statement follows?
Comment: I will put it in an answer.
Answer: Let $\pi\colon X\to Y$ be a flat morphism of finite type $k$-schemes, which has relative dimension $d$. Let $f\colon Y'\to Y$ be another morphism of schemes over $k$. We have to show that the pullback $\pi'\colon X'=X\times_Y Y'\to Y'$ is flat of relative dimension $d$. We know that $\pi'$ is flat, so now we have to show that for an arbitrary point $y'\in Y$, the fiber $\pi'^{-1}(y')$ has dimension $d$ over $k(y')$. We have the following diagram of pullbacks:

(I'm sorry for its comical size.) By pullback pasting, the large rectangle is also a pullback diagram. However, the bottom composite equals $\mathrm{Spec}\,k(y')\to\mathrm{Spec}\,k(f(y'))\to Y$, and hence $\pi'^{-1}(y')$ is isomorphic to the base change $\pi^{-1}(f(y'))\times_{k(f(y'))} k(y')$. We know that $\pi^{-1}(f(y'))$ is of dimension $d$ over $k(f(y'))$ as $\pi$ is flat of relative dimension $d$, so $\pi'^{-1}(y')$ is also $d$-dimensional over $k(y')$, because the pure dimension of finite type schemes over a field is preserved under any field extension.
Comment: And we do not need nor $Y$ nor $X$ to be equidimensional, yes?
Comment: No, because we are only interested in the dimensions of the fibers. These need to have a constant pure dimension.


Prove this mathematical induction?

Question: $$
\sum_{j=1}^{n} 2^j = 2 \left( 2^{n} - 1 \right)
$$
Could someone explain how to prove this problem fully?

Link to problem image
Answer: When $n=1$,
$$L.H.S.=\sum^{(1)}_{j=1}2^j=2=2\big(2^{(1)}-1\big)=R.H.S.$$
$\therefore$The proposition is true for $n=1$.
Assume that the proposition is true when $n=k\in\mathbb{Z^+},$ i.e. $$\sum^k_{j=1}2^j=2\big(2^k-1\big).$$
When $n=k+1$,
$\begin{split}L.H.S.&=\sum^{(k+1)}_{j=1}2^j\\&=2\big(2^k-1\big)+2^{k+1}\\&=2\big(2^{(k+1)}-1\big)\\&=R.H.S.\end{split}$
$\therefore$The proposition is true for $n=k+1$ when the proposition is true for $n=k$.
$\therefore$The proposition is true by the principle of mathematical innduction.
Answer: Use the relations
$$
1 - q^n = (1 - q)\left( 1 + q + \cdots + q^{n-1}\right)
$$
and
$$
\sum_{j=1}^{n} 2^j = 2 \left( \sum_{j=0}^{n-1} 2^{j} \right)
= 2 \frac{1 - 2^{n}}{1 - 2} = 2 \left( 2^{n} - 1 \right)
$$

Prove this mathematical induction?


Class design 'dilemma'

Question: I never did proper class design, so bear with me.
Let's say we have a Project class. Then let's say we have a ProjectGroup class that has the same members as the Project class, plus a list of Projects.
Should ProjectGroup be the superclass of Project or is ProjectGroup a specialization of Project and the former should be a subclass of the latter?
Comment: not an answer to your immeduate problem but check out Domain Driven DEsign by Eric Evans, or Object Thinking by David West.
Comment: @Mitch Wheat I'll have a look, tnx
Answer: I won't bother you with theory, because you're probably in a hurry to get a quick answer. So here it goes:
If your two classes are actually implying they should be related by inheritance then ProjectGroup should inherit from Project class. This is how it would look like in C#:
public class ProjectGroup: Project ...

If they are not, but they use some common class members (that define their state and some functionality over that state), then I'd write an interface and implement it in both classes. C# code again:
public interface ICommonState ...

public class Project: ICommonState ...

public class ProjectGroup: ICommonState
{
    IEnumerable<ICommonState> projects
    ...
}

Edit
If your classes are actually Project and ProjectGroup and they both have properties like ID and Name in common (for instance), they still shouldn't be inherited. They just happen to have properties with the same name, but they are basically different entities.
They could both either

implement an ICommonEntity interface - use it when they have the same state+functionality but functionality behaves differently in each of them
inherit from CommonEntity class - use it when functionality is completely identical; this way you'll follow the DRY (don't repeat yourself) philosophy

So your component may be an interface or a class (when using composite pattern).
Direct inheritance between two classes is more suitable where entities imply on being in relation to each other. Like User and Person classes. They can be inherited either way. Depending on the business scenario.
class User: Person

This would be the case where you have an application with contacts. Some of them are also users of this very same application.
class Person: User

This would be a web site where you can register as a user. In case you fill up some personal details as well your user data becomes of type Person.
Comment: If you are willing to elaborate, please do. This is related to a minor part of the project I'm writing, so I'm in no hurry.
Comment: Since the two classes methods perform the exact same operation (the difference is only the addition of the `Project`s list and method to handle them, does it make sense that the Component (as used in Composite Pattern) is a class instead of an interface?
Answer: It sounds like you might want the Composite pattern.  Both LeafProject and CompositeProject implement the Project interface, and CompositeProject also holds a collection of Project instances.
Comment: This is interesting, I'll look for more info about this Composite Pattern
Comment: @klez: My interface implementation is basically composite pattern.
Answer: if the member list of projects is unique to projectgroup and does not apply to all types of projects, then make project your super/base class and derive projectgroup from project.

Class design 'dilemma'


Understanding the proof of a formula for $p^e\Vert n!$

Question: This is a proof from a book on number theory I'm reading. I'm having a hard time following. I think there's a variable here that means two different things at two different times...
Theorem:
If n is a positive integer and p is a prime, then $p^e \vert\vert n!$, where $e=\lfloor\frac{n}{p}\rfloor + \lfloor\frac{n}{p^2}\rfloor + \dots + \lfloor\frac{n}{p^r}\rfloor$ and r is determined by n by the inequality $p^r \le n <p^{r+1}$
Proof:
For a given integer k, the multiples of $p^k$ that do not exceed  n are $p^k, 2p^k, \cdots, qp^k$ , where q is the largest integer such that $qp^k \le n$. But this says that q is the largest integer not exceeding $n/p^k$, so that  $q= \lfloor n/p^k \rfloor$. Thus, $\lfloor n/p^k\rfloor$ gives the number of positive multiples of $p^k$ that do not exceed n.

Interlude:
I understand the proof so far. We've simply chosen some power of p
  and shown that $\lfloor n/p^k \rfloor$ is the largest integer that we can multiply by $p^k$ and stay under n. Here's where I start to get confused.

Now, if $1 \le m \le n$, then $m=qp^k$ with $(q,p) = 1, 0 \le k \le r$, and m contributes precisely k to the total exponent e with which p appears in the canonical representation of n!

Interlude 2:
How exactly does $m=qp^k$ follow from $1 \le m \le n$? Also, this q seems to mean something other than $\lfloor n/p^k\rfloor$ since we seem to be considering the set of all numbers less than or equal to n and greater than or equal to 1 that have the form $m=qp^k$?

Moreover, m is counted precisely k times by the sum
$\lfloor\frac{n}{p}\rfloor + \lfloor\frac{n}{p^2}\rfloor + \dots + \lfloor\frac{n}{p^r}\rfloor$,
once as a multiple of p, once as a multiple of $p^2$, ... , once as a multiple of $p^k$, and no more. Of course, if $k=0$, then m is not counted in the sum. Therefore, the sum above accounts exactly for the contribution of each m between 1 and n to the exponent e as claimed.

Interlude 3:
What exactly is meant here by counted? I really don't understand the last part of this proof at all...
Comment: Re: Interlude 2, I don't think it's the same $q$. We're just writing $m$ as a power of $p$ (possibly $p^0$) times a number prime to $p$. We can always do this.
Comment: I thought so too. However I'm still confused at the last part of the proof. I always use different variables to avoid confusion, this really is annoying.
Comment: Re: Interlude 3, Think back to the beginning of the proof. $\lfloor n/p^s \rfloor$ counts the multiples of $p^s$ that are $\leq n$, and for $s = 1, \ldots, k$, your $m$ is such a multiple. So $m$ contributes $k$ to the exponent $e$ and $k$ to this sum on the RHS. There might be a better way of organizing this -- if no one else has done this when I get back from walking the dog, I'll give it a shot.
Answer: Interlude 2. You are considering the numbers of the form $qp^k$ that are between $1$ and $n$, because you are trying to figure out how many multiples of $p^k$ you have in $n!$. $m=qp^k$ does not follow from $1\leq m\leq n$; it is an extra condition. That is, "Let's now look at the numbers of the form $qp^k$ with $\gcd(p,q)=1$ that are between $1$ and $n$."
Interlude 3. In order to figure out the largest power of $p$ that divides $n!$, we need to count how many times $p$ occurs in the prime factorization of $n!$; this is equivalent to counting how  many times it occurs in the prime factorizations of each number $m$, $1\leq m\leq n$, and then adding.  It will appear once for every multiple of $p$ that is not a multipe of $p^2$; twice for every multiple of $p^2$ that is not a multiple of $p^3$; three times for each multiple of $p^3$ that is not a multiple of $p^4$; etc. But that is hard to count.
Alternatively: once for each multiple of $p$; then one more for each multiple of $p^2$; then one more for each multiple of $p^3$; then one more for each multiple of $p^4$; etc. That's easy to count, because we just figured out exactly how many multiples of $p$, how many multiples of $p^2$, etc. there are between $1$ and $n$.
There are $\lfloor\frac{n}{p}\rfloor$ multiiples of $p$; $\lfloor\frac{n}{p^2}\rfloor$ multiples of $p^2$; $\lfloor \frac{n}{p^3}\rfloor$ multiples of $p^3$; etc. Add them up, we get the number of times $p$ shows up in the factorization.
What they are saying is, instead: focus on a single $m = qp^k$, $\gcd(p,q)=1$. How many times do we count $m$? Once for $p$, once for $p^2$, once for $p^3$, etc. up until we get to $p^k$.
Comment: Arturo, I really can't thank you enough. Understanding this proof absolutely made my night. The formula itself is quite beautiful.
Comment: Thanks a bunch. I get it now. This is actually a really clever way to count the number of times p goes into n! I think I would have been helped if the book had labeled the content before the first interlude a lemma, and then not used q twice in the proof. But it makes perfect sense now.
Comment: @Josh: Glad to help.
Answer: Maybe the easiest way to follow the proof is to work through a numerical example. What power of 3 divides 100-factorial? Up to 100, the number of multiples of 3 is $[100/3]=33$, and each of these contributes a factor of 3. The number of multiples of $3^2$ is $[100/9]=11$, and each of these contributes an additional factor of 3. The number of multiples of $3^3$ is $[100/27]=3$, and each of these numbers contributes yet one more 3 to the product. Finally, the number of multiples of $3^4$ is $[100/81]=1$, giving yet one more factor of 3. All told, $$[100/3]+[100/9]+[100/27]+[100/81]$$
Answer: One can give a very nice proof using the Von Mangoldt function. We define $\Lambda(n)$, as follows. It equals $\log p$ is $n=p^k$ for some prime $p$; and $0$ else. Observe then that if $n=p_1^{\alpha_1}\cdots p_k^{\alpha_k}$ then $$\log n=\sum_{i=1}^k \alpha_i \log p_i= \sum_{d\mid n}\Lambda (d)$$
The last equality holds by observing we have $\log p$ accounted $\alpha_i$ times for $p^j\mid n,j=1,\ldots,\alpha_i$, and any composite divisor dies. Now, $$\log m!=\sum_{b=1}^m\log b=\sum_{b=1}^m\sum_{d\mid b}\Lambda(d)$$
It suffices we note that $$\sum_{b=1}^m\sum_{d\mid b}\Lambda(d)=\sum_{b=1}^m \sum_{d\geqslant 1}[d\mid b]\Lambda(d)=\sum_{d\geqslant 1}\Lambda(d)\sum_{b=1}^m[d\mid b]$$
and of course $\displaystyle\sum_{b=1}^m[d\mid b]=\left\lfloor \dfrac m d\right\rfloor$, since it counts the number of multiples of $d$ less than $m$. Thus
$$\log m!=\sum_{b=1}^m\log b=\sum_{d\geqslant 1} \Lambda(d)\left\lfloor\frac md \right\rfloor$$
Since the Von Mangoldt function is nonzero only at prime powers, $$\log m!=\sum_{i\geqslant 1}\sum_{p\;\rm prime}\Lambda(p^i)\left\lfloor\frac{m}{p^i}\right\rfloor=\sum_{i\geqslant 1}\sum_{p\;\rm prime}\log p\left\lfloor\frac{m}{p^i}\right\rfloor$$
Hence the result: if we define $v_p(n)=\displaystyle\sum_{i\geqslant 1} \left\lfloor\frac{n}{p^i}\right\rfloor$ $$n!=\prod_{p\rm\; prime}p^{v_p(n)}$$
Answer: This is referred to as Legendre's formula (1830) and is very popular in contest mathematics books. A complete treatment is given in pages 122-128 in Number Theory: Structures, Examples, and Problems by Titu Andreescu and Dorin Andrica.
As in $p$-adic Numbers by Fernando Q. Gouvea, I will refer to the highest exponent with which a prime $p$ divides a nonzero integer $n$ as $v_p(n).$
That is, if $n \equiv 0 \pmod {p^k}$ and  $n \neq 0 \pmod {p^{k+1}},$ then we say $v_p(n) = k.$ In particular, A and A define $e_p(n) = v_p(n!)$ and call it Legendre's function. The notation $v_p(n)$ makes a good deal of sense in English language writing, as the function $v_p$ is the "$p$-adic valuation," see page 25 of Gouvea. Ireland and Rosen
denote this by $ \mbox{ord}_p \; n = v_p(n),$ see pages 3-15.
Quoted without proof in
How to find maximum $x$ that $k^x$ divides $n!$
So, Theorem 6.5.1 on page 123 of Andreescu and  Andrica is
$$ e_p(n) = v_p(n!) = \sum_{i \geq 1} \left\lfloor \frac{n}{p^i} \right\rfloor = \frac{n - S_p(n)}{p-1}   $$
where $S_p(n)$ is the sum of the digits of $n$ when written in base $p.$
I thought I would prove the middle equality by mathematical induction. We need, for any positive integers $m,n,$
LEMMA:
(A) If $n + 1 \equiv 0 \pmod m,$ then
$$  \left\lfloor \frac{n + 1}{m} \right\rfloor = 1 +  \left\lfloor \frac{n}{m} \right\rfloor $$
(B) If $n + 1 \neq 0 \pmod m,$ then
$$  \left\lfloor \frac{n + 1}{m} \right\rfloor =   \left\lfloor \frac{n}{m} \right\rfloor $$
For $n < p,$ we know that $p$ does not divide $n!$ so that $e_p(n) = v_p(n!)$ is $0.$ But all the $\left\lfloor \frac{n}{p^i} \right\rfloor$ are $0$ as well. So the base cases of the induction is true.
Now for induction, increasing $n$ by $1.$
If $n+1$ is not divisible by $p,$ then $e_p(n+1) = e_p(n),$ while part (B) of the Lemma says that the sum does not change.
If $n+1$ is divisible by $p,$ let $v_p(n+1) = k.$ That is, there is some number $c \neq 0 \pmod p$ such that $n+1 = c p^k.$ From the Lemma, part (A), all the $\left\lfloor \frac{n}{p^i} \right\rfloor$ increase by $1$ for $1 \leq i \leq k,$ but stay the same for $i > k.$ So the sum increases by exactly $k.$ But, of course, $e_p(n+1) = v_p((n+1)!) = v_p(n!) + v_p(n+1) = e_p(n) + k.$ So both sides of the middle equation increase by the same $v_p(n+1) = k,$ completing the proof by induction.
Note that it is not necessary to have $n$ divisible by $p$ to get nonzero $e_p(n).$ All that is necessary is that $n \geq p,$ because we are not factoring $n,$ we are factoring $n!$
Comment: Your encyclopedic seeming knowledge of problem solving literature is frightening.
Comment: @Josh, dogs like me.
Answer: Let $n$ be a positive integer, and let $p$ be prime.  We want to find the largest $e$ such that $p^e$ divides $n!$.  We will understand what's going on  as soon as we have thoroughly absorbed one numerical example.  So let $p=5$ and $n=888$.
By the Fundamental Theorem of Arithmetic, the $5$'s come from the $5$'s that divide the various numbers from $1$ to $888$.  For example, the number $5$ contributes one $5$.  So do $10$, $15$, and $20$. But $25$ is divisible by $5^2$, so contributes two $5$'s.  But $30$ contributes only one, as do $35$, $40$, and $45$. However, $50$ is more generous and contributes two.  And some numbers are more generous still. For instance, $125$ contributes three, while $625$ contributes four.
Imagine that the taxperson wants to collect $1$ dollar fpr every $5$ that a number "has." So the number $10$ will have to pay a tax of $1$ dollar, while $75$ will have to pay $2$ dollars, and $675$ will have to pay $4$ dollars.
The taxperson collects the tax as follows. First she gets $1$ dollar from every number that is divisible by $5$.  These numbers are $1\cdot 5$, $2\cdot 5$, $3\cdot 5$, $4\cdot 5$, $5\cdot 5$, and so on up to $117\cdot 5$.  There are $117$ such numbers. To put it another way, the number of such numbers is
$$\left\lfloor \frac{888}{5}\right\rfloor.$$
Note that $25$, $50$, $75$, and so on still owe money.  So the taxperson collects $1$ dollar from every number that still owes money. These are the multiples of $25$, and there are
$$\left\lfloor \frac{888}{5^2}\right\rfloor$$
of them. But the multiples of $125$ still owe money. So the taxperson collects $1$ dollar from each multiple of $5^3$. There are
$$\left\lfloor \frac{888}{5^3}\right\rfloor$$
of them. Finally, $1$ dollar is collected from the lone number which still owes money. The number of dollars collected in this final stage is
$$\left\lfloor \frac{888}{5^4}\right\rfloor.$$
Now everybody has paid up. The total amount collected is
$$ \left\lfloor \frac{888}{5^1}\right\rfloor+\left\lfloor \frac{888}{5^2}\right\rfloor +\left\lfloor \frac{888}{5^2}\right\rfloor+\left\lfloor \frac{888}{5^4}\right\rfloor.$$
Precisely the same idea works for every positive integer $n$, and every prime $p$.
Comment: This explanation also made my night. How entertaining.
Comment: @Josh: I came up with this version when dealing with "contest kids." In North American society at least, even relatively young people have a sophisticated understanding of money.
Answer: Here is a concise way of expressing the argument. In the equalities below, $j$ and $k$ are positive integers, and $k$ does not exceed $n$. Denoting by $e$ the integer we want to compute, we have
$$
e
=\sum_{j\ge1,\,p^j|n!}1
=\sum_{k=1}^n\ \sum_{j\ge1,\,p^j|k}1
=\sum_{j=1}^\infty\ \sum_{1\le k\le n,\,p^j|k}1
=\sum_{j=1}^\infty\ \left\lfloor\frac{n}{p^j}\right\rfloor.
$$
There are four equalities. The justifications of the first and the last ones are the same. The other equalities are obvious. Thus, it suffices to convince yourself that the first equality holds. This is very clearly explained in the other answers. (I just wanted to break the reasoning into a small number of elementary steps.)
Comment: The lack of summation indices might be confusing to some.
Comment: @PedroTamaroff - Dear Pedro: Thanks for your comment. I edited.


Is the goal of natural deduction to prove logical equivalence, or an implies statement from the proposition to the conclusion?

Question: When we are using natural deduction as a method of proving a statement, does it prove logical equivalence or rather that the final statement is true if the proposition is true? For example, one could use V-intro with the following example. P (prop) would allow us to deduce ∴P V Q using V-into, but P and ∴P V Q are not logically equivalent. From my understanding, natural deduction allows us to say if our proposition is true, then the conclusion we come to using the laws of natural deduction is also true.
Answer: Your understanding is correct: The existence of a natural deduction derivation $A_1, ... A_n \vdash B$ proves a logical implication: If all premises $A_i$ are true, then the conclusion $B$ is true as well.
The reverse direction does in general not hold. To prove that two propositions $A$ and $B$ are logically equivalent, one has to show a derivation from $A$ to $B$ and a derivation from $B$ to $A$.


How to compute importance sampling?

Question: I am trying implement importance sampling of this integral
$$
\mathfrak{I} = \int\limits_{-\infty }^{\infty }{\sqrt{\left| \frac{\theta }{1-\theta } \right|}}f(\theta )\text{d}\theta
$$
where $f(\theta )\propto {{(1+{{\theta }^{2}}/5)}^{-3}}$ is a t-distribution with df=5.
I already sampled from the above distribution and was told to use samples from 1 and 2 below:

Importance function equal to
$$
0.5\{{{g}_{1}}(\theta )+{{g}_{2}}(\theta )\},
$$
where
$$
{{g}_{1}}(\theta )=\frac{1}{\pi }\frac{1}{1+{{\theta
    }^{2}}}
$$
and
$$
{{g}_{2}}(\theta )=\frac{1}{4\sqrt{\left|1-\theta
    \right| }} \quad\text{on}\quad\space [0,2]
$$
Importance function equal to
$$
g'(\theta)\propto \frac{1}{\sqrt{\left| 1-\theta  \right|}}\exp (-\left| 1-\theta  \right|)
$$

How should I do this?  I have searched around, and vaguely understands concept.  Could someone explain more in detail what I should do?  Seems like I have all the tools I need.
Comment: The first suggestion is wrong:  $g_2$ is not defined on the real line. See Example 3.13 of our book [Monte Carlo Statistical Methods](http://www.amazon.com/gp/product/1441919392?ie=UTF8&tag=chrprobboo-20&linkCode=as2&camp=1789&creative=390957&creativeASIN=1441919392) where this problem is fully processed!
Comment: 1. $\theta\in [0,2]$ still does not work in $\sqrt{1-\theta}$!
Comment: I see, I didn't notice it is a folded gamma. I did this  $$F(x)=\left\{ \begin{array}{*{35}{l}}
   \int\limits_{0}^{1}{\frac{1}{\sqrt{1-x}}\exp \left( -(1-x) \right)dx} & \text{if x}<1  \\
   \int\limits_{1}^{\infty }{\frac{1}{\sqrt{x-1}}\exp \left( -(x-1) \right)}dx & \text{if x}>1  \\
\end{array} \right.$$
$$\int\limits_{0}^{1}{\frac{1}{\sqrt{1-x}}{{e}^{-(1-x)}}}dx=-\int\limits_{1}^{0}{2{{e}^{-{{u}^{2}}}}}=\sqrt{\pi }erf(1)=1.49$$
$$\int\limits_{1}^{\infty }{\frac{1}{\sqrt{x-1}}\exp \left( -(x-1) \right)}dx=\int\limits_{0}^{\infty }{2{{e}^{-{{u}^{2}}}}}du=\sqrt{\pi }=1.77$$
1.49+1.77=3.27
Comment: I've also been reading your other book"Introducing Monte Carlo Methods with R", pretty good examples, I find it very practical for learning.
Comment: @Xi'an: wow, you have keen eyes, I missed out typing $for \theta \in [0,2]$.  Actually, I have a general question, in this formula
$$h(x)=\int{h(x)\frac{f(x)}{g(x)}g(x)dx=E\left[ \frac{h(X)f(X)}{g(X)} \right]}$$
$$\simeq \frac{1}{n}\sum\limits_{j=1}^{n}{\frac{f\left( {{X}_{j}} \right)}{g\left( {{X}_{j}} \right)}h\left( {{X}_{j}} \right)}$$
Where do you find your $h\left( {{x}_{j}} \right)$ ?
Comment: 2. Computing $h(x_j)$ means taking a simulated $x_j$ and applying the function $h$ to this value... What is the problem with this?!
Comment: @Xi'an I am having a hard time applying the formula, what are my h, g, f, functions.  Here's what I think, $$h(x) \text{ is } \sqrt{\left| \frac{\theta }{1-\theta } \right|}$$

$$g(x) \text{ is } \frac{1}{\sqrt{1-\theta }}\exp \left( -(1-\theta ) \right)$$

$$f(x) \text{ is } (1+ \theta^{2}/5)^{-3}$$

Is this correct?  If so, then say, I am using samples from gamma distribution $$g\left( x \right)\propto \frac{1}{\sqrt{\left| 1-x \right|}}\exp \left(-\left| 1-x \right| \right)$$, do I have to find normalizing constant?
Comment: Note that $g$ is a _folded_ gamma distribution: this means you simulate $X\sim G(1/2,1)$ and then derive $Y=1\pm X$, the sign being chosen uniformly, i.e. with probability $1/2$. Therefore the normalisation constant is simply $1/$ of the usual $G(1/2,1)$ density, $1/\Gamma(1/2)$.
Comment: Two things: (a) the first integral should be from $-\infty$ to $0$, in relation to the initial problem (b) the function $F(x)$ does not depend on $x$ since $x$ is integrated out (use two constants $C_1$ and $C_2$ instead).
Comment: Could you let us know where you are stuck on our explanation in Example 3.13 of our book [Monte Carlo Statistical Methods](http://www.amazon.com/gp/product/1441919392?ie=UTF8&tag=chrprobboo-20&linkCode=as2&camp=1789&creative=390957&creativeASIN=1441919392)?
Comment: I just got a hold of your book today (thanks for the examples, Christian).  In example 3.13, I was stuck on $h_{1}(x)$, $h_{2}(x)$, $h_{3}(x)$.  I haven't read through from the beginning, maybe you mentioned earlier.
Answer: In case your difficulty is with the simulation per se, here is my R code to compare simulations from $f$ (plain), $g$ equal to
$$
\frac{1}{2} \frac{1}{\pi} \frac{1}{1+x^2} + \frac{1}{2}\frac{1}{4}\frac{\mathbb{I}_{[0,2]}(x)}{\sqrt{|1-x|}}
$$
(mixture of Cauchy and power distributions) and $m$ equal to
$$
\frac{1}{2}\frac{1}{\Gamma(1/2)}\frac{1}{\sqrt{|1-x|}}\exp\{-|1-x|\}
$$
(folded Gamma).
Simulating from $f$ is straightforward
<code>> sam1=matrix(rt(10^6,df=5),ncol=100)
> fam1=h(sam1)
</code>
where
<code>> h
function(x){
sqrt(abs(x/{1-x}))}
</code>
Simulating from $g$ requires simulating from the square-root part. If you integrate out $1/4{\sqrt{|1-x|}}$ over $[0,2]$, you get either $1-\sqrt{1-x}$ over $[0,1]$ or $\sqrt{x-1}$ over $[1,2]$, which means that this distribution can be represented as
$$
1\pm \mathcal{U}(0,1)^2.
$$
(In the following, I force both subsamples to have the same size $5\cdot10^5$, which is a Rao-Blackwellisation trick to reduce the variance with no impact on the expectation.)
<code>> sam22=1+sample(c(-1,1),5*10^5,rep=TRUE)*runif(5*10^5)^2
> sam21=rcauchy(5*10^5)
> sam2=matrix(sample(c(sam21,sam22)),ncol=100)
> fam2=h(sam2)*dt(sam2,df=5)/g(sam2)
</code>
where

g=function(x){.5*dcauchy(x)+.125*((x>0)*(x<2))/sqrt(abs(1-x))}

Simulating from $m$ follows from the folded representation:
<code>> sam3=matrix(1+sample(c(-1,1),10^6,rep=TRUE)*rgamma(10^6,.5),ncol=100)
> fam3=h(sam3)*dt(sam3,df=5)/(.5*dgamma(abs(1-sam3),.5))
</code>
The comparison of the three simulation methods is illustrated in the following boxplot (that we should use in the next edition of Monte Carlo Statistical Methods!)
Comment: Here the definition of `sam3` takes 5 times as many samples as the other tests.  This makes the folded Gamma look better than the Cauchy-power mixture, while the reverse is true.  The folded Gamma estimator has infinite variance, while the Cauchy-power mixture does not.
Comment: The problems with the variance are akin to the game where you win $2^n/n$ dollars with probability $2^{-n}$.  The expected payout may be infinite, but I am not about to sell my house to play.  With the folded gamma there will be large excursions, but they will be extremely rare.  In practice using $\frac{\sum hf/g}{\sum f/g}$ with the folded gamma performs worse, although in theory it has finite variance.
Comment: @Xi'an Sorry to bother you again, but your definition of `h` contain the t distribution, when it should just have the $\sqrt{|x/(1-x)|}$. This causes all the estimates to be off because you are multiplying by f^2 instead of f.  The approximations should be around 1.015, while they are around 0.25.
Comment: I will run this in R, if I got questions, I'll leave a msg, thanks again!
Comment: Indeed, the mixture does better now. About the infinite variance, we noticed this (major) drawback in [the book](http://rads.stackoverflow.com/amzn/click/1441919392). However, it does not seem to impact the practical implementation (in that we do not see strange realisations in the range of the estimates)...

How to compute importance sampling?


Find the max and min values for $f(x,y)=y^2-x^2$ subject to $(1/4)x^2+y^2=1$ using the Lagrange Multiplier

Question: When you solve the system of the derivates, you end up with two different values for the same multiplier as well as $-1/2 = 2$
This is my solution:
$\nabla f(x,y)=\lambda \nabla g(x,y)$ which takes us to the following nonsense system:
$-2x=\lambda (1/2)x$
$2y=\lambda2y$
it gives us $\lambda = 4$ and $\lambda = 1$ and $-0,5=2$
How can this system of equations give me the maximum and minimum points that I'm looking for?
Comment: Not sure what $-0,5=2$ might mean.  But...where is the difficulty?  Your system forces one of $x,y$ to be $0$.  Just check those points.  Otherwise, make the substitution $y^2=1-\frac {x^2}4$ and reduce this to a routine one variable problem.
Comment: In your "nonsens system" you forgot the equation $(1/4)x^2+y^2=1.$
Answer: Apart from solving the system that gets the stationary points of
$$L(x,y,\lambda) = y^2-x^2- \lambda\left(\frac 14 x^2 +y^2-1\right),$$
you must make the argument that $f$ actually attains a max/min on the admissible region, and that these max/min are critical points of the Lagrangian function.
The existence of max/min comes from the fact that $f$ is continuous over the admissible region and that the admissible region (defined by $\frac 14 x^2+y^2=1$) is a compact set.
The fact that all involved functions are differentiable and that the Jacobian matrix of the restriction has maximal rank allows you to conclude that the min/max are attained at  critical points of $L$.
Just solving the system is not a complete answer.

Regarding the solution of the system, you have that
$$ -2x-\lambda \frac x2=0, \quad 2y -2\lambda y = 0,\quad \frac 14 x^2+y^2=1$$
Starting with the first equation, you get $x=0 \vee \lambda = -4$. If $x = 0$, you get $y = \pm 1$. If $\lambda = -4$, you get $y=0$ and then $x = \pm 2$. So, four candidates for min/max: $(0, \pm 1)$ and $(\pm 2, 0)$. Checking the value of the objective function $f$ over these four points, you conclude that the global minimum is attained at $(\pm 2 0)$ and the global maximum is attained at $(0, \pm 1)$.


App won't lauch on Nook, ClassNotFoundException

Question: I've submitted an app to the Nook developers portal.  It runs fine on my rooted nook color and on all the different emulators plus thousands of devices on the play store.  The problem is that when I submit it, it fails to launch on any of their devices.  Below is my manifest and my launch activity which it says it is Caused by: java.lang.ClassNotFoundException: com.bfreq.dice.SplashScreen in loader dalvik.system.PathClassLoader[/data/app/com.bfreq.dice-1.apk]
Is it not finding my main class or is it not finding the class which the SplashScreen loads?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bfreq.dice"
    android:installLocation="auto"
    android:versionCode="11"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="11" />

    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:resizeable="true"
        android:smallScreens="true"
        android:xlargeScreens="true" />

    <meta-data
        android:name="ADMOB_ALLOW_LOCATION_FOR_ADS"
        android:value="true" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".SplashScreen"
            android:label="@string/app_name"
            android:theme="@style/Theme.Sherlock" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ViewPagerMain"
            android:label="@string/app_name"
            android:theme="@style/Theme.Sherlock"
            android:windowSoftInputMode="stateHidden" >
            <intent-filter>
                <action android:name="com.bfreq.dice.VPM" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".CustomDiceHandler"
            android:label="@string/app_name"
            android:windowSoftInputMode="stateHidden|adjustPan" >
            <intent-filter>
                <action android:name="com.bfreq.dice.CDH" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".AdProvider"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Wallpaper"
            android:windowSoftInputMode="stateHidden|adjustPan" >
            <intent-filter>
                <action android:name="com.bfreq.dice.ADP" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.google.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" >
        </activity>
    </application>

</manifest>

Here is my SplashScreen
package com.bfreq.dice;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;

public class SplashScreen extends SherlockActivity {

    AdProvider adTime = new AdProvider();
    DicePreferences prefs = new DicePreferences();
    static int ori = 0;
    static int time = 1000;
    static boolean firstLoad = true;

    Thread splashThread = new Thread() {
        @Override
        public void run() {
            try {
                int waited = 0;
                while (waited < time) {
                    sleep(100);
                    waited += 100;
                }
                Log.d("Hi", "I'm your thread, you should only see me once");
            } catch (InterruptedException e) {
                // do nothing
            } finally {
                Intent intent = new Intent("com.bfreq.dice.VPM");
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                Log.d("Finished", "I just launch your intent, yay!");
                finish();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        ActionBar actionbar = getSupportActionBar();
        actionbar.setTitle("D&D Dice");
        actionbar.setSubtitle("by b.freq");
        actionbar.hide();
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        prefs.loadArrayLists(this);
        prefs.loadStrings(this);
        prefs.loadSettings(this);
        prefs.loadDemo(this);

        if (adTime.getCurrentTime() > ViewPagerMain.endDemo
                && VersionCheck.demo) {
            VersionCheck.demo = false;
            ViewPagerMain.startDemo = 0;
            ViewPagerMain.endDemo = 0;
            prefs.saveDemo(this);
        }
        if (DialogFonts.sizeMain < 10 || DialogFonts.sizeDL < 10) {
            DialogFonts.sizeMain = 20;
            DialogFonts.sizeDL = 15;
            prefs.saveSettings(this);
        }

        // This is for manually changing orientation
        if (firstLoad) {
            prefs.loadOrientation(this);
            ViewPagerMain.ori = ori;
        }
        switch (ViewPagerMain.ori) {
        case 0:
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
            break;
        case 1:
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            break;
        case 2:
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            break;
        }

        setContentView(R.layout.splash);

        // Dumping assets into their sdcard
        try {
            copyStream("CustomSheet - BlankSheet.csv", this);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // This stops hardware keyboard orientation change
        if (((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) < 3)
                & (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)) {
            // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("Orientation not Supported on your device!!!");
            alertDialog.setMessage("Close your KEYBOARD!!!");
            alertDialog.show();
            alertDialog.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    finish();
                }
            });
        } else {
            splashThread.start();
        }

    }

And Finally here is the error log which they sent me.
Files: Rejected: NOOK Color, NOOK Tablet, NOOK HD, NOOK HD+
Your app has failed to launch or crashed. Please see the log that is
attached for more information.
1. Install and boot the app.
Result: The app fails to boot and displays the message " Unfortunately,
D&D Dice by b.freq has stopped."

10-10 12:57:50.670 I/ActivityManager(  958): Starting activity: Intent {
act=android.intent.action.MAIN
dat=content://applications/applications/com.bfreq.dice/com.bfreq.dice.SplashScreen
flg=0x14000000
cmp=com.android.providers.applications/.ApplicationLauncher (has extras)
}

10-10 12:57:50.720 I/ApplicationLauncher( 3546): Launching
ComponentInfo{com.bfreq.dice/com.bfreq.dice.SplashScreen}

10-10 12:57:50.732 I/ActivityManager(  958): Starting activity: Intent {
act=android.intent.action.MAIN flg=0x10200000
cmp=com.bfreq.dice/.SplashScreen }

10-10 12:57:50.763 I/SurfaceFlinger(  958):

10-10 12:57:50.763 I/SurfaceFlinger(  958):
SurfaceFlinger::createSurface() : layer->mIdentity=244, LayerName=
Starting com.bfreq.dice

10-10 12:57:50.763 I/SurfaceFlinger(  958):
SurfaceFlinger::createSurface() : layer->clientIndex=1,
surfaceHandle->mToken=0x1

10-10 12:57:50.826 I/ActivityManager(  958): Start proc com.bfreq.dice
for activity com.bfreq.dice/.SplashScreen: pid=5006 uid=10051
gids={1015, 3003}

10-10 12:57:51.092 D/AndroidRuntime( 5006): Shutting down VM

10-10 12:57:51.092 W/dalvikvm( 5006): threadid=1: thread exiting with
uncaught exception (group=0x4001d888)

10-10 12:57:51.105 E/AndroidRuntime( 5006): FATAL EXCEPTION: main

10-10 12:57:51.105 E/AndroidRuntime( 5006): java.lang.RuntimeException:
Unable to instantiate activity
ComponentInfo{com.bfreq.dice/com.bfreq.dice.SplashScreen}:
java.lang.ClassNotFoundException: com.bfreq.dice.SplashScreen in loader
dalvik.system.PathClassLoader[/data/app/com.bfreq.dice-1.apk]

It continues on for an crazy long time...
Comment: Please read [Android Splash Screens Done Right](http://blog.iangclifton.com/2011/01/01/android-splash-screens-done-right/) by Ian G. Clifton.
Answer: I wouldn't call sleep in my splash screen or any other activity, that piece of code smells. Try changing that. Why not use Handler.postDelayed() Also you might get an ANR if you use sleep for a considerable amount of time.
It's simple, just do the following.
Runnable splashRunnable = new Runnable() {

    @Override
    public void run() {
        Intent intent = new Intent("com.bfreq.dice.VPM");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }
}

And in your onCreate() method:
new Handler().postDelayed(splashRunnable, SPLASH_DELAY);

Now, you are done.
Also remember, try catch blocks shouldn't be used to handle program logic, it should only be used to recover from problems. There could be exceptions sometimes, but this situation is not appropriate.
Comment: So with the post delay and not using Intent filters it pass testing!  So I won't use wait on threads if I can help it.  Thanks for your help!
Comment: Also are you running ICS / JellyBean on your Nook?
Comment: I think the post delay is a good idea but am not really convinced that that is what's causing this. The nook color is running stock rooted so I have to put this in as a system apk which is not how they're installing it. I have tried the nook hd (ics) emulator and that works fine.
Comment: There are several things Google has done to make Android apps responsive. One such example is attempting to perform a network operations on older Android version blocks the UI but JellyBean crashes. So calling sleep on the UI thread could be a performance violation as well. So may be you should give this a try. Also let me try the Thread.sleep() on my Galaxy Nexus.
Comment: Ok I'll try the postDelayed().  I've never used it before so could you throw up some simple code?
Comment: Cool, put that in and it works great.  I also changed how I'm building my intent as it's giving me that class not found exception.  Switched it to:

Intent intent = new Intent(getApplicationContext(), ViewPagerMain.class);

I'm going to try to submit this as today is the last submition day to guarantee getting on in time for the Nook HD.


can one order the elements of a finite group such that their product is equal to the first element in the list?

Question: This question is inspired by this question.
Given a finite group $G$, is there an ordering $G=\{a_1, \dots, a_n\}$ of its elements such that the product of all group elements in that specified order equals the first element, i.e $a_1\cdot\dots\cdot a_n=a_1$. Equivalently, can we multiply all but one element of the group in such a way to obtain the unit $1$.
Trivial cases (probably not very helpful):

$G$ is abelian (just define $a_1$ to be the product of all elements).
$G$ has no element of order $2$ ($a_1=1$ and pair the elements with their inverses in the list).
$G$ has a unique element of order $2$ (set $a_1$ to be that element and pair the others with their inverses).

Slightly less trivial cases (still probably not that useful)

$G=S_3$ (symmetric group) if $a=(12), b=(23)$ are the standard generators, then $(aba)=(aba)(a)(ba)(b)(ab)1$
$G$ with $|G|>6$ has exactly two or three elements of order $2$: Consider the conjugation action of $G$ on the set $X$ of elements of order $2$. If this action is non-trivial, then for at least one $x\in X$ the centralizer of $x$ has at most $\frac{|G|}{2}$ elements, hence we find a $g\in G\setminus X$ with $y:= gxg^{-1}\neq x$; then the product $ygxg^{-1}$ followed by all the elements of order $\geq3$ paired with their inverses is trivial. If the action is trivial, then $X$ lies in the center and is thus an abelian subgroup (because the product of commuting elements of order $2$ has order $\leq 2$); hence we can first multiply all elements of $X$, followed by all other elements paired with their inverses.
Comment: @rwbogl That might work for perfect groups.  But the product of all elements of $G$ is well-defined up to $G'$, so if $G$ has a nontrivial abelianization $G/G'$, then there are elements that won't work as $a_1$.
Comment: If the group is commutative, you can pick $a_1=\prod_{g\in G} g$ (as the product does not depend on the order of multiplication). In the case where there is no element of order two, you can choose $a_1=e_G$ (the neutral element) and order the rest in such a way that you group $g$ and $g^{-1}$ next to each other. I have no idea how to do it in the general case.
Comment: If $G$ is non-abelian, fixing an arbitrary $a_1 \in G$ leaves you with $(n - 1)!$ different ways to choose the remaining terms. Some of the resulting products may repeat, but perhaps "enough" of them do not to sweep out the group itself.
Comment: Note this is equivalent to being able to find a product of all elements is the identity. If $a_1=a_2\cdots a_n$ then $a_1^{-1}=a_n^{-1}\cdots a_2^{-1}$ err nevermind it's all the elements not all but one
Comment: If there are 4 elements of order two, if two of them commute, then their product is another element of order two, and the product of the three elements is trivial.
Comment: On the other hand, let $X=\{h-1,h_2,h_3,h_4\}$. If $e\ne h_1h_2h_3h_4=g\notin X$, then take the product $g\cdot g^{-1} h_1h_2h_3h_4$, followed by the elements of order $\ge 3$.
Comment: If $h_1h_2h_3h_4$ is $h_1$ take $a_1=h_1$. Similarly, if $h_1h_2h_3h_4=h_4$, then $h_4h_3h_2h_1=h_4$ and take $a_1=h_4$. So it suffices to consider $h_1h_2h_3h_4=h_2$ (by symmetry we get the case $h_3$). In that case $h_2h_1h_2=h_3h_4$ is in $X$, and it cannot be $h_1$, since then $h_1$ and $h_2$ commute, it cannot be $h_2$, since then $h_1=h_2$, and it cannot be $h_3$ or $h_4$, since then one of them would be equal to $e$.
Comment: The smallest group not covered by the described cases is the dihedral group of order $8$, with five elements of order $2$. But $(e)(r)(r^2)(r^3)(f)(fr)(fr^2)(fr^3)=e$.
Comment: I have an argument for #X=5 and #X=6.
Comment: I'm trying to generalize it.
Answer: We will prove a bit stronger result: Given an element $x_0$ of order two, we can order the elements in the group such that one of the following cases occur:

The product is trivial, and you can set $a_1=1$.
The product is equal to $x_0$ and the first element is $x_0$.

Proof: Let $X$ be the set of elements of order two and set $$X_0=\{ x\in X\setminus \{x_0\}: \ xx_0=x_0x\}$$ and $$X_1=\{ x\in X: \ xx_0\ne x_0x\}.$$
Then we have the disjoint union
$$ X=\{x_0\}\cup X_0\cup X_1$$
Consider the orbits $\{x,x_0x\}$ in $X_0$ corresponding to (left) multiplication by $x_0$, and the orbits $\{x, x_0 x x_0\}$ in $X_1$ corresponding to the adjunction with $x_0$.
Clearly all orbits have cardinality two.
For each pair of orbits $\{\{x,x_0 x\}, \{ y, x_0 y\}\}$ in $X_0$ consider the product
$$ x\cdot (x_0 x)\cdot y \cdot (x_0 y)= x_0 \cdot x_0=1,$$
and for each orbit $\{ x, x_0 x x_0\}$ in $X_1$ set $g= x_0 x$ (so $g^{-1}=x x_0=x_0(x_0 x x_0)$) and consider the product
$$ g \cdot x \cdot g^{-1}\cdot (x_0 x x_0)= x_0 \cdot x_0=1.$$
Note that the sets $\{ g, g^{-1}\}$ are disjoint, since the orbits are disjoint.
So, if there is an odd number of orbits in $X_0$, set $a_1=1$, then take one orbit $\{ x,x_0 x\}$ in $X_0$, and consider the product $$ x_0 \cdot x \cdot (x_0 x)=1.$$
Then form the product of all elements in $G$ multiplying by the products corresponding to pairs of orbits in $X_0$, then by the products corresponding to orbits in $X_1$, and finally multiplying by pairs $\{ g, g^{-1}\}$ of elements in $G\setminus X$ that have not been used in any of the previous products. Then the product of all elements is trivial.
If there is an even number of orbits in $X_0$, then set $a_1=x_0$ and multiply as before by the remaining elements. Then the product of all the elements is $x_0$, which is the first element.


Can I use rate-limiting with HTTP basic authentication in Apache?

Question: So I'm running a few popular web applications on my server. I want these to be reachable from any computer without creating too many vulnerabilities.
I am using Apache 2.4.29 as my HTTP server. My current idea for hiding potential security vulnerabilities in my applications from attackers is to enable HTTP basic authentication (AuthType Basic) for the relevant virtual hosts as an additional security layer. Of course, I'm only allowing SSL connections.
Now this is all quite easy to accomplish. But my question is this: how can I best avoid brute force style attacks with HTTP basic authentication? I.e., how can I enable rate limiting?
My current plan is something like this:
Since I'm using ufw (Uncomplicated Firewall) to limit SSH connections, I thought I could do the same on a specific port I use for HTTPS. However, I see two problems with this:

Can't an attacker just use Connection: Keep-Alive and keep trying different passwords without even reconnecting? So limiting incoming connections wouldn't be of any use here.
If I disabled Connection: Keep-Alive somehow, I guess I would run into trouble with the underlying web applications, since they would require a lot of individual connections so the browser can retrieve additional files.

It would be perfect if I could instruct Apache to only keep the connection going for authenticated users and drop it for failed attempts. Is there a way to do this? I am actually not sure what is the default behavior and don't understand enough about HTTP to easily test this.
The KeepAlive and MaxKeepAliveRequests settings in Apache can apparently be configured on a per virtual host basis, but I'm not sure how I could change these settings based on a successful authentication.
Comment: Typically a firewall can't distinguish between regular site visitors and people brute forcing a login page. You need either an web application firewall that is protocol aware (such as Apache's mod_security) or use the decoupled approach of for instance fail2ban that scans your log files for malicious events and creates firewall rules to block the offenders
Answer: HTTP basic authentication is done by sending an additional header in the each and every request the client makes, i.e. for each and every resource.
Authorization: Basic <credentials>

If you do not provide this header in a request, you will be prompted to provide credentials.
There is thus no single login page which you can protect by any kind of rate limiting or firewall rules. Rate limiting all pages also is not an option. Should you rate limit each IP address to only one request per second, valid users can only fetch one resource per second. Loading a web page, two style sheets, and four images, would thus take at least seven seconds.


What are the different ways of indicating that a random variable has a specific distribution?

Question: Recently I have seen random variable distributions described in two ways:
$$
X \sim Nb(r,p) \\
X \stackrel{d}{=} Nb(r,p)
$$
Both indicating that $X$ is a negative binomial random variable with $r$ successes and $p$ probability of failure. Do these mean the same things? Are there any other ways of writing this?
Answer: Yes.
Both symbols are commonly used to mean "has a distribution of".
I've encountered "$\sim$" much more often than "$\mathop{=}^d$", possibly because it is more convenient to typeset, but your mileage may vary.
Negative binomial is typically indicated by both-capitalised "NB", or the whole word "Pascal".
I cannot recall any other variations, but it is quite possible they exist.  A good text book should have a glossary of symbols used.
$$X\sim\mathrm{N\!B}(r,p)$$