I want to play sounds after each other but make them wait until the first one is done. How do I do it?

Question: I am currently doing a simple morse code translator and I want my code to play a long beep on '-' and a short beep on '.', and of course this is to be done after one another. But my program is currently playing it all at once. What am I doing wrong?
I have tried adding an onCompletionListener but Netbeans 8.1 gives an error and cant resolve the problem.
    //Play the morse code
public void playButton(ActionEvent event){
    String morse = mcTextField.getText();
    char[] charArray = morse.toCharArray();
    for(int x = 0; x<charArray.length; x++){

        if(charArray[x] == '.'){
            playBeep(shortBeep);
        }
        else if(charArray[x] == '-'){
            playBeep(longBeep);
        }
        else{
            sleep(500);
        }
        sleep(1000);
    }
    }

private void playBeep(String name){
    String musicFile = name;

    Media sound = new Media(new File(musicFile).toURI().toString());
    MediaPlayer mediaPlayer = new MediaPlayer(sound);
    mediaPlayer.play();

    sleep(1000);

}

 private void sleep(int duration){
    try{
        Thread.sleep(duration);
    }catch(Exception e){
        System.out.println("Did not work."+e);
    }
}

Comment: I'd place all the audio files into a `List`, I'd then use `LineListener` to monitor for when the line stops, pop off the next audio and play it, till you run out of audio to play - [This example](https://stackoverflow.com/questions/34758718/panel-fails-to-show-up-concurrently-with-sound-file-in-java-swing/34758778#34758778) demonstrates at least the use of the `LineListener`
Comment: I'd also be VERY weary about using `Thread.sleep` from within the context of any GUIs main thread
Answer: This make use of the Java Sound API, but the basic idea should be feasible for most audio libraries, so long as the provide "end of play back" notification.
All this does is, places the sequence you want to play into a queue, it plays the next tone, wait till it completes and plays the next, until there are no more tones in the queue.
Because AudioClip plays in it's own thread, this uses another Thread to allow the example to "wait for" the sequence to play out fully.  If you're doing this from a UI framework, then you could get away without the additional overhead.
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Test {

    public static void main(String[] args) throws InterruptedException {
        try {
            new Test();
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
            ex.printStackTrace();
        }
    }

    public Test() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
        Sound longBeep = new Sound(new File(...));
        Sound shortBeep = new Sound(new File(...));

        List<Sound> message = new ArrayList<Sound>(9);
        message.add(shortBeep);
        message.add(shortBeep);
        message.add(shortBeep);
        message.add(longBeep);
        message.add(longBeep);
        message.add(longBeep);
        message.add(shortBeep);
        message.add(shortBeep);
        message.add(shortBeep);

        play(message);
    }

    public void play(List<Sound> message) {
        try {
            List<Sound> queue = new ArrayList<>(message);
            Transmit transmit = new Transmit(message);
            Thread thread = new Thread(transmit);
            thread.start();
            transmit.waitFor();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    public class Transmit implements Runnable {

        private List<Sound> queue;
        private ReentrantLock lock;
        private Condition playCondition;

        public Transmit(List<Sound> message) {
            this.queue = new ArrayList<>(message);

            lock = new ReentrantLock();
            playCondition = lock.newCondition();
        }

        @Override
        public void run() {
            playNext();
        }

        public void waitFor() throws InterruptedException {
            lock.lock();
            if (!queue.isEmpty()) {
                try {
                    playCondition.await();
                } finally {
                    lock.unlock();
                }
            } else {
                lock.unlock();
            }
        }

        protected void playNext() {
            if (queue.size() > 0) {
                lock.lock();
                try {
                    System.out.println("Play Next");
                    Sound sound = queue.remove(0);
                    sound.addLineListener(new LineListener() {
                        @Override
                        public void update(LineEvent event) {
                            if (event.getType().equals(LineEvent.Type.STOP)) {
                                sound.removeLineListener(this);
                                System.out.println("Audio Completed");
                                playNext();
                            }
                        }
                    });
                    sound.play();
                } finally {
                    lock.unlock();
                }
            } else {
                lock.lock();
                try {
                    playCondition.signalAll();
                } finally {
                    lock.unlock();
                }
            }
        }

    }

    public class Sound {

        private Clip audio;

        public Sound(AudioInputStream audioInputStream) throws LineUnavailableException, IOException {
            audio = AudioSystem.getClip();
            audio.open(audioInputStream);
        }

        public Sound(File file) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
            this(AudioSystem.getAudioInputStream(file));
        }

        public Sound(URL url) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
            this(AudioSystem.getAudioInputStream(url));
        }

        public Sound(InputStream stream) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
            this(AudioSystem.getAudioInputStream(stream));
        }

        public void close() {
            Objects.requireNonNull(audio, "Audio Clip has not been initalised");
            audio.close();
        }

        public void play() {
            Objects.requireNonNull(audio, "Audio Clip has not been initalised");
            audio.setFramePosition(0);
            audio.start();
        }

        public void addLineListener(LineListener listener) {
            Objects.requireNonNull(audio, "Audio Clip has not been initalised");
            audio.addLineListener(listener);
        }

        public void removeLineListener(LineListener listener) {
            Objects.requireNonNull(audio, "Audio Clip has not been initalised");
            audio.removeLineListener(listener);
        }
    }

}

If you want to know when the sequence completes, without going to trouble of using the waitFor method, you wouldn't be a difficult thing to add an observer into for the Transmit class which generate a "completed sequence" event, but I'll leave that up to you to implement
Comment: for some reason the program can't find the audio file. It says there is no such file in the directory but it is there and it the same directory worked with the old code.
Comment: Well, I tested the code by placing the audio in the current working directory. Try using `File#exists` to check that the file is where you think it is
Comment: It works now! The audio file needs to be in .wav format, .mp3 does not seem to work. Thanks a lot for the help @MadProgrammer


What contributes to extinguishing room fires faster?

Question: When a room is on fire, the quickest way to extinguish the flames (so that it credits the "extinguish fires" objective) is to have the room filled to capacity with non-pregnant dwellers.
Powerful guns + high Perception work to reduce the amount of time that radroaches and mole rats disturb a fully-occupied room.
Given a fully-occupied room on fire, besides maintaining occupancy, are there additional factors which reduce the amount of time it takes to extinguish a room fire?  Perhaps stocking the room with dwellers who have a specific high-value SPECIAL attribute?
Answer: Many people have debated regarding what SPECIAL value affects extinguishing fires.  This inconclusive discussion implies that Intelligence affects the rate a fire is extinguished. Apparently, the only factor that might affect extinguishing fires is the room size. Obviously, smaller rooms are easier and faster to extinguish, especially if it's loaded to capacity with dwellers. Endurance combined with level also helps in these disasters; your dwellers will last longer while putting ones out.
Comment: I've seen intelligence cited a number of places, but never any good evidence. You link one of these places, but then go on to say that the intelligence doesn't affect things. Was that concluded somewhere and I missed it?
Answer: Room level is also a factor I had a maxed out 3 wide living quarters catch fire and it took almost a whole minute to put it out. But disasters in my level 1 3 wide hospital are handle almost instantly. (My dwellers have very strong guns there.) even when I replaced two high intelligence dwellers for two nitwits things were still just as fast.
Answer: In my own experience my fully expanded medical with only 2 dwellers in the room was extinguished much faster than my fully expanded kitchen that had 6 dwellers. I tried to RUSH on making food and failed ending in fire. It took them sooooooo long to put it out. Upon inspection, they are all stupid with almost no intelligence at all, whereas the medical is reliant upon high intelligence. Just my experience.
Answer: A room will continue to be on fire (and the fire will spread to adjoining rooms) for a specific duration then it will die out on it's own once it has spread to another room.
Surprisingly, the room that was totally burned out will automatically return to normal operation once the fire is finally extinguished.
In short, no, there is nothing else you can do to reduce the duration of the fire.
(For reference, I just tested this on my experimental vault.)
Comment: Side note: It does mean however, that an empty room on fire, next to an occupied room, there's no impetus for fighting the fire in the other room. Just wait until it spreads to the occupied room and fight it then.
Comment: Objective: "extinguish # fires" disagrees.
Comment: You don't always have that objective. Just saying that for an end-room that's empty and on-fire, next to a room full of dwellers, it may not be worth moving them all into that room to fight it.
Comment: Edited poor wording again to clarify
Comment: Not sure about whether leaving a fire untended will cause it to be more severe - I've found getting dwellers onto it early will reduce the time required to extinguish, and the health effect on the dwellers. Also, an untended fire will spread to most of the adjoining rooms, leading to more work to extinguish.


Are these fractions all equal?

Question: Are the following expressions all equal to one another?
<code>(2ab+c)/y

(2ab)/y + c/y

(2a)/y * (2b/y) + c/y
</code>
$$\dfrac{2ab+c}{y}=\dfrac{2ab}{y}+\dfrac{c}{y}=\dfrac{2a}{y}×\dfrac{2b}{y}+\dfrac{c}{y}$$
Comment: Change 2b/y to b in the last one, then you're fine
Comment: $$\dfrac{2ab+c}{y}=\dfrac{2ab}{y}+\dfrac{c}{y}=\dfrac{2a}{y}b+\dfrac{c}{y}$$
Comment: If you're having trouble seeing why the 3rd one is different, try putting $a=b=c=y=1$ into each expression. Note: expression, not equation; you haven't written any equations.
Answer: By starting with the first, and applying the distributive law, we get the second: $$\frac{2ab+c}{y} = (2ab+c) \frac{1}{y} = 2ab \frac{1}{y} + c \frac{1}{y} = \frac{2ab}{y} + \frac{c}{y}$$
The last one is not equal to the other two, because
$$\frac{2a}{y} \cdot \frac{2b}{y}  + \frac{c}{y}= \frac{2a\cdot 2b}{y\cdot y} + \frac{c}{y} = \frac{4ab}{y^2} + \frac{c}{y},$$
and $\frac{4ab}{y^2} + \frac{c}{y}$ is (usually) not equal to $\frac{2ab}{y} + \frac{c}{y}$. Notice that we used the fact that
$$\frac{a}{b} \cdot \frac{c}{d} = \frac{ac}{bd}.$$
So the first two are equal, but not the third.
Answer: Eivand's answer is complete - but I want to talk about a related idea. How does one know if something is true?
Often, proving that something is true is incredibly complicated. To prove something false, one needs only a counterexample. But the first step should always be to experiment with the idea. In this case, this probably means making a few fractions of the forms that you have described, and testing to see if they are equal.
After a few tests for the first 2 cases, you might convince yourself that they are true (this does not, of course, constitute a proof!). But the same heuristic approach would quickly destroy the third: suppose we let $a=1 \quad b=2 \quad c=3 \quad y = 5$.
Then $\frac{2a}{y} * \frac{2b}{y} + \frac{c}{y} = \frac{2}{5} * \frac{4}{5} + \frac{3}{5} = \frac{8}{25} = \frac{15}{25} = \frac{23}{25} < 1$.
On the other hand, $\frac{2ab+c}{y} = \frac{4+3}{5} > 1$. Almost any trial would yield a contradiction. I think that this style of patient problem-solving and analysis is under-emphasized and under-utilized, because it provides great insight on many questions.
Reasonable to add?

Are these fractions all equal?


Not to display DataTextField value in GridView

Question: Really silly question but it's really frustrating me.
Inside my gridview I have DataTextField and also a field for Text
<asp:ButtonField DataTextField="hotelId" HeaderText="View Hotel" ButtonType="Button" CommandName="Select" Text="View" />

At the moment when I display results that are binded, the hotelId get replaced with values inside the array. On the front end instead of displaying all those values I just want to display 'View' as suggested in the Text="View".
I've tried everything...
Answer: If you want the text to be View do not provide a DataTextField. It's as simple as that.


svn-externals with own svn-externals: how to recursively checkout?

Question: So I'm using svn:externals to checkout an external repo. The external repo has its own svn-externals set up.
Now, when updating the working copy of my project, the files from the external repo are being updated, but its externals are not. Is that behavior as designed, can it be extended to also update the external dependencies?
Answer: Recursive checkout are supported since Subversion1.5, as this thread illustrates.
The "Version Control with Subversion" book does mention svn checkout, svn update, svn switch, and svn export commands as able to recurse in the externals repos, but:

If an external is set for a particular revision, no amount of 'update' will change any file in it, even though the external repo has had new revisions.
the update must be always initiated from the parent repo, not directly from the sub-repo:

Be careful, though, that you don't inadvertently modify your external working copy in subtle ways that cause problems.
For example, while an externals definition might specify that the external working copy should be held at a particular revision number, if you run svn update directly on the external working copy, Subversion will oblige, and now your external working copy is out of sync with its declaration in the primary working copy.

So maybe one of those two cases applied here.

The OP Carsten reports:

It is actually working now.
I had set the externals prop on the root node of the external project (lets say project 'lib').
In my concrete project (project 'A'), the external was defined on a sub-folder of 'lib' (ie. myLocalFolder > lib/someFolder).
That seems to be the reason for subversion not recursing into lib's externals; only looked inside 'someFolder', didn't find external defs there, so it didn't checkout someFolder/externalLib.
Now, in 'lib' I changed externals definitions so that they are defined inside the folder that I refer to in 'A'; works like a charm now!
Comment: Thanks for the thorough info!
Comment: It is actually working now.

Fyi. I had set the externals prop on the root node of the external project(lets say project 'lib'). In my concrete project(project 'A'), the external was defined on a sub-folder of 'lib'(ie. myLocalFolder > lib/someFolder).
That seems to be the reason for subversion not recursing into lib's externals; only looked inside 'someFolder', didnt find external defs there, so didnt checkout someFolder/externalLib.

Now, in 'lib' I changed externals definitions so that they are defined inside the folder that I refer to in 'A'; works like a charm now!
Comment: @Carsten: excellent :) I have added your conclusion in the answer.


oracle - PLS-00103 & ORA -06550 on procedures

Question: I'm getting the above error while trying to run a simple PL/SQL program that uses procedures. I dont know what went wrong, please help out.
declare
    create or replace procedure palindrome (x in number,y out number) is
    i integer;
    j integer;
    k integer:=0;
begin
    i:=x;
    while i>0
    loop
        j:=mod(i,10);
        k:=k*10+j;
        i:=i/10;
    end loop;
    y:=k;
end;
begin
    x integer:=121;
    y integer;
    palindrome(x,y);
    dbms_output.put_line(y);
end;

/
ERROR at line 2:

ORA-06550: line 2, column 2: PLS-00103: Encountered the symbol
  "CREATE" when expecting one of the following: begin function pragma
  procedure subtype type   current cursor delete exists prior
Answer: Modifications to your code.
  create or replace procedure palindrome (x in number,y out number) is
    i integer;
    j integer;
    k integer:=0;

begin
    i:=x;
    while i>0
    loop
        j:=mod(i,10);
        k:=k*10+j;
        i:=i/10;
    end loop;
    y:=k;
    dbms_output.put_line(y);
end;

/
Execute that procedure
declare
y number;
begin
 palindrome(133,y);
end;

Answer: You only need DECLARE when you're creating an anonymous PL/SQL block that contains variable declarations. When you're creating a named procedure/function/package, then your CREATE OR REPLACE ... statement takes the place of the DECLARE. Anything between that statement and the corresponding BEGIN is known as the declaration section.
It's not especially clear if you're trying to create a named procedure that you can then call with another PL/SQL anonymous block, in which case you'd do:
create or replace procedure palindrome (x in number,y out number) is
    i integer;
    j integer;
    k integer:=0;
begin
    i:=x;
    while i>0
    loop
        j:=mod(i,10);
        k:=k*10+j;
        i:=i/10;
    end loop;
    y:=k;
end;
/

declare
    x integer := 121;
    y integer;
begin
    palindrome(x,y);
    dbms_output.put_line(y);
end;
/

or if you're trying to declare a procedure inside an anonymous PL/SQL, in which case you'd do:
declare
    x integer := 121;
    y integer;

    procedure palindrome (x in number, y out number) is
        i integer;
        j integer;
        k integer := 0;
    begin
        i := x;
        while i > 0
        loop
            j := mod(i,10);
            k := k*10 + j;
            i := i/10;
        end loop;
        y := k;
    end palindrome;
begin
    palindrome(x,y);
    dbms_output.put_line(y);
end;
/

Comment: Not a tutorial, no. But I can suggest the [PL/SQL reference manual](https://docs.oracle.com/cd/E11882_01/appdev.112/e25519/toc.htm) and Steven Feuerstein's book [Oracle PL/SQL Programming](http://www.amazon.co.uk/Oracle-SQL-Programming-Steven-Feuerstein/dp/1449324452/)


Combine two mongoose aggregation pipeline into one where result of first pipeline is used in another pipeline

Question: I have a collection named dummy .
It's schema is defined as -
const schema = mongoose.Schema(
{
    Name: { type: String },
    start: { type: String },
    end: { type: String },
}

Now I want to fetch documents from the collection where end < x .
But here is a catch -

From the document matching above filter I do not want want those document for whose Name we can find another document where start<=x<=end .
And only one document for each Name should be fetched where end is closest to x.

I can achieve this in multiple aggregation pipeline by getting all the Name in namesArr where start<=x<=end in first aggregation pipeline and then using {$nin:namesArr} to remove documents with such names and then group by Name and insert all documents in decreasing sort and select first to get only one document for each bus where end is closest to x in second aggregation pipeline.
Example collection-
{Name : 'a', start :30, end :35},
{Name : 'a', start :40, end :50},
{Name : 'b', start :10, end :25},
{Name : 'b', start :30, end :35},
{Name : 'b', start :60, end :80},

So if x is 44 then the query should return only {Name : 'b', start :30, end :35}
But I want to achieve this in single aggregation pipeline because I do no want to fetch the namesArr first and then pass that in second aggregation pipeline.
So is there any way to achieve this ?
Comment: Normally, I would ask to see what you've already tried, but this question piqued my interest, so I made: https://mongoplayground.net/p/AxDouR8Pxx2
Comment: above aggregate pipeline worked for me and giving the desired result.
Answer: We can achieve the desired behaviour by calculating 4 helper fields.

isInRange: boolean, indicating whether start<=x<=end
diffToX: numeric, indicating the absolute difference of x and end
By grouping of Name field, we get 2 more aggregated helper fields
anyInRange: boolean, by using $max, we check whether any isInRange is in the Name group. If any entry is in range, the final result will be true; otherwise will be false.
rank: int, computed rank by sorting diffToX. Entry with end closest to X should have the highest rank(i.e. smallest rank number)

By using the 4 helper fields, we can get your expected result in following steps:

compute isInRange and diffToX for every documents
compute anyInRange and rank in $setWindowFields with "partitionBy": "$Name" and "sortBy": {"diffToX": 1}
$match with end <= X and anyInRange: false
$sort with rank: 1 and $limit: 1 to get the entry closest to X

db.collection.aggregate([
  {
    $set: {
      isInRange: {
        "$cond": {
          "if": {
            $let: {
              vars: {
                x: 44
              },
              in: {
                $and: [
                  {
                    $lte: [
                      "$start",
                      "$$x"
                    ]
                  },
                  {
                    $gte: [
                      "$end",
                      "$$x"
                    ]
                  }
                ]
              }
            }
          },
          "then": true,
          "else": false
        }
      },
      diffToX: {
        "$abs": {
          "$subtract": [
            "$end",
            44
          ]
        }
      }
    }
  },
  {
    "$setWindowFields": {
      "partitionBy": "$Name",
      "sortBy": {
        "diffToX": 1
      },
      "output": {
        "anyInRange": {
          "$max": "$isInRange"
        },
        "rank": {
          "$rank": {}
        }
      }
    }
  },
  {
    "$match": {
      end: {
        $lt: 44
      },
      anyInRange: false
    }
  },
  {
    $sort: {
      rank: 1
    }
  },
  {
    $limit: 1
  },
  {
    "$unset": [
      "anyInRange",
      "diffToX",
      "isInRange",
      "rank"
    ]
  }
])

Mongo Playground


What's topology of $L^p$ when p is smaller than 1?

Question: For $p>1$ or $p=1$, $L^p(X,\Sigma,m)$ space is a normed vector space with $L^p$ norm. However, when $p<1$, if $f\in L^p$, $$||f||_{L^p}=(\int_X |f|^p dm)^{1/p} $$ fails to be a norm. So my question is whether the collection of sets $B(f,\epsilon)=\{g\in L^p| ||f-g||_{L^p}<\epsilon\}$ for $\epsilon>0$ and any $f\in L^p$ forms a base when $0<p<1$ for some topology?
Comment: @mathworker21: it's a TVS, but not locally convex
Comment: that collection generates a locally convex topological vector space
Comment: @Dap yea, you're right. thanks!
Answer: As already mentioned in the comments, this defines a topological vector space, but not locally convex, as noted in the comments. First note that it is complete and metrizable, namely by
$$d(f,g) = \int_X |f-g|^p \, \mathop{dm},$$
since it satisfies the $\Delta$-inequality,
because $|x-y|^p \leq |x-z|^p + |z-y|^p$ if $0 < p <1$.

One interesting fact is that the continuous dual space $(L^p[a,b])^*$ is trival, i.e. consists only of the zero-functional.

Proof: Let $F \in (L^p[a,b])^*$. Assume that there exists $f \in L^p[a,b]$ with $F(f) \neq 0$. By Rescaling we can assume that $F(f)=1$. Now by continuity of the measure (and since $\lambda$ is non-atomic), we may decompose $[a,b] = \cup_{i=1}^n [a_i,b_i]$ such that $$\int_{a_i}^{b_i} |f|^p \mathop{dx} = \frac{1}{n} \int_0^1 |f|^p \mathop{dx}.$$
Now $$1= F(f) = \sum_{i=1}^n F(1_{[a_i,b_i]} f)$$
Thus, there exists $i=1,\ldots,n$ with
$$\frac{1}{n} \leq F(1_{[a_i,b_i]} f).$$
Define $g_n = n 1_{[a_i,b_i]} f$, then
$$F(g_n) \geq 1,$$
but
$$\int_0^1 |g_n|^p \mathop{dx} = n^{1/p-1} \int_0^1 |f|^p \mathop{dx} \rightarrow 0.$$
A contradction.
More information can be found here.
Comment: It's certainly not locally convex! Indeed, if it were, by Hahn-Banach it'd have lots of functionals, etc.


example to show that an increasing union of finitely generated submodules of some module need not be finitely generated

Question:
Give an example to show that an increasing union of finitely generated submodules of some module need not be finitely generated.

My attempt:
Let $R = \Bbb Z$ .
Consider $M=\Bbb Z \oplus \Bbb Z(\sqrt{2})+\oplus \Bbb Z(\sqrt{3})\oplus \ldots$ and the chain of submodules :$$\Bbb Z \subset \Bbb Z \oplus \Bbb Z(\sqrt{2}) \subset \Bbb Z \oplus \Bbb Z(\sqrt{2}) \oplus \Bbb Z(\sqrt{3}) \subset \dots $$
Each sub-module in the chain is finitely generated but their union (which turns out to be $M$ ) is not!
Please point out mistakes if there are any in my argument.
I have observed that there are a few questions already in the same query but the main reason for posting this question is to see whether my argument is valid or not. So please do not mark it as duplicate.
Comment: For extra fun, why not make all the f.g. submodules cyclic (that is with one generator).
Comment: @LordSharktheUnknown Okay I'll try doing it. But is my answer alright?
Answer: Your answer is correct, though it is more complicated than it needs to be.  You could just let your chain be $\mathbb{Z} \subseteq \mathbb{Z}^2 \subseteq \mathbb{Z}^3 \subseteq \cdots$, where $\mathbb{Z}^n$ is the direct sum of $n$ copies of $\mathbb{Z}$.  (To be really precise here, you should specify how $\mathbb{Z}^n$ is a submodule of $\mathbb{Z}^{n+1}$.)
Or start with, say the polynomial ring $\mathbb{Z}[X]$, viewed as a $\mathbb{Z}$-module, and find an increasing sequence of finitely-generated submodules whose union is $\mathbb{Z}[X]$.


Help with a limit question

Question: The question is: How do we evaluate
$$\lim_{n\rightarrow \infty}\frac{n!n^{x}}{x(x+1)...(x+n)}(Re(x)>0)$$
Any hint will be appreciated.
Comment: https://en.wikipedia.org/wiki/Gamma_function#Euler.27s_definition_as_an_infinite_product
Answer: Let $a_{n}$ be your sequence and set $b_{n}=1/a_{n}$. Apply the ration test for convergence of series and show that |b_{n+1}/b_{n}| converges to 0 as $n$ goes to infinity, and conclude that the series of general term $b_{n}$ is convergent. Thus the general terms of the series, i.e., the sequence $b_{n}$, approaches 0. Form there conclude that your sequence (in absolute value) goes to infinity

Help with a limit question


Android Studio fails to create new project

Question: I'm getting started using Android Studio, and even after reinstalling the entire IDE a couple of times it's still not working right. When I create a new project, it loads with an error saying that the gradle wrapper properties could not load.
Could not load wrapper properties from '...MyApplication2\gradle\wrapper\gradle-wrapper.properties'.

The contents of that file, on the newly created project mind you, are this:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AndroidLayouts">
<shared>
<config />
</shared>
</component>
<component name="AndroidLogFilters">
<

Exactly that, with the unmatched final bracket and all. And when creating a new project, the IDE throws this error message.
java.lang.RuntimeException: java.lang.NullPointerException
    at com.intellij.openapi.application.TransactionGuardImpl.submitTransactionAndWait(TransactionGuardImpl.java:174)
    at com.intellij.openapi.command.WriteCommandAction.execute(WriteCommandAction.java:234)
    at com.intellij.openapi.command.WriteCommandAction$BuilderImpl.compute(WriteCommandAction.java:122)
    at com.android.tools.idea.npw.module.ModuleModel$ModuleTemplateRenderer.render(ModuleModel.kt:125)
    at com.android.tools.idea.npw.model.MultiTemplateRenderer$countDown$2.invoke(MultiTemplateRenderer.kt:139)
    at com.android.tools.idea.npw.model.MultiTemplateRenderer$countDown$2.invoke(MultiTemplateRenderer.kt:42)
    at com.android.tools.idea.npw.model.NewProjectModel$multiTemplateRenderer$1$$special$$inlined$run$lambda$1$1.run(NewProjectModel.kt:124)
    at com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider.disableChecksDuring(NonProjectFileWritingAccessProvider.java:174)
    at com.android.tools.idea.npw.model.NewProjectModel$multiTemplateRenderer$1$$special$$inlined$run$lambda$1.invoke(NewProjectModel.kt:123)
    at com.android.tools.idea.npw.model.NewProjectModel$multiTemplateRenderer$1$$special$$inlined$run$lambda$1.invoke(NewProjectModel.kt:103)
    at com.android.tools.idea.gradle.project.AndroidNewProjectInitializationStartupActivity.runActivity(AndroidNewProjectInitializationStartupActivity.kt:41)
    at com.intellij.ide.startup.impl.StartupManagerImpl.runActivity(StartupManagerImpl.java:216)
    at com.intellij.ide.startup.impl.StartupManagerImpl.lambda$runPostStartupActivitiesFromExtensions$2(StartupManagerImpl.java:168)
    at com.intellij.openapi.extensions.impl.ExtensionPointImpl.processWithPluginDescriptor(ExtensionPointImpl.java:292)
    at com.intellij.openapi.extensions.ExtensionPointName.processWithPluginDescriptor(ExtensionPointName.java:157)
    at com.intellij.ide.startup.impl.StartupManagerImpl.runPostStartupActivitiesFromExtensions(StartupManagerImpl.java:166)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.doLoadProject(ProjectManagerImpl.java:461)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.lambda$loadProjectUnderProgress$8(ProjectManagerImpl.java:440)
    at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:247)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:888)
    at com.intellij.openapi.progress.impl.CoreProgressManager$5.run(CoreProgressManager.java:441)
    at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:163)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:585)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:531)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:59)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:150)
    at com.intellij.openapi.application.impl.ApplicationImpl.lambda$null$4(ApplicationImpl.java:441)
    at com.intellij.util.ConcurrencyUtil.runUnderThreadName(ConcurrencyUtil.java:221)
    at com.intellij.util.ConcurrencyUtil.lambda$underThreadNameRunnable$3(ConcurrencyUtil.java:209)
    at com.intellij.openapi.application.impl.ApplicationImpl$1.run(ApplicationImpl.java:238)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
    at com.intellij.xml.arrangement.XmlArrangementVisitor.createNewEntry(XmlArrangementVisitor.java:100)
    at com.intellij.xml.arrangement.XmlArrangementVisitor.visitXmlTag(XmlArrangementVisitor.java:52)
    at com.intellij.psi.impl.source.xml.XmlTagImpl.accept(XmlTagImpl.java:310)
    at com.intellij.xml.arrangement.XmlArrangementVisitor.visitXmlFile(XmlArrangementVisitor.java:45)
    at com.intellij.psi.impl.source.xml.XmlFileImpl.accept(XmlFileImpl.java:71)
    at com.intellij.xml.arrangement.XmlRearranger.parse(XmlRearranger.java:128)
    at com.intellij.psi.codeStyle.arrangement.engine.ArrangementEngine$Context.from(ArrangementEngine.java:550)
    at com.intellij.psi.codeStyle.arrangement.engine.ArrangementEngine.arrange(ArrangementEngine.java:119)
    at com.intellij.psi.codeStyle.arrangement.engine.ArrangementEngine.arrange(ArrangementEngine.java:83)
    at com.android.tools.idea.templates.TemplateUtils.reformatAndRearrange(TemplateUtils.kt:208)
    at com.android.tools.idea.templates.TemplateUtils.reformatAndRearrange$default(TemplateUtils.kt:184)
    at com.android.tools.idea.templates.TemplateUtils$reformatAndRearrange$1.run(TemplateUtils.kt:154)
    at com.intellij.openapi.command.WriteCommandAction.lambda$runWriteCommandAction$5(WriteCommandAction.java:356)
    at com.intellij.openapi.command.WriteCommandAction$BuilderImpl$1.run(WriteCommandAction.java:110)
    at com.intellij.openapi.application.RunResult.run(RunResult.java:35)
    at com.intellij.openapi.command.WriteCommandAction.lambda$null$1(WriteCommandAction.java:251)
    at com.intellij.openapi.application.impl.ApplicationImpl.runWriteAction(ApplicationImpl.java:885)
    at com.intellij.openapi.command.WriteCommandAction.lambda$performWriteCommandAction$2(WriteCommandAction.java:250)
    at com.intellij.openapi.command.WriteCommandAction.lambda$doExecuteCommand$4(WriteCommandAction.java:308)
    at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(CoreCommandProcessor.java:212)
    at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(CoreCommandProcessor.java:188)
    at com.intellij.openapi.command.WriteCommandAction.doExecuteCommand(WriteCommandAction.java:310)
    at com.intellij.openapi.command.WriteCommandAction.performWriteCommandAction(WriteCommandAction.java:249)
    at com.intellij.openapi.command.WriteCommandAction.execute(WriteCommandAction.java:230)
    at com.intellij.openapi.command.WriteCommandAction$BuilderImpl.run(WriteCommandAction.java:112)
    at com.intellij.openapi.command.WriteCommandAction.runWriteCommandAction(WriteCommandAction.java:356)
    at com.intellij.openapi.command.WriteCommandAction.runWriteCommandAction(WriteCommandAction.java:348)
    at com.android.tools.idea.templates.TemplateUtils.reformatAndRearrange(TemplateUtils.kt:146)
    at com.android.tools.idea.npw.model.NewTemplateRendererKt$render$2.run(NewTemplateRenderer.kt:65)
    at com.intellij.ide.startup.impl.StartupManagerImpl.lambda$runWhenProjectIsInitialized$6(StartupManagerImpl.java:486)
    at com.intellij.ui.GuiUtils.invokeLaterIfNeeded(GuiUtils.java:324)
    at com.intellij.ide.startup.impl.StartupManagerImpl.runWhenProjectIsInitialized(StartupManagerImpl.java:472)
    at com.android.tools.idea.npw.model.NewTemplateRendererKt.render(NewTemplateRenderer.kt:65)
    at com.android.tools.idea.npw.module.ModuleModel$ModuleTemplateRenderer.renderTemplate(ModuleModel.kt:152)
    at com.android.tools.idea.npw.module.ModuleModel$ModuleTemplateRenderer$render$success$1.compute(ModuleModel.kt:126)
    at com.android.tools.idea.npw.module.ModuleModel$ModuleTemplateRenderer$render$success$1.compute(ModuleModel.kt:77)
    at com.intellij.openapi.command.WriteCommandAction$BuilderImpl$2.run(WriteCommandAction.java:120)
    at com.intellij.openapi.application.RunResult.run(RunResult.java:35)
    at com.intellij.openapi.command.WriteCommandAction.lambda$null$1(WriteCommandAction.java:251)
    at com.intellij.openapi.application.impl.ApplicationImpl.runWriteAction(ApplicationImpl.java:885)
    at com.intellij.openapi.command.WriteCommandAction.lambda$performWriteCommandAction$2(WriteCommandAction.java:250)
    at com.intellij.openapi.command.WriteCommandAction.lambda$doExecuteCommand$4(WriteCommandAction.java:308)
    at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(CoreCommandProcessor.java:220)
    at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(CoreCommandProcessor.java:188)
    at com.intellij.openapi.command.WriteCommandAction.doExecuteCommand(WriteCommandAction.java:310)
    at com.intellij.openapi.command.WriteCommandAction.performWriteCommandAction(WriteCommandAction.java:249)
    at com.intellij.openapi.command.WriteCommandAction.lambda$execute$0(WriteCommandAction.java:234)
    at com.intellij.openapi.application.TransactionGuardImpl.lambda$submitTransactionAndWait$2(TransactionGuardImpl.java:162)
    at com.intellij.openapi.application.TransactionGuardImpl.runSyncTransaction(TransactionGuardImpl.java:83)
    at com.intellij.openapi.application.TransactionGuardImpl.lambda$submitTransaction$1(TransactionGuardImpl.java:107)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.doRun(LaterInvocator.java:441)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.runNextEvent(LaterInvocator.java:424)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.run(LaterInvocator.java:407)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764)
    at java.awt.EventQueue.access$500(EventQueue.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:715)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:734)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:908)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:781)
    at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$8(IdeEventQueue.java:424)
    at com.intellij.openapi.progress.impl.CoreProgressManager.computePrioritized(CoreProgressManager.java:687)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:423)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:109)
    at java.awt.WaitDispatchSupport$2.run(WaitDispatchSupport.java:190)
    at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:235)
    at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:233)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.WaitDispatchSupport.enter(WaitDispatchSupport.java:233)
    at java.awt.Dialog.show(Dialog.java:1077)
    at com.intellij.openapi.ui.impl.DialogWrapperPeerImpl$MyDialog.show(DialogWrapperPeerImpl.java:708)
    at com.intellij.openapi.ui.impl.DialogWrapperPeerImpl.show(DialogWrapperPeerImpl.java:433)
    at com.intellij.openapi.ui.DialogWrapper.doShow(DialogWrapper.java:1698)
    at com.intellij.openapi.ui.DialogWrapper.show(DialogWrapper.java:1657)
    at com.intellij.openapi.progress.util.ProgressDialog.show(ProgressDialog.java:270)
    at com.intellij.openapi.progress.util.ProgressWindow.showDialog(ProgressWindow.java:211)
    at com.intellij.openapi.progress.util.ProgressWindow.lambda$null$1(ProgressWindow.java:144)
    at com.intellij.openapi.application.TransactionGuardImpl$2.run(TransactionGuardImpl.java:309)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.doRun(LaterInvocator.java:441)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.runNextEvent(LaterInvocator.java:424)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.run(LaterInvocator.java:407)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764)
    at java.awt.EventQueue.access$500(EventQueue.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:715)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:734)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:908)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:781)
    at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$8(IdeEventQueue.java:424)
    at com.intellij.openapi.progress.impl.CoreProgressManager.computePrioritized(CoreProgressManager.java:698)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:423)
    at com.intellij.ide.IdeEventQueue.pumpEventsForHierarchy(IdeEventQueue.java:965)
    at com.intellij.openapi.progress.util.ProgressWindow.startBlocking(ProgressWindow.java:186)
    at com.intellij.openapi.progress.util.ProgressWindow.startBlocking(ProgressWindow.java:172)
    at com.intellij.openapi.application.impl.ApplicationImpl.runProcessWithProgressSynchronously(ApplicationImpl.java:455)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcessWithProgressSynchronously(CoreProgressManager.java:453)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcessWithProgressSynchronously(ProgressManagerImpl.java:82)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcessWithProgressSynchronously(CoreProgressManager.java:250)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcessWithProgressSynchronously(CoreProgressManager.java:204)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.loadProjectUnderProgress(ProjectManagerImpl.java:439)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.lambda$openProject$5(ProjectManagerImpl.java:415)
    at com.intellij.openapi.application.TransactionGuardImpl.runSyncTransaction(TransactionGuardImpl.java:83)
    at com.intellij.openapi.application.TransactionGuardImpl.submitTransactionAndWait(TransactionGuardImpl.java:149)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.openProject(ProjectManagerImpl.java:414)
    at com.android.tools.idea.npw.model.NewProjectModel$multiTemplateRenderer$1.invoke(NewProjectModel.kt:127)
    at com.android.tools.idea.npw.model.NewProjectModel$multiTemplateRenderer$1.invoke(NewProjectModel.kt:103)
    at com.android.tools.idea.npw.model.MultiTemplateRenderer.countDown(MultiTemplateRenderer.kt:128)
    at com.android.tools.idea.npw.model.MultiTemplateRenderer.skipRender(MultiTemplateRenderer.kt:116)
    at com.android.tools.idea.npw.model.RenderTemplateModel.handleSkipped(RenderTemplateModel.kt:128)
    at com.android.tools.idea.wizard.model.ModelWizard.handleFinished(ModelWizard.java:408)
    at com.android.tools.idea.wizard.model.ModelWizard.goForward(ModelWizard.java:330)
    at com.android.tools.idea.wizard.model.ModelWizardDialog$FinishAction.doAction(ModelWizardDialog.java:313)
    at com.intellij.openapi.ui.DialogWrapper$DialogWrapperAction.actionPerformed(DialogWrapper.java:1834)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6550)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3325)
    at java.awt.Component.processEvent(Component.java:6315)
    at java.awt.Container.processEvent(Container.java:2239)
    at java.awt.Component.dispatchEventImpl(Component.java:4899)
    at java.awt.Container.dispatchEventImpl(Container.java:2297)
    at java.awt.Component.dispatchEvent(Component.java:4721)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
    at java.awt.Container.dispatchEventImpl(Container.java:2283)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4721)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:766)
    at java.awt.EventQueue.access$500(EventQueue.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:715)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
    at java.awt.EventQueue$4.run(EventQueue.java:739)
    at java.awt.EventQueue$4.run(EventQueue.java:737)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:736)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:908)
    at com.intellij.ide.IdeEventQueue.dispatchMouseEvent(IdeEventQueue.java:846)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:778)
    at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$8(IdeEventQueue.java:424)
    at com.intellij.openapi.progress.impl.CoreProgressManager.computePrioritized(CoreProgressManager.java:687)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:423)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:109)
    at java.awt.WaitDispatchSupport$2.run(WaitDispatchSupport.java:190)
    at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:235)
    at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:233)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.WaitDispatchSupport.enter(WaitDispatchSupport.java:233)
    at java.awt.Dialog.show(Dialog.java:1077)
    at com.intellij.openapi.ui.impl.DialogWrapperPeerImpl$MyDialog.show(DialogWrapperPeerImpl.java:708)
    at com.intellij.openapi.ui.impl.DialogWrapperPeerImpl.show(DialogWrapperPeerImpl.java:433)
    at com.intellij.openapi.ui.DialogWrapper.doShow(DialogWrapper.java:1698)
    at com.intellij.openapi.ui.DialogWrapper.show(DialogWrapper.java:1657)
    at com.android.tools.idea.actions.AndroidNewProjectAction.actionPerformed(AndroidNewProjectAction.kt:45)
    at com.intellij.openapi.actionSystem.ex.ActionUtil$1.run(ActionUtil.java:298)
    at com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAware(ActionUtil.java:315)
    at com.intellij.openapi.actionSystem.impl.ActionMenuItem$ActionTransmitter.lambda$actionPerformed$0(ActionMenuItem.java:293)
    at com.intellij.openapi.wm.impl.FocusManagerImpl.runOnOwnContext(FocusManagerImpl.java:263)
    at com.intellij.openapi.wm.impl.IdeFocusManagerImpl.runOnOwnContext(IdeFocusManagerImpl.java:77)
    at com.intellij.openapi.actionSystem.impl.ActionMenuItem$ActionTransmitter.actionPerformed(ActionMenuItem.java:282)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at com.intellij.openapi.actionSystem.impl.ActionMenuItem.lambda$fireActionPerformed$0(ActionMenuItem.java:110)
    at com.intellij.openapi.application.TransactionGuardImpl.runSyncTransaction(TransactionGuardImpl.java:83)
    at com.intellij.openapi.application.TransactionGuardImpl.lambda$submitTransaction$1(TransactionGuardImpl.java:107)
    at com.intellij.openapi.application.TransactionGuardImpl.submitTransaction(TransactionGuardImpl.java:116)
    at com.intellij.openapi.application.TransactionGuard.submitTransaction(TransactionGuard.java:121)
    at com.intellij.openapi.actionSystem.impl.ActionMenuItem.fireActionPerformed(ActionMenuItem.java:110)
    at com.intellij.ui.plaf.beg.BegMenuItemUI.doClick(BegMenuItemUI.java:517)
    at com.intellij.ui.plaf.beg.BegMenuItemUI.access$300(BegMenuItemUI.java:36)
    at com.intellij.ui.plaf.beg.BegMenuItemUI$MyMouseInputHandler.mouseReleased(BegMenuItemUI.java:539)
    at java.awt.Component.processMouseEvent(Component.java:6550)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3325)
    at java.awt.Component.processEvent(Component.java:6315)
    at java.awt.Container.processEvent(Container.java:2239)
    at java.awt.Component.dispatchEventImpl(Component.java:4899)
    at java.awt.Container.dispatchEventImpl(Container.java:2297)
    at java.awt.Component.dispatchEvent(Component.java:4721)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
    at java.awt.Container.dispatchEventImpl(Container.java:2283)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4721)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:766)
    at java.awt.EventQueue.access$500(EventQueue.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:715)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
    at java.awt.EventQueue$4.run(EventQueue.java:739)
    at java.awt.EventQueue$4.run(EventQueue.java:737)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:736)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:908)
    at com.intellij.ide.IdeEventQueue.dispatchMouseEvent(IdeEventQueue.java:846)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:778)
    at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$8(IdeEventQueue.java:424)
    at com.intellij.openapi.progress.impl.CoreProgressManager.computePrioritized(CoreProgressManager.java:698)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:423)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

No activity is created in the new project, and when I go to create a new activity, it doesn't give any error message, but no new activity shows up in the IDE or in the file explorer.
I'm running the latest version of Android Studio. I tried uninstalling everything and reinstalling it. Same problem. I tried installing a different SDK version and it still did this. Any help would be appreciated. Thanks!
Comment: try to reinstall latest version of android studio
Comment: Like I said in the post, I've reinstalled the whole thing 2 or 3 times.
Comment: Now is 2021, and this very same issue still exist. Not only gradle-wrapper.properties have wrong and incomplete content, but several xml file (e.g. activity layout file) is also corrupted. Reinstalling doesn't work, invalidate cache doesn't work.
Answer: I met the same problem as you. I also opened the gradle-wrapper.properties and it seemed broken. So I opened another gradle-wrapper.properties created in my previous project, its content is:
#Fri Jul 31 11:47:56 CST 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip

make sure the gradle version is what you need.
Upd: I found although the build process was successful after editing the file, there was no default activity in directory Java, so I tried uninstalling the whole thing and reinstalling Android Studio in another place. It worked!


MySQL - max in group of results

Question: So maybe my question title is not most relevant but I'm not good in sql and I will need to learn it for sure (So hint for some book would be very useful)
Anyhow I got table which has following (important) columns:
user_id,username,revenue

and records like this:
1,john,39
2,mark,53
3,philipp,7
1,john,17
2,mark,3
2,mark,100

I need to get user who has the biggest revenue, so I need to get all rows, calculate total earnings and print the user who has the biggest revenue in total.
Any hints ;) ?
Comment: Are you missing something in your sample data? Why `user_id` 3 has different username (philipp and mark)?
Comment: sorry typo, usernames are uniqe
Comment: Then update your question. The current answer is fine.
Answer: You can use ORDER BY and LIMIT :
SELECT user_id, username, SUM(revenue) FROM table
GROUP BY user_id /* add ', username' ONLY if two different usernames with the same user_id is a possible case */
ORDER BY SUM(revenue) DESC
LIMIT 0,1

With this, you'll calculate the revenue for each user, you order by decreasing total and get only the first one, so that you have the highest revenue.
Comment: Actually in every other DBMS this query would be rejected with an error because of incorrect usage of the `group by` clause. MySQL does accept it but simply returns random values. See here for an explanation: http://rpbouman.blogspot.de/2007/05/debunking-group-by-myths.html
Comment: @tsabz - I know the problem is in the OP data, so grouping by `user_id` and `username` will not solve the issue either because there are usernames having different ids, So I think group by username and selecting only the username with out id [**like in this**](http://www.sqlfiddle.com/#!2/7bbe4/2) will be fine in this case.
Comment: This will result the user with the id = 3: `philipp` as the max total revenue with total = `107`, apart from it is wrong total, it should be the user `mark` with total revenue = 156.
Comment: Because you'd rather group by name instead of id ? What if two guys have the same name ?
Comment: @MahmoudGamal - Actually there is some error in OP's given data. [See this](http://stackoverflow.com/questions/14581407/mysql-max-in-group-of-results#comment-20351162).
Comment: No this is in the query you posted, and this is happenning because you are grouped by the user_id and selecting the username which is different for the same userid.
Comment: And yes, I think the last line should have "philipp" as username.
Comment: I see your point @MahmoudGamal, I added something in my answer to cover this case then.
Comment: In this situation I agree with @Mahmoud Gamal, because id and names does not match so it is better to go with username.

MySQL - max in group of results


Error 1300 while submitting UWP app to Windows Store

Question: Since I've upgraded to Visual Studio 2015 Update 3, every new submission to Windows Store generates an error code 1300 as such:

The submission failed with error code(s) 1300. More info about the error(s) can be found here.

I've never experienced this kind of error with older updates of Visual Studio.
I've tried several submissions but it fails constantly.
I can't upgrade my app anymore, does anyone experience the same issue?
Answer: I've found a workaround.
It seems there's an issue at this time with NuGet package Microsoft.NETCore.UniversalWindowsPlatform 5.2.0
I've downgraded from 5.2.0 to 5.1.0 for each project of my solution, which has solved my issue.
Comment: They now have an upgrade from 5.2. I upgraded and got past the error


on applying toBeA() method on expect().toBe() it gives an error that cann't read the property of undefined

Question: I am applying toBeA() method on expect() and it gives the error TypeError: Cannot read property 'toBeA' of undefined how can I apply these methods by chaining.
utils.test.js code
const expect = require('expect');
const utils = require('./utils');

it('should add two numbers',() => {
  var res = utils.add(44,11);
  expect(res).toBe(55).toBeA('number');  ----> here it gives the above error.

});
it('Object should be equal',() => {

  expect([1,2,5,7]).toInclude(5); ---> here it gives the error TypeError: expect(...).toInclude is not a function
});

utils.js code
module.exports.add = (a, b) => a + b ;

How do I fix this issue ?
Comment: Which version of `expect` are you using?
Comment: I am using the latest version 23.4.0
Answer: The expect package API has changed since Jest took ownership and they renamed some of the methods.
If you check the code of the expect package you will find out the toBeA and toInclude methods are not available anymore.
You can change your implementation with these methods that are available in the v.23.4.0.
it('should add two numbers',() => {
  var res = utils.add(44,11);
  expect(typeof res).toBe('number');
  expect(res).toBe(55);
});

it('Object should be equal',() => {
  expect([1,2,5,7]).toContain(5);
});


What do the Chimpy Cam options do?

Question: In the options for Donkey Kong 64 I can set Chimpy Cam to either Free or Follow. What's the difference between Free and Follow?
Answer: Free means that you can handle the camera manually.
Follow means that the camera will tend to go behind the character.
Comment: What do the camera control buttons do when Follow is selected?
Comment: If I have to guess, you can probably still move the camera and it will then return behind the player. You may test this by yourself if you own the game.

What do the Chimpy Cam options do?


create a backup of database every day using Cron. [putty]

Question: I have this code which created a backup of my database.

pg_dump -U dbadmin -h 127.0.0.1 123telcom -f dbbackup

Now i want to create a backup every night.
Is there a way u can execute this code with crontab?

0 3 * * * pg_dump -U dbadmin -h 127.0.0.1 123telcom -f dbbackup

I'm new to putty so if anyone could help me a little that would be great.
Comment: put the command in a shell script and execute that from cron as you have stated 0 3 * * * (at 3am every day)
Comment: thanks. I made a script which works when I execute it manualy, but when I want to run it like this                                                                                0 3 * * * /home/ruud/backup1.sh it says  -su: 1: command not found. Could u tell me what I'm doing wrong here
Comment: Please move your question to [su]. It's [off-topic](http://stackoverflow.com/help/on-topic) here.
Comment: Did you make it executable?
Comment: @ruud Did you ever get this working?
Comment: @RolfofSaxony yes. I put the file in the wrong directory. I used "crontab -e" and create my crontab there. Thanks for the help!
Answer: I suspect that you have fallen foul of cron's PATH set up.
If you look in /etc/crontab, it will define a PATH for itself and you will probably have a different PATH set up for your login.
Create your script with the first 2 lines:
#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

where the PATH includes whatever is set up in your environment and ensure that the script is executable.
To test what is going on try this script:
#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

echo $PATH >> /home/yourhome/cron.txt

create an entry in /etc/crontab:
* * * * * root /home/yourhome/yourshell.sh

tell cron about the changes by using sudo crontab -e and then just save it and exit (often Ctrl O and Ctrl X if using nano editor) or I think that you can just kill the cron process and it will re-spawn.
Then check the cron.txt file to see what it is using for PATH.
PS Don't forget to remove this script from the crontab afterwards


Kubernetes proxy route traffic to different sub services depending on request path

Question: Very simple and common case, i have 2 pods in cluser:

wordpress blog + mysql
nginx serving static web site

I want to show static web site when user load http://my-site.com and show blog when user will do http://my-site/blog
Without kubernetes I would just use haproxy with rules analysing request path, I don't have so much experience in kubernetes to build it right way.
Should 1 and 2 pods be a services as well?
Answer: One way to accomplish this may be to use an ingress resource. You could make the two services and then point at them from the ingress resource.
Reference: Simple fanout using ingress resources.


How to summarise values according to different values and then aggregate it?

Question: I'm trying to summarise values according to different groups.
Here's my example below.
Is there a way to get the expected result in a more robust way ?
Many thanks in advance !
library(dplyr)

tab1 <- starwars %>%
  slice(1:8) %>%
  group_by(eye_color,sex) %>%
  summarise(value=sum(mass,na.rm = T)) %>%
  ungroup()

tab2 <- tab1 %>%
  group_by(eye_color) %>%
  summarise(pourcentage=round(value/sum(value)*100,1))

# What I want
tibble(
  eye_color = tab1$eye_color,
  sex = tab1$sex,
  value = tab1$value,
  pourcentage = tab2$pourcentage,
)
# A tibble: 6 x 4
  eye_color sex    value pourcentage
  <chr>     <chr>  <dbl>       <dbl>
1 blue      female    75        27.6
2 blue      male     197        72.4
3 brown     female    49       100
4 red       none      64       100
5 yellow    male     136        64.5
6 yellow    none      75        35.5

Answer: summarise by default drops one level of grouping, so you can add a mutate after the first summarise to calculate the percentage.
library(dplyr)

starwars %>%
  slice(1:8) %>%
  group_by(eye_color,sex) %>%
  summarise(value=sum(mass,na.rm = T)) %>%
  mutate(percentage = round(prop.table(value) * 100, 1)) %>%,
  #prop.table is same as value/sum(value)
  #percentage=round(value/sum(value)*100,1)) %>%
  ungroup

#  eye_color sex    value percentage
#  <chr>     <chr>  <dbl>      <dbl>
#1 blue      female    75       27.6
#2 blue      male     197       72.4
#3 brown     female    49      100
#4 red       none      64      100
#5 yellow    male     136       64.5
#6 yellow    none      75       35.5

Comment: Awesome, I didn't know the grouping behaviour of  `summarise`


Classifying space of a category / classifying space of a group

Question: Consider the classifying space of a category as defined in
this post. Consider the case of a group $G$. I can't see something pretty simple, that is that this coincides with the 'standard' classifying space $BG$.
It seems to me that the Nerve of $C$ is the same as the contractible simplicial space $EG$ which covers $BG$: namely, $EG$ is constructed as having as $n-1$-simplices the $n$-uples of $G^n$, and then one quotients by the diagonal action of $G$, obtaining $BG$.
Now it would seem that the classifying space of the category $G$ (one only object, and one morphism for every element of $G$, interpreted as left multiplication) gives $EG$ and not $BG$. Why am I wrong? I suspect that the point comes when constructing the geometric realisation, but when?
Thank you in advance.
Comment: I think you should have $EG$ being the contractible simplicial set with $EG_n=G^{n+1}$.
Answer: Let $E$ be the category with object set $G$. Define $Hom_E(a,b) = \{(k,a,b): ak = b\}$. In other words, there is exactly one morphism between every object, represented by the group element that multiplies the domain to the codomain. Observe that $G$ acts on $E$ via $g \cdot (k,a,b) = (k,ga,gb)$.

The quotient category $E/G$ is exactly the one-object category $\diamond$ associated to the group $G$.
The $G$-action on $E$ is free. Therefore the induced action of $G$ on the classifying space $BE$ is also free. On the other hand, $BE$ is contractible because $E$ has an initial object (it is actually equivalent to a one object category with only the identity map). Thus the quotient $BE/G$ is a model for $K(G,1)$.

Thus $BE/G = B(E/G) = B (\diamond)$ is a $K(G,1)$ (the first equality can be verified looking at individual simplices).


Using Bootstrap's intended form validation styles

Question: I am interested in using the Bootstrap form validation styles documented at http://v4-alpha.getbootstrap.com/components/forms/#validation.
When I paste the exact HTML for this first example on my own site, the colors/styles are off, and the glyphicons are not present (not sure if glyphicons are intended to appear by default in these types of fields, or if that was just specific to the example page). See image below:
Same exact code from Bootstrap site running on my site
As you can see, the danger color on my site isn't even registering at all (both field and checkboxes have default colors instead of red).
Is there something I'm missing here? This seems like such a dumb issue, but I can't find any answers. I have no CSS overriding this, and the example pictured was taken from an otherwise blank HTML doc. I'm using Bootstrap 3.3.6 from their CDN.
Answer: The Bootstrap doc website that you linked is for the alpha version of Bootstrap 4, not 3. Download Bootstrap version 4 or have a look at these v3 docs: Bootstrap - Validation States


What items should I buy from the shop before stealing the bow?

Question: I'm attempting a no death run to unlock that sweet seagull ending, and so after I steal the bow from the shop I never plan to return to it. I could just save up my rupees of course but, well, I'd rather just steal it. In order to get away from my thievery (mostly) consequence free,  I want to hold off on stealing the bow until there's nothing left at the shop but consumable items (i.e. arrows).
I know the shop contains the shovel and at least one heart container. I'm also under the impression that you need to buy the bombs from the shop before they'll start appearing as item drops (but I could be wrong on that). Is there anything else?
What items should I purchase from the shop before stealing the bow?
Comment: FWIW, you can accumulate rupees _very_ quickly in the Rapids Raid (+300 per run no problem), so maybe it's not worth stealing anything at all?
Comment: @BenP. Yeah but I'm a filthy thief.
Answer: From what I saw while playing, theres at least :

a heart piece
a Dampe dungeon block

You might not want to steal the Bow as it's not the most expensive item anymore (the block being 1000ish).
Comment: I forgot about the chamber blocks, but I'm not going for 100% anyways, so I'm not worried about them. More importantly though, is that I'm playing on Hero Mode, during which the shopkeeper is way harder to steal from. The end result is that I just ended up stealing the bow anyways. Once I've finished this current playthrough I should be able to confirm if there's anything aside from what we've already listed.
Comment: The shop now sells several chamber stones, each for 1280 rupees, so you won't be able to 100% the game any more (without dying). I didn't pay massive attention to which chamber stones they were, but I think they tended to be unique ones - fairy fountains, extra boss fights and the like.


Is taking cover important to Scoundrels and Operatives?

Question: I know that to Snipers and Gunslingers, taking cover is extremely important. But, to the other halves of the Agent and Smuggler, Scoundrel and Operative, do they need to use it to be effective?
I have only played as Sniper/Gunslinger, and never as the other types.
Answer: Not really, no.  It doesn't enhance DPS or enable more abilities the way it does for Snipers and Slingers.
Hard cover (automatically rolling into position where the green "ghost" is shown) provides immunity to damage from Ranged attacks.  This is almost completely useless given that it only functions while you're crouched, and to heal or attack you automatically stand up and expose yourself.
Comment: so if I roll the stealth close range stun type, I don't need to take cover (unless I need to get somewhere fast)?
Comment: Right, except that as noted in the other answer you will get a 12m Roll ability that you can use twice in a row that's more preferable than rolling to cover for covering distance.
Answer: Scoundrels and Opertives do not need cover to perform any attacks in their rotation.
Before 3.0 they would use it to make use of explosive probe and snipe(dont know the rep counter names), but due to changes in the game system, snipe no longer requires cover and explosive probe is now sniper/gunslinger only.
Snipe and probe are/were useful because they had 30m range, and range on a melee class is always a benefit.
But now you can snipe without cover.
As for rolling into cover to get somewhere, it can be useful in some situations like pvp.
However this is also a tactic that was used a lot in the early years of the game before operatives got their own roll ability that can be used 2x in a row as gap closer.
You can still use 'roll into cover' when its on cooldown, but you might not always end up where you expected too.
Even as a healer, the ability isn't really a big benefit, operative healers are the most mobile healers.
Placing yourself in cover does not really help you in pvp, you can still be pulled or charged by other classes (unlike snipers who are in cover).
In short; no, you do not need cover as a operative/scoundrel and very few situations will give you a benefit from using it.


Are there more integer solutions to this system of equations?

Question: Let $n>0$ and $b_1,b_2, \dots, b_n,b_{n+1},b_{n+2} >0$ as well as $c_1, \dots, c_n >0$ be positive integers.
We ask that $b_i < c_j$ for $i \in \{1,\dots,n+1\}$ and $j \in \{1, \dots, n\}$.
That is: "every $b_i$ is smaller than every $c_j$."
Find all solutions to the system of equations
$$
\sum_{i=1}^{n+2} b_i^2 - \sum_{i=1}^n c_i^2 = -1,
\quad\quad
\sum_{i=1}^{n+2}b_i-\sum_{i=1}^n c_i = 1.$$
Example:
$n=1$, $b_1=b_2=b_3=1$ and $c_1=2$ is a solution.
For $n=1$ Mathematica says this is the unique solution.
Answer: The only solution is $n=1$, $b_i=1 (i=1,\cdots,3)$, $c_1=2$.
Proof: Suppose there is a solution.  Let $x = \max(b_i,i=1,\cdots,n+2)$. Then:
$$\sum_{i=1}^{n+2}b_i \leq (n+2)x$$
$$\sum_{j=1}^n c_j\geq n(x+1)$$
Hence, using the second equation:
$$1=\sum_{i=1}^{n+2}b_i - \sum_{j=1}^nc_j \leq (n+2)x – n(x+1) = 2x – n$$
So $1 \leq 2x–n$  implying $n \leq 2x-1\quad(A)$.
Also:
$$\sum_{i=1}^{n+2}b_i^2 \leq (n+2)x^2$$
$$\sum_{j=1}^n c_j^2\geq n(x+1)^2$$
Hence, using the first equation:
$$-1=\sum_{i=1}^{n+2}b_i^2 - \sum_{j=1}^n c_j^2 \leq (n+2)x^2-n(x+1)^2 = 2x^2-n(2x+1)$$
So, using (A):
$$-1\leq 2x^2 – (2x-1)(2x+1) = 1-2x^2$$
Since the $b_i$'s and therefore x are positive integers, this implies $x=1$ and therefore, from (A), $n=1$, from which we can infer $b_i=1 (i=1,\cdots,3)$ and $c_1=2$.


Accessing /run/user/xxxx/gvfs

Question: I am trying to read files from the gvfs directory as root user after I start an x server with sudo xinit ./myscript -- :1.
I keep getting permission denied error. I tried allowing other users and allowing root in /etc/fuse.conf, switching to a user with su user. They didn't work. It is a fresh install of Ubuntu 18.04.
Is there a way I can access the mounted devices as root user or can I log in as a user after xinit?
If I exec whoami, I still see root even aftersu user.
#!/bin/sh
su user &

whoami &

cd ../../run/user/1000

ls gvfs

It seems it is not possible to change users from a shell script. It is possible to run commands as another user with -c flag.
So just su user -c /path/to/script.py.
Answer: Alternative to su user -c /path/to/script.py, is to disable auto mounting and use jmtpfs or similar tools to mount the device to another directory.

Accessing /run/user/xxxx/gvfs


Setting x-axis as Year from datetime index of dataframe column using matplotlib

Question: Here's a simplified version of the code which explains what I'm trying to do:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

dates = pd.date_range('20070101',periods=1000)
df = pd.DataFrame(np.random.randn(1000), index = dates, columns =list ('A'))

plt.plot(df['A'])

this results in this graph:

I want to use the Year from the datetime index as the labels for the x axis on this graph, not the number of datapoints/days. I want 2007, 2008, 2009 etc based on the datetime index (as this will vary according to my input data).
I've looked at every help site for this and nothing seems to work, I may be missing something very obvious, which I apologise for, but I can't figure this out.
EDIT
New code to illustrate error:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

dates = pd.date_range('20070101',periods=1000)
df = pd.DataFrame(np.random.randn(1000), columns =list ('A'))
df['date'] = dates

def get_season(row):
    if row['date'].month >= 3 and row['date'].month <= 5:
        return 'spring'
    elif row['date'].month >= 6 and row['date'].month <= 8:
        return 'summer'
    elif row['date'].month >= 9 and row['date'].month <= 11:
        return 'autumn'
    else:
        return 'winter'

df['Season'] = df.apply(get_season, axis=1)
df['Year'] = df['date'].dt.year
df.loc[df['date'].dt.month == 12, 'Year'] += 1
df = df.set_index(['Year', 'Season'], inplace=False)

df.head()

fig,ax = plt.subplots()
df.plot(x_compat=True,ax=ax)

ax.xaxis.set_tick_params(reset=True)
ax.xaxis.set_major_locator(mdates.YearLocator(1))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))

plt.show()

This gives the error:
ValueError: ordinal must be >= 1

This seems to come from the line
ax.xaxis.set_major_locator(mdates.YearLocator(1))

I think it's to do with the multi-index, but don't understand how to plot it with the multi-index.
Answer: You can plot directly from the DataFrame using df.plot
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

dates = pd.date_range('20070101',periods=1000)
df = pd.DataFrame(np.random.randn(1000), index = dates, columns =list ('A'))

df.plot()

plt.show()

EDIT
To just show the year, we need to turn off the default pandas date formatting, by setting x_compat=True.
Then, we can use a DateLocator and DateFormatter from matplotlib.dates to just use the year.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

dates = pd.date_range('20070101',periods=1000)
df = pd.DataFrame(np.random.randn(1000), index = dates, columns =list ('A'))

fig,ax = plt.subplots()
df.plot(x_compat=True,ax=ax)

ax.xaxis.set_tick_params(reset=True)
ax.xaxis.set_major_locator(mdates.YearLocator(1))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))

plt.show()

Comment: Thanks! I used your code, and edit it to fit my needs, which is in MONTH ->>>>>>>>>>> new_hash_per_day_plot.xaxis.set_major_locator(dates.MonthLocator())
new_hash_per_day_plot.xaxis.set_major_formatter(dates.DateFormatter('%m'))
Comment: @tom , In your first plot you are using df.plot(), that automatically set the xlabel in two rows (months and years), I am trying to do that without using df.plot() because I have using plt.subplots(), so do you know how do xlabel in two rows (months/years) using matplotlib.dates ?
Comment: thanks, this works, but the data I'm actually using is indexed by both year and season, and these overlap each other when graphed. Is there a way of only using one aspect of the index (i.e. the year) to label the x axis?
Comment: thanks again, but I'm still hitting an error when it gets to the  `ax.xaxis.set_major_locator(mdates.YearLocator(1))` line. The error says `ValueError: ordinal must be >= 1`. I thought this was because I was plotting only one column from the data frame, but when I create a new dataframe with only one column which I want, then try to plot that, the same error comes up.
Comment: maybe you should create a minimal example that actually reproduces your error?


How to call sql function from mule

Question: I need to call sql function from mule, i need to know the syntax be declared as part of query key
sample sql script:
<code>create or replace type testArray  as table of varchar2(30);

create or replace function getTestArray return testArray   as

  t_data testArray := testArray();   begin

   for i in 1 .. 10 loop
       t_data.extend;
       t_data(t_data.count) := 'entry ' ||  i;
   end loop;
   return t_data;
end;
</code>
i need to call getTestArray function.Please let me know how i need to declare mule query key to call function.
Comment: Can you share your Mule config?
Answer: Both the legacy JDBC transport and the new DB connector support calling stored procedures:

http://www.mulesoft.org/documentation/display/current/JDBC+Transport+Reference#JDBCTransportReference-OutboundStoredProcedureSupport-Basic
http://www.mulesoft.org/documentation/display/current/Database+Connector

How to call sql function from mule


Prove that $\lim_{x \rightarrow \infty, y \rightarrow \infty} F_{XY}(x, y) = 1. $

Question:
Prove that $\lim_{x \rightarrow \infty, y \rightarrow \infty} F_{XY}(x, y) = 1. $

Attempt:
$\lim_{x \rightarrow \infty, y \rightarrow \infty} F_{XY}(x, y) = \lim_{x \rightarrow \infty, y \rightarrow \infty} P(X \leq x, Y \leq y) = P(X \leq \infty, Y \leq \infty) = P(\{R_X\}\cap\{R_Y\}) = P(R_{XY}) = 1. $
Where $R_X$ denotes the range of $X$, $R_Y$ denotes the range of $Y$, and $R_{XY}$ denotes the range of the bivariate r.v. $(X, Y)$.
Official proof:
Since $\{X \leq \infty, Y \leq \infty\} = S$, we have
$$ P(\{X \leq \infty, Y \leq \infty\}) = F_{XY}(\infty, \infty) = P(S) = 1. $$
I want to know if my proof is valid. I think so because, well, suppose it's a univariate problem, then $P(R_X) = P(S) = 1.$ But in the bivariate case, I'm unsure if $R_X \cap R_Y = R_{XY}$. Looks like a Lemma I'd have to prove separately. But I like my proof better than just saying that $\{X \leq \infty, Y \leq \infty\} = S$, because this last equation isn't very clear in my head.
Edit:
Okay, I have already found a counter example to $R_X \cap R_Y = R_{XY}$.
So suppose my attempt is, then
$\lim_{x \rightarrow \infty, y \rightarrow \infty} F_{XY}(x, y) = \lim_{x \rightarrow \infty, y \rightarrow \infty} P(X \leq x, Y \leq y) = P(X \leq \infty, Y \leq \infty) = P(R_{XY}) = 1. $
Comment: Okay, I have already found a counter example to $R_X \cap R_Y = R_{XY}$.
Answer: Something like that
$$
\mathbb{P}(\mathbb{R}^2) = 1 = \int_{\mathbb{R}^2} dF_{X,Y}(x,y)
$$
where
$$
\lim_{(x,y) \to (\infty, \infty) } F_{X,Y}(x,y) = \int_{\mathbb{R}^2} dF_{X,Y}(x,y) = \int \int f_{X,Y}(x,y) dx dy  = 1
$$
Comment: Hmmm, looks good, but it supposes $(X, Y)$ is a continuous bivariate r.v.
Comment: I believe that Lebesgue dominated measure will solve this problem (i.e., the integral may refer to a countable sum as well)
Comment: Well, I'm not familiarized with Lebesgue Integration so I couldn't use that, besides, using Lebesgue integrals on this problem feels like "nuking a bug".
Answer: Take any sequence $(x_n,y_n)\nearrow(\infty,\infty)$. Then
$$
\lim_{n\to\infty}F_{X,Y}(x_n,y_n)=\lim_{n\to\infty}\mathsf{P}(X\le x_n,Y\le y_n)=\mathsf{P}\!\left(\bigcup_{n\ge 1}\{X\le x_n,Y\le y_n\}\right)=1.
$$
Comment: You need to use sequences to justify the second equality (continuity of $P$ from below).
Comment: Also $R_{XY}$ is typically $\mathbb{R}^2$.
Comment: Very clear proof, thank you. I was wondering, though, if my proof is correct (the last line of the OP). Could you please verify?


Am I supposed to have no idea what's going on in the first few hours of play?

Question: I've been playing for a while now, I'm apparently looking for a girl or something, but unless I missed it, there was absolutely no introduction to who I am, or what I am doing, what I'm looking for, where I am, what any of this is.
Have I missed something (perhaps cos I didn't play the earlier bioshock games?)  or am I supposed to have no idea what's going on?
Comment: This will all make sense in hindsight, don't worry.
Comment: A game is making you think and question your morality! What a world we live in! ;)
Comment: I too found the beginning of the game incredibly confusing, but I felt it added to the sense of immersion. I felt almost as confused as I assume I might were I to sit in a dentist chair in a lighthouse that subsequently became a rocket to a city in the clouds. Take a page out of Booker's book - steady on, stay alive, and get the girl.
Comment: It's hard to be immersed when I feel I'm just gunning down innocent people for no reason. I'll stick with it though, the visuals and the looting are fun.
Comment: What makes you feel like you're just gunning down "innocent people"?
Comment: Basically the game starts with me on a boat, I have no idea who I am or what I'm doing, then I end up in this city in the sky, they are gonna stone a couple of people to death so I then decide to just start killing hundreds of people because I don't like their customs, none of whom have done bad to me, they're just doing their job of protecting the people in the city. Then I'm kidnapping one of their citizens for reasons unknown whilst still mowing down loads of them. I feel like *I* am the bad guy, but I just don't know what's going on.
Comment: @SLC, the scene where they're going to stone the interracial couple was supposed to convince you that there's a lot of racism at work in the city.  There's an undercurrent of slavery/mistreatment of workers (the Vox Populi) and Comstock's kind of got some world domination plans which he will elaborate on.  Meanwhile, Elizabeth is held, isolated and experimented on, in a tower prison.  Whether or not you find those things objectionable is subject to your own opinion, but if you don't, you're unlikely to understand the game, I'm afraid.
Comment: Sure, I get that. But that's just normal for the time period. Can't go murdering people because I disagree with them then continue murdering the police who come to stop me with a clear concience though. It's weird how I've only ever experienced this in this game. I guess because I don't feel like a hero trying to save the day? Who knows.
Answer: Bioshock: Infinite starts in medias res.  There are a lot of details of the "hows" and "whys" that will be explained as you play.
From the outset, you should know that the player character is Booker DeWitt, a private detective who has been hired by a pair of rather unusual people to retrieve a rather unusual girl from a rather unusual city.
The game is quite linear, so there's little to no chance that you'll get lost and not be able to figure out what to do next.  Just keep following along, and eventually the plot will start to come into focus.
However, the plot can be relatively difficult to understand, so I won't go so far as to say that eventually things will make sense :)
There is little to no dependency between Bioshock 1/2 and Infinite.  If you haven't played the first two, you might miss out on some understanding of a few late game moments, but it's nothing major.  I believe the "Burial at Sea" DLC is more tightly tied to Bioshock 1, so you might want to play that game first if you plan on playing the DLC.
Comment: Phew, that's ok then. I am finding it hard to really care about the game though, like running through an exploding building to save someone, I have no idea why I'm there, who I'm saving, where I am, why they're a prisoner, why I'm saving them etc. so I don't feel any kind of tension or sense of urgency :(
Comment: @SLC, I added some basic info about who you are and what the job is to the answer, in case that's not clear to you.  If you don't really feel invested now, chances are the plot twists that are coming aren't going to make much sense, unfortunately.  The original Bioshock was famous for its twists, and they tried to "one up" them for the sequel.


What is the maximum number of consecutive sides whose lengths you can choose without uniquely determining the polygon?

Question:
For every $n$-sided equiangular polygon, define $f(n)$ to be the maximum number of consecutive sides whose lengths you can choose without uniquely determining the polygon. Find the last two digits of:$$\sum_{n=3}^{2019} f(n)$$

Can someone verify this ? I think $(n-3)$ works, and I posted it in AOPS, but the guy is saying that it is wrong.
Here's the solution:
Answer : $36$, $f(n)=n-3 $
clearly for any $n , n-2$ doesn't satisfy because then equiangular property fixes the polygon.
For $n=3, 4$ , clearly $f(n)=n-3$ works .
For $n\ge 5$ , consider the following construction , which i took for $n=7$ ,( but one can understand what's the construction) . It's just extending $2$ sides and making a parallel side . So $n-3$ consecutives doesn't fix.

So $n-3$ works .
And answer is  $\frac{2016\cdot 2017}{2}=2033136 \equiv 36 \pmod {100}$

Here's the other guy's solution, which many people are saying it to be true :
Equilateral triangle which is regular, square but we can have a rectangle, pentagon where all it's sides are equal and so on. Then I see a pattern. This was the crucial observation.
In Euclidean Geometry, if we have an equiangular polygon with odd sides then it's all the sides will be equal, i.e it will be a regular polygon. So, we have the regular polygons with side lengths $3,5,\cdots$ and so on. Here, in this case we can choose only one of it's side length and all the side lengths will be automatically chosen since it is an equiangular and hence regular polygon. Therefore, $f(n)=\boxed{1}$, in the case when we have an equiangular polygon with odd sides.
Now, we see what happens when we choose an equiangular polygon with odd sides, so we can choose half of the sides of the polygon(these needs to be consecutive sides). Therefore $f(n)=\frac{n}{2}$ in the case where $n=\text{even}$.
$\text{Sum}=(1+2)+(1+3)+(1+4)+\cdots+(1+1009)+1=510553 $.
Therefore Last two digits of the sum$\boxed{53}$.

Is there a flaw in the solution , I wrote ?
Comment: Your solution is flawless. The other person's claim is clearly wrong as you have shown.
Comment: In the original question, does it include the "consecutive" requirement? If you drop that requirement, for even $n$, it is possible to specify the length of $n-2$ sides without fixing the polygon (fixing the length of all sides except for a pair of parallel sides)
Comment: @achillehui yes it was specified ..
Comment: @SunainaPati okay, then the other guy is wrong.
Answer: Your solution is correct.
You can have an equiangular pentagon that is not regular. Take the regular pentagon and extend any two of its non-adjacent alternate sides. You can now shift the intermediate side parallel to itself such that it remains between the extensions.
You now have an equiangular non-regular pentagon.


Where do the hinge knuckles go on these fold down table legs?

Question: https://youtu.be/e9GSTO-4Txo?t=119 is a This Old House fold down workbench (among other things). The knuckle of the leg hinge (at 1:59) appears to be pointed into the 2x4 of the table top frame. If so, how did they get the hinge to lay flat? I'm talking about the leaf that goes against the table top, and not really the table top, just the frame.
It seems to me they could have used a shim to support part of the hinge; although, I see no evidence. So maybe it's a special hinge, a hinge that's different than what I have?
Comment: It looks like a standard hinge to me.
Comment: It seams pretty clear in the video and any thing Tom Silva does is done correctly.  There is no need to rethink this.
Answer: It appears that the outside edge of the knuckle is flush with the hinge plate attached to the table top, like this (side view):
Comment: Yes, this must be the answer.  I just thought I would get a peak at the other leaf at https://youtu.be/e9GSTO-4Txo?t=331 or https://youtu.be/e9GSTO-4Txo?t=336
Comment: Maybe the leg leaf is in a mortise in the leg.


How to connect a button function to an object property?

Question: This is the simplified code I'm working with. Is there a better way to find the correct bool?
I'm a beginner so I dont understand keyword "this" completely, but is there a way to connect button with a coresponding object maybe with "this" or something simmilar?
arr = [
 {
   name: "obj1",
   bool: false,
 },
   {
   name: "obj2",
   bool: false,
 }
];

function buildButtons() {
  for (var i = 0; i < arr.length; i++) {
    let button = document.createElement("button");
    button.innerHTML = arr[i].name;
    button.onclick = function() {
      // is there a better way to find the correct bool?
      for (i = 0; i < arr.length; i++) {
        if (this.innerHTML === arr[i].name) {
          arr[i].bool = true;
        }
      }
    };

  window.document.body.appendChild(button);
  }
}

buildButtons();

Answer: Your best bet is to change the data structure to a more appropriate one. Rather than having to loop through an array to find the correct name, just use the names as keys in a single object, so you can look them up directly. Altered code follows:
obj = { obj1: false, obj2: false}

function buildButtons() {
  for (let name in obj) {
     let button = document.createElement("button");
     button.innerHTML = name;
     button.onclick = function() {
       obj[name] = true;
     }
    window.document.body.appendChild(button);
  }
}

buildButtons();

Note that I've used let rather than var for the loop variable - this is necessary (in your version too) for the event handler functions to "capture" the correct value of the loop variable. See here for a very thorough explanation of this.


Is it possible to disable view-lossage?

Question: I use M-x term as my primary shell in emacs. However, unlike M-x shell,  view-lossage will still store my keystroke if my password is prompted. After some search, it looks like there is no way to stop view-lossage recording when prompted.
I would like to know, is it possible to disable it completely ? How can I workaround this problem ?
Comment: Hm. I wonder if this isn't an Emacs bug (misfeature). You might try `M-x report-emacs-bug`, to suggest that keys for password input not be remembered for things like `view-lossage`.
Answer: recent-keys is a C function, so it looks like you'll need to re-compile Emacs.
keyboard.c:
#define NUM_RECENT_KEYS (300)

Just change 300 to 0 and you're done.
Comment: Apparently it doesn't prevent them from being recorded, but it partially clears the record with `clear-this-command-keys`.
Comment: It would be useful to figure out how `M-x shell` prevents password keystrokes from being recorded.
Answer: I figure out a way to workaround the problem, using the clear-this-command-keys function mentioned in @Sean's comment.
Basic idea is to "clear recorded keys when key is send" by advising term-send-raw, I call clear-this-command-keys whenever enter is pressed.
(defadvice term-send-raw (after clear-recorded-key activate)
  (if (string= (kbd "RET") (this-command-keys))
      (clear-this-command-keys)))

Comment: I will accept my answer as long as there is no better way to deal with this problem, because I'm expecting workaround that can be used  in emacs, not change the source code.

Is it possible to disable view-lossage?


Gas logs / how open does flue need to be opened

Question: Either vented or non vetoed gas longs. How open does the flue have to be open. I lose a lot of heat the way it is set now Flue is set to wide open. Can I ajust the stop on handle to close it to @ 2 to 3 inches in the open position
Comment: I don't know about the flue for sure, but two comments - gas logs are pretty much for ambiance, not a serious or efficient contribution to heat. Be sure you have functioning carbon monoxide detectors.
Answer: You should be able to dampen the flue as you would with a wood fire to slow burn rate. Bring it down slowly and monitor for smoke intrusion. It doesn't take much to maintain a chimney draft--maybe 25% open.
Do keep a carbon monoxide detector in service as a safety precaution.
Answer: my codes inspection officer told me they have a lock you can put on the flue to hold it open about 1 inch therefore I is vented but you don't lose all your heat up the chimney
Comment: Hello, and welcome to Home Improvement. Thanks for the answer; keep 'em coming. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to contribute here.
Answer: Hmmm thinking, you have a gas burning appliance with a designed flue size to vent the proper exhaust gasses out so nobody gets killed from carbon monoxide poisoning and you are wondering if you can close it down in order to get more heat out of a device meant for looks instead of heating. I think the answer should be exremely simple, if you want to continue living just leave it alone. If you feel the need not to wake up one morning or the same for your wife and children if you have these then by all means play with things you should just leave alone. Those were designed for romantic evenings, with the love of your life summer and winter. Just because it's winter and you want heat from it too, then go out and buy the apporpiate appliance to heat your room don't play with things not designed to be played with
Comment: TL;DR: Keep it open all the way, or die. Your choice.


How can I delete xfce4 if I deleted crouton?

Question: I downloaded xfce on my Chromebook, but my graphics driver isn't updated enough so I cant do a lot of the things I wanted to, and I wasn't successful at updating it so I am currently trying to delete xfce and get kde or some other version, but I deleted crouton, so when I type in the command to delete it, It doesn't work. Is there any way to fix this?
Answer: The beauty of Chromebooks is that you can do a clean reset of the device if you did something wrong to it, and lose nothing.
But from what you have written, I think you are running Crouton rather than a full Linux install - which I would say from experience does not usually result in a very stable computer.
If you wish to use Ubuntu full time on your Chromebook, I recommend installing Ubuntu onto the hard-drive directly.