As a beginner guitarist is it worth learning to play lead guitar early on?

Question: I started to learn how to play guitar a month ago, but being in a busy science program in college I have limited time to practice. I would like to eventually play lead rather than rhythm.
I am using online lessons by Adam St James and I want to know if I have to know chords to play lead.

Is it not enough to practice scales alone?
How well should I know chords?
What should I practice everyday?

Say, if I like to be able to play lead of some of my favorite Metallica tracks? will I need to know the scales and chords that are used?
Please help me, I honestly need it!
Thanks!
Comment: I wouldn't worry much about goals, too -- when you are beginning, that is usually an unknown unknown. So, I still think the best advice is: just learn to play tons of songs. You'll end up learning all the rest in the process, and be more prepared to maybe adapt your goals.
Comment: The solution to this question depends on what your goal for playing guitar is. Do you just want to learn a few lead parts to songs just to be able to play them or would you like to become the lead guitarist in a band?
Answer: Is it not enough to practice scales alone?
If you just want to learn the solos of other players, you don't need any theory, and you don't need to learn any chords. I'm just answering because everyone else it saying that you do. It's not true, a lot of people want to learn guitar because they like the lead guitar parts they hear their favorite artists play. You can play the lead parts of a song without even knowing what the actual notes are, and what key the song is in...
When I started playing, I wasn't interested at all in chords, because I thought that all the interesting bits where in the melody, and that people would rather hear the solo played alone, instead of just the rhythm. Imo, you'll want to learn chords pretty soon even if your main objective is to master lead guitar. If you're not convinced that you should learn chords, than don't. You can play lead without them, but I'm convinced you'll learn them sooner or later. Many lead players rely heavily on arpeggios, and arpeggios are just chords played one note at a time.
How well should I know chords?
Unless you want to be able to improvise or compose your own songs/solos, you do not need to know any chords. You just need to pick up the tablature and practice. The only advantage of knowing chords there, is it helps you memorize arpeggios better. For example instead of remembering the fret positions of the notes A C E G, you just remember that it's an A minor 7 arpeggio.
If your goal is to compose or improvise, learning all the basic concepts of music theory (chords, scales, keys, rhythm...) is very helpful. In fact it's very hard to do anything without having at least a basic understanding of all of these concepts.
What should I practice everyday?
Again, it depends on your goals:
If your goal is just to be able to play you favorite Metallica solos, just practice scales and the actual solos you want to learn. If you're curious about how they work, why they sound nice, or how to make something similar, you probably have to learn all the basic theory (not just the scale) and do some ear training exercises.
Say, if I like to be able to play lead of some of my favorite Metallica tracks? will I need to know the scales and chords that are used?
No, I know a lot of players who have no idea in what key they're playing, or what the chords are ; and yet they play the parts they practice extremely well, and I really enjoy listening to them. However, scales do help a lot because most (if not all) of the notes you'll be playing are going to be part of the scale. So scales help you memorize. Chords won't help you as much in this particular situation, but they can still help you in some areas, like memorizing arpeggios.
My advice: for now, just learn and practice tablature. Learn some of your favorite lead parts. Do just what you feel like doing. Don't worry about chords and theory. In the end this just a hobby, and it's meant to be fun. Why do you want the answers to questions you're not even asking? You're obviously not interested in chords right now. And you also don't need them to learn to play a solo. In the long run, if you're still as enthusiastic and motivated as you are right now, you'll start asking those questions automatically.
Comment: I totally agree with you. Theory, ear training and all that is what makes you a musician. But for a beginner, it's all about seeing results to stay motivated. That's what they're most interested in when they start (at least I was). I tried teaching theory to a beginner once, and it was horrible: it's like I was talking to a brick wall! Theory shouldn't be learnt at the very beginning. Did your parents teach you grammar as a baby? I DO NOT encourage anyone to play TAB all the time. But if that's the way they enjoy it... what the heck!
Comment: I agree with this for the most part as a good way to get into guitar but a lot of Metallica is technical enough where if you don't have any knowledge of scales or practice them regularly it will take twice as long to do what you might want to do. Essentially what I'm trying to say is, there are much more effective ways to learn to play Metallica then actually playing Metallica!
Comment: You enjoy listening to those guys who have no idea what they're playing? That is weird. No, in fact I completely disagree with your advice: going this way will not make you a good guitarist, at least not without other input. It might make you a good guitar _player_, but not a musician. Sure, lots of people only learn by tabulature these days. Many become remarkably proficient in terms of technique. But I haven't met any I much liked to make music with yet. Well, ok, "just for fun"... but what's fun about sitting alone in a room trying to copy a solo by someone who does it yet better anyway?
Answer: There are several ways to learn the guitar. But you probably have more fun learning through songs.
Don't be too worried about practicing scales, chords and other theory stuff, so that you end up playing few songs. Learn tons of songs! Learn songs you love, learn songs you hate, learn songs you like, learn songs you despise. Play them, play with them -- try changing the time, the rhythm.
You'll end up learning chords, melody, rhythm and harmony in the process.
Don't worry if it takes a bit of time until you can do the solos you want to your heart's content. Keep in mind that learning the guitar is something you never stop. The feeling that right now you can't play what you'd like to play accompany many guitarists their whole lives, because you'll always be wanting more.
So, enjoy the ride. =)
Answer: I think you have a classic problem for beginner guitarists. Every guy who started to play the electric guitar is thinking about the right time to learn "rhythm guitar" and "lead guitar".
The issue is that they are not able to see the "big picture" of learning. Ultimately, this is no more a problem when they have a guitar teacher. But for autodidacts, it is, for a long time on their journey.
My view on that : you should ask yourself what you really want to do, and what are the steps necessary to be there. You can ask a few questions to a teacher, your friends, read books about guitar learning. Then, you will see that all these steps or tasks don't have the same priority, or can't be finished at the same order. You will have to order them the right way.
At the end, you will see a few things, like :

There is no guitarist who can play only rhythm parts or lead parts. Even James Hetfield, who is considered as a "rhythm guitarist" is soloing sometimes.
If you want to be a "lead guitarist", that means that you will have to learn easy things to master, more difficult thing later, and that you won't be able to bypass totally the "rhythm" part.
To be there, you need to work on a few songs, a few technical things, a few theory stuff. There is no shortcut, like "I can do this without all the least fun part", only good possible paths
Answer: Every chord is made up of notes in a key - those notes in the key are the notes in a scale. So by learning the scales you are essential setting yourself up for success. With that said I would suggest learning the Essential Guitar Chords first. After you learn the essential chords you will be able to play almost every song on the radio.
Next I suggest practicing your modes. A mode is a variation of a scale and they will be your best friend when it comes to soloing. The modes include:

Ionian, Dorian, Phrygian, Lydian, Mixo-Lydian, Aeolian, Locrian

This image is a great way to visualize and practice the modes:
In order to become a lead guitarist you need to practice these scales everyday. After you understand them and can play through each of them pick a key and practice inside of that key. I also recommend listening to backing tracks (you can find any key and almost any genre of backing tracks on youtube) and soloing along. This can be fun and really help you practice inside a certain key.
Another great tool to help you learn guitar is learn cover songs (like Metallica as you mentioned). You have a plethora of tabs and chord sheets available to you online so go and use it. By learning other materials you will start to get some great ideas of your own.
Learning guitar is not the easiest thing out there and like anything else it takes time and you need to keep practicing daily. If you have the time and money it is not a bad idea to find a local guitar instructor to help you visualize and practice some of the core concepts. Good luck and rock on!
Answer: You should know chords to play lead. To answer the other questions:

You need scales and chords. Playing chords helps dexterity that will help with chords
Know power chords very well. Only way your going to have fun early on playing at this point.
Practice pentatonic scales and power chords.

if you are looking for a quick way to play solos, there aren't any. It takes years to play Metallica solos the way they sound. Try to learn the guitar so you have options to play any form of music and move to what you like without getting frustrated. Learn the basics and you will eventually play technical solos like Metallica.
Comment: Power chords (http://goo.gl/YDQLmK) can be a really good tool to know, but I wouldn't suggest only sticking to power chords. From my experience and other guitar students they have said learning power chords first can get you stuck in a place musically that is hard to get out of. With that said learn power chords, but also learn the essential chords in first position.
Answer: A good way to start is to pick up the tablature for the White Album by the Beatles and the album itself.
The White Album is a good starting point because it contains songs that are relatively simple to play while covering a wide range of styles and techniques. Also it is one of the most influential albums around (some say the song Helter Skelter "invented" heavy metal) and the licks you pick up will prove useful in other contexts. These chord progressions crop up time and again (for example Karma Police by Radiohead uses a similar chord progression to Sexy Sadie).
First: listen to the album a couple of times.
Second: train your ear by playing along on the guitar. pick a song you like and try to play the vocal part or the lead guitar part by ear. the idea is to get a feel for where the notes are on the fretboard rather than 100% accuracy.
Third: play along to the song using the chords and the tab, noting how it compared to your initial impression of what was being played.
Fourth: improvise along to the song, using scales / modes you may have learnt or simply by ear. Get a feel for what sounds good and what does not. Try to write down any passages you discover while improvising that you particularly like using tablature with a view to improving these later.
Repeat and by the time you've worked through the album you should have improved your play quite considerably.
Answer: It would be good to know how to play chords, cos I don't think you'll ever play just solos. Also, knowing how to play chords, will help you play solos.
I would suggest practicing both scales and chords (of the respective scale you are practicing). That would help you get a better idea of the scale and help you play lead.
If you want to play some Metallica songs, get the tab/music sheet/whatever and just start practicing it. Sure, you won't be able to get it right from the first time you play it, but play it over and over again and eventually you'll get it right.
It might help you to start playing it a bit slower than the normal speed(if the song is somewhat speedy - Metallica have some speedy songs).
Also,it would be good to find some beginners' guitar exercises that will help you get used to your guitar, help you with scales,chords etc
Might help you to take a look at these:
Need Help in Starting to Learn Guitars?
Lead Guitar : How much chords should I learn?
Answer: First I'd say that both lead and rhythm are simply part of guitar. Many bands, in both jazz and rock, only have one guitar player. Part of learning guitar is being able to play rhythm when you need to play rhythm and lead when it's time to play lead. Chords feed into understanding of scales and vice versa. Don't listen to the ones saying don't learn theory, even players who "play by ear" know enough theory to get through a solo. They still keep track of what chord they are soloing over, what note they're on, and a few scale patterns that they know can be played over the chord. To train your ear, don't simply listen to individual intervals and chords and try to determine them. Instead look up a simple cadence, record yourself playing the chords you decide on, and play it back on a loop. This sets the sound of the key you are in and lets you keep it in your ear. Then play all the notes in that key one at a time, listening for the unique sound quality that each scale degree has. Then you can figure out any song. Just listen to the bass note of a chord and decide what degree of the major scale it sounds like. If you learn a bit about chord theory that's all you need to determine things by ear. Got a little sidetracked, but seriously if you want to learn lead, play a backing track that goes through a common rock chord progression, find out what scales work over each chord and learn them, then every day improvise over thOse chords. Loop it endlessly and play until you come up with a few lines that you actually like and want to remember, and do it 6 days a week. In a month you'll be impressed with how decent you are at surviving the occasional improvised solo. Dennis Sandole said being able to just improvise a tasteful solo using just a major scale puts you ahead of most musicians. You need some theory, more can revolutionize your playing, but if you are waiting until you know enough theory to be able to solo you'll never get there. When you start soloing, it feels like you're missing something, that's natural and it only goes away by spending time actually improvising and not reading about how to improvIse.
Answer: woaaah take it easy
his been playing a month and people are already shoving scale degrees and modes down his throat?  no way should any beginner guitarist, especially not after a month should be worrying about modes... maybe scales and knowing the scale formula, practising them, but the other theory is too much for a beginner.
Continue learning your basic cords, practise changing between them, look up some easy songs for beginner guitar players.  Don't try anything overly difficult or youll get discouraged.
Don't worry too much about about lead and rhythm guitar at this stage, get your basic down.  Learn the chromatic scale and know your notes on the fretboard.
In order to decide whether you wanna play lead or rhythm you need your basics down first.  Personally i think its best to practise both.  In the long run if you aren't so good with solos (like me) play rhythm more, if your not that great with chords/rhythm, play licks and solos more.  It all depends on what your good at.
Sorry I haven't quite answered it properly because I was so shocked about the fact people are expecting someone playing after a month to learn about modes.  You don't need to know what scales are used in order to play any song if your are not learning them by ear.  Just learn to use tabs :)  Its good to know chords so you don't continually have to look up every chord you do.  However, knowing these things in the long run will make you a better musician and make you able to understand music and how its created better :)
Answer: I'm a guitar teacher, to comprehend the guitar you just need a few things, and master them, these are

Major scale (all positions up and down the neck) and all the modes of the major scale and the pentatonic scale (all positions and it's related modal shapes)
Chord progressions and modal progressions
Harmonizing scales licks and riffs into chords (and arpeggios if you want more options)
Technique
Ear training, transcribing

After that you can start using more advanced scales like the harmonic minor and the melodic minor and their modes.
If you want to be ultra advanced after learning the major scale and it's modes, harmony etc, modal and chord progressions, try mastering every chord on the fretboard..
And never give up
Comment: This is a good answer on what to practice when learning guitar, but doesn't answer the question per se, which asks about the lead guitar
Answer: First of all, you should be aware that even if your goal is to be a lead player, you will probably find yourself playing just as much - if not more - rhythm as lead. The reason: rhythm guitar makes up the majority of a song.
Having said that, you don't have to know all that many chords to play good rhythm in most styles.
Do I have to know chords to play lead?
Strictly speaking: no, but it helps.
Unless you are playing unacompanied solos - like Van Halen's Eruption - you will be playing lead over some kind of harmony - that is: chords. What chords you are playing over determines whether the notes you play sound good or horrible. Now, as long as you are just learning to play other people's music, you don't really have to know why it works - you already know that it does. However, if at some point in time you begin to create your own leads, you will have to deal with the fact that certain notes work with certain harmony and others do not. You can, of course, just settle for trial and error, but there are two dangers down that path:

You will have to discover what works and what doesn't on your own, so be
prepared for a lot of groping around in the dark,
When you discover several ideas that do work, you might find yourself using them all over the place, which runs the risk of having all your leads and solos sounding the same (and thus boring).

Picking up a general knowledge of chords as you go along provides a safeguard against both of these. It will increase your understanding of what you are playing - even if you are just learning other people's songs - and that makes it easier for you to come up with your own ideas that work when you wish to do your own thing.
Is it not enough to practice scales alone?
I would suggest that practicing scales is not that important, overall, even for lead playing.
Why do we practice scales at all? Firstly, to achieve a measure of technical proficiency with single-note melodic lines. Second, to learn the note sequence and basic fingering patterns for a given key. These are important skills, but not in themselves sufficient to create interesting and exciting melodies and leads. Think of it this way: when you learn to write at school you will be practicing your handwriting and spelling just to be able to write something that will be legible to someone else, but a mastery of these two skills is not enough to write an essay or a story. So it is with scales.
In short: practicing scales is only a small part of developing lead technique and style and by no means the most important. I'd go as far as saying you can develop good lead skills without practicing any scales (although I would not suggest this).
How well should I know chords?
You know those chord dictionaries with the weird fingering diagrams and names like F#7b9? Depending on the style you are playing, you can probably ignore 90% of that.
Guitar George may know all the chords, but you probably will only need a small fraction of them and most of the chord shapes you will need will be movable - that is: you'll be using a single fingering which gives you the same type of chord with a different root (C major, D major, E major; A minor, B minor, C minor) depending on which fret you start with. Most of the chords in the dictionary are the same fingerings played in different positions of the fingerboard (the same goes for scales).
In the long run, it is much more important to know at least the basics of chord construction (which notes make up a particular chord) as well as chord relationships (which chords go well together and when) than memorising all the various fingerings.
You will probably want to learn at least the basic open position chords at some point (chords played near the headstock, using open strings), the movable power chord fingerings (since your question suggests you'll be wanting to play metal and rock stuff) and maybe some movable barre chord shapes to complement that.
What should I practice every day?
If you are already following a guitar course, you should stick to it at first and make sure you are really working on all the exercises and drills that it gives you. Every course follows some method and the later, more advanced material assumes you are already comfortable with the skills presented earlier.
What about practice outside the course? Since you are just starting out and don't really have a lot of time to practice, you will probably do best by learning to play some actual music first, before diving into more technical things.
Find some riffs, simple leads and songs that you can begin learning. Take some time to master one and then move on to the next. This will help you stay motivated because you will be playing music, as opposed to going through drills, and it will help you build up a base for more advanced concepts.
The single most important thing: Get a metronome, drum machine or computer equivalent and learn to play along with it. This also means learning note values and rhythm notation, as well as counting while playing.
The metronome is an indispensable tool when learning to play. It will prepare you for playing with other musicians, teach you to play in time - which is an absolute must, whatever it is you are playing - and allows you to pick apart difficult passages by counting them out and playing slowly at first and then gradually increasing the tempo.
Ideally, as you are learning new music you should be looking at what you are playing and thinking about how it relates to other things you already know. You might start noticing patterns about how the music you are playing is put together and see them repeat in different places. Take note of it. If you are following a course, notice how things you have learned show up in the music you are learning on your own.
The goal here is to have an understanding of the music you are playing. With time you should not only be able to play more complex material, but also have an idea of how the elements of the music you play fit together.
Bottom Line
Every guitar player needs solid rhythm skills - even if they are primarily a lead player - because most songs are mostly rhythm accompaniament and the notes in a lead will need to be played with good timining.
Timing is the single most important skill you should be developing when learning to play.
Knowledge of chord fingerings and scale shapes is a lot less important than knowing how the notes in chords and scales work together musically. It is a good idea to gradually gain at least some understanding of how the music you play works - especially if you ever wish to try a hand at writing your own - but, luckily, it is a skill set that can be developed along the way.
Answer: You do need to know chords quite well because lead guitar in most songs will sometimes play a chord and than pick single strings on the chord shape. I play from 12 years and no, you don't need to know scales if you just wanna learn someone else's track like metallica for example. If you wanna make up your own stuff than yes, you will definitely need them. I would suggest even if you just wanna play other people's songs to learn pentatonic scales and arpeggios anyway as they are ALWAYS in guitar solos or being played during the song itself.
IMPORTANT: If you wanna make up your own solos/lead guitar licks you will need to start off with the pentatonic. It will take you a week to start improvising, but years to get your phrasing right.


Nextjs image loades image but not showing

Question: I am using react-responsive-carousel to make carousel, it was working fine but after 4 days its not showing images, when I debug, I see that images are there, but its not showing on screen. Console also is not giving any error.
import Image from "next/image";
import { Carousel } from "react-responsive-carousel";
import "react-responsive-carousel/lib/styles/carousel.min.css";

function Slider() { return (

  <Carousel
    autoPlay
    infiniteLoop
    showStatus="{false}"
    showIndicators="{false}"
    showThumbs="{false}"
    interval="{5000}"
  >

      <Image src={require("../public/Img/banner1.png")} width={1440} height={600} objectFit='cover'
      />

      <Image src={require("../public/Img/banner2.png")} width={1440} height={600} objectFit='cover'
      />

      <Image src={require("../public/Img/banner3.png")} width={1440} height={600} objectFit='cover'
      />

      <Image src={require("../public/Img/banner4.png")} width={1440} height={600} objectFit='cover'
      />

      <Image src={require("../public/Img/banner5.png")} width={1440} height={600} objectFit='cover'
      />

      <Image src={require("../public/Img/banner6.png")} width={1440} height={600} objectFit='cover'
      />

  </Carousel>

); }

export default Slider;

Edits:
When I replaced next Image with img, its showing same error.
Comment: share a working link here....
Comment: The code looks fine. Can you reproduce the issue on different browsers?
Answer: Try to change the path from ../public/Img/banner6.png to /Img/banner6.png.
Comment: Or try to
Comment: its loading image correctly, but not displaying


Can confidence intervals be added?

Question: For example, say we have three coins.  Due to several tests, we have 95% confidence intervals for X (the heads percentage) of each coin.  Coin A is 0-5%, coin B is 1-9%, and coin C is 40-70%.
[For the curious, these CI's were created using inverse binomial CDF, based a small sample of ~30 flips of the coin.  Not surprisingly, we have no clue about the composition of the coin-bag these coins were drawn from.]
Can we say anything about the number of heads we would expect to see if we flipped all three? Or if we chose one coin randomly and flipped it?  Based on the computed CI's alone?  What if we can also use the info that led us to those CI's?
Edit: let me tell you much more about my problem.
We have 50 coins, all of which we suspect are very low probability heads (well under 5%).  We do 30 trials, where each trial consists of flipping all the coins and recording all the results.  The value we seek is a CI on the average number of heads in a trial.
One approach would be to record the 30 "numbers of heads", and do a standard normal approximation.  The problem is that many of these 30 numbers are 0 and 1,
so while we get the correct mean, I fear the resulting CI is way tighter than it has any right to be.
What I would like to do is calculate a CI for each coin, using it's 30 binary outcomes.  I have calculated that for 0 heads out of 30, this leads to a 95% CI of 0-11.5% (with a mean of 0, of course).  I did this by substituting values for P in "cumulative distribution function(1) of binomial distribution n=30 p=P" in Wolfram Alpha until the result was around 0.025.  For 1 heads out of 30, I get a CI of 0-17.2%
Once I have done this, can I add up the CI's in any way?
Answer: There are multiple methods to calculate the binomial confidence intervals, and in case of your small (~30) sample size this may mean notable differences.
Can we say anything about the number of heads we would expect to see if we flipped all three? Assuming that the normal approximation was used and was appropriate to get the three confidence intervals we can go on with the normal approximation: expected number of heads $E=\frac{0+5}{2} + \frac{1+9}{2} + \frac{40+70}{2}$, $CI = E ± ½ \sqrt{(5-0)^2 + (9-1)^2 + (70-40)^2}$, see sum of normally distributed random variables
Or if we chose one coin randomly and flipped it? If randomly meant choosing one of these 3 coins with equal probabilities than we expect ⅓ times the expected value and a CI of $\frac{1}{\sqrt{3}}$ times the width of the result of the previous question.
What if we can also use the info that led us to those CI's? I that info could mean all or some of your assumptions before setting up the experiment, the experimental conditions and the observations. In that case you could formulate the full conditional probability, tell a bit more about the coins, tackle the small sample size better, particularly giving more accurate CIs for the previous questions.
Comment: Thanks for the input!  Unfortunately my data cannot fairly be approximated as normal.  I may have to post another question to discuss my shady binomial confidence intervals, but for now, I just want to combine oracle-given CI's.
Comment: normal approx would be particularly bad for the 0-5% coin
Answer: This is a problem which can be relatively easily solved using a Bayesian approach.  This is one of the "re-using" the original data answers, rather than one which uses the CIs.
Each coin has some long run frequency of heads $\theta_i$ $(i=1,\dots,50)$.  Now you have some partial information about these frequencies, that you suspect them to be below 5%.  Not exactly clear what is meant by this: do you want to test this? or do you have information which says that it should be less than 5%?  And do you think its 5% because of the data, or did you think this before seeing the data?  Given that you have a reasonably large amount of data, this kind of information probably won't make much difference - so I will simply ignore it.
Now there has been no logical connection stated between each coin - so I will not pre-suppose that one exists.  This means in words that knowing the results of one coin doesn't tell you anything about any other coin.
So we start by supposing that the only thing that was known about each coin is that it is possible for each to give heads, and possible for it to give tails (i.e. we assume that if we flipped the coin until we saw both a head and a tail we would not sample forever).  This results in a uniform prior for each:
$$p(\theta_{i}|I)=1$$
(where $I$ simply denotes the "prior information" or assumptions contained in the problem).  Now you will throw each coin $n_{i}=30$ times, and conditional on $\theta_{i}$ the number of heads observed $x_{i}$ will have a binomial sampling distribution
$$(x_{i}|n_{i},\theta_{i},I)\sim Binomial(n_{i},\theta_{i})$$
The posterior distribution for each $\theta_{i}$ will have a beta distribution:
$$(\theta_{i}|x_{i},n_{i},I)\sim Beta(x_{i}+1,n_{i}-x_{i}+1)\implies p(\theta_{i}|x_{i},n_{i},I)= \frac{\theta_{i}^{x_{i}}(1-\theta_{i})^{n_{i}-x_{i}}}{B(x_{i}+1,n_{i}-x_{i}+1)}$$
Where $B(a,b)$ is the beta function.  Note that each posterior has mode (most likely value) equal to the observed proportion $\frac{x_{i}}{n_{i}}$.  Now this is the posterior for each of the $50$ coins is always proper, well behaved, and exact even when the observed fraction is zero (no approximations have been made).  Denote the number of future trials as $m_{i}$ and the unknown number of heads in these trials by $y_{i}$
So if you knew which coin you picked, then you have a posterior predictive for the next result:
$$p(y_{i}|m_{i},x_{i},n_{i},\text{ith coin},I)=\int_{0}^{1}p(y_{i}|m_{i},\theta_{i},I)p(\theta_{i}|x_{i},n_{i},I)d\theta_{i}$$
$$={m_{i} \choose y_{i}}\int_{0}^{1}\theta_{i}^{y_{i}}(1-\theta_{i})^{m_{i}-y_{i}}\frac{\theta_{i}^{x_{i}}(1-\theta_{i})^{n_{i}-x_{i}}}{B(x_{i}+1,n_{i}-x_{i}+1)}d\theta_{i}$$
$$={m_{i} \choose y_{i}}\frac{B(x_{i}+y_{i}+1,m_{i}+n_{i}-x_{i}-y_{i}+1)}{B(x_{i}+1,n_{i}-x_{i}+1)}=\frac{{x_{i}+y_{i} \choose y_{i}}{m_{i}+n_{i}-x_{i}-y_{i} \choose m_{i}-y_{i}}}{{m_{i}+n_{i}+1 \choose m_{i}}}$$
Which looks like a hypergeometric like distribution, but not quite, as the "random variable" $y_{i}$ appears in different places to what you would see in a hypergeometric.  This is called a beta-binomial compound distribution.  Note that it is "parameter free" - it only depends on what is unknown but of interest $y_{i}$ and what is known $m_{i},x_{i},n_{i}$ - no "pluggin in" of any estimate is required - hence this is an exact inference.
What if we chose one coin randomly and flipped it $m$ times?
But if you now don't know which coin is going to be picked, then the answer cannot depend on $i$.  To do this we simply average out, or marginalise out the $i$.  Assuming that you have no reason to suspect any one coin will be preferred in the choice (what is really meant by "randomly" I think), then each is equally likely, and we get:
$$p(y|m,D,I)=\frac{1}{50}\sum_{i=1}^{50}\frac{{x_{i}+y \choose y}{m+n_{i}-x_{i}-y \choose m-y}}{{m+n_{i}+1 \choose m}}$$
Where $D\equiv x_{1},\dots,x_{50},n_{1},\dots,n_{50}$ ("the data") and the $i$ subscript has been dropped from $m,y$ to indicate that the result doesn't depend on $i$ (i.e. doesn't depend on which coin is flipped).  Now this is an exact answer to your problem.  You can calculate a 95% interval for $y$ using this probability distribution, setting $m=30$ (since this is the sample size you used).  This should give you what you are after - in that the frequentist CI is usually phrased in a predictive fashion "if we sampled again what would we likely the true value be covered by the CI 95% of the time" - a CI talks about the future.

Can confidence intervals be added?


How to prove the monotonicity of Softmax when decreasing the weighted inputs?

Question: Softmax function $a^L_j = z^L_j / sum_k(z^L_k)$. When we think about the monotonicity of the Softmax function, $∂a^L_j/∂z^L_k$ is positive if j=k, and negative if j≠k. As a consequence, increasing $z^L_j$ is guaranteed to increase the corresponding output activation $a^L_j$, and will decrease all the other output activations.
My question is, decreasing $z^L_j$ will decrease the corresponding output and will increase all the other output activations. But, $\frac{∂a^L_j}{∂z^L_k}$ is always positive if j=k, and negative if j≠k. So, I'm curious how to prove that decreasing $z^L_j$ will actually decrease the corresponding output when we always have $\frac{∂a^L_j}{∂z^L_k}$ is positive when j=k?
Comment: Isn't this immediately true from the definition of a partial derivative?
Comment: Uh.. can you elaborate on it? da/dz = a - a^2, where 0 <= a <= 1, j=k. I was thinking the partial derivative of a with respect to z's always positive so a was always increasing, regardless if z's decreasing or not.
Comment: A partial derivative is the (instantaneous) rate of change of one variable with respect to another. With a positive partial derivative, you increase $z$ by some amount, you increase $a$ by a corresponding amount. Similarly, if you _decrease_ $z$, then you _decrease_ $a$ by a corresponding amount.
Comment: I see now. Thank you very much. By the way, is there any way to vote up your answer on comment?
Comment: I've turned this into an answer now, so yes.
Answer: (Consolidating my comments into an answer.)
This comes directly from the definition of a partial derivative.
A partial derivative is the (instantaneous) rate of change of one variable with respect to another. With a positive partial derivative, you increase $z$ by some amount, you increase $a$ by a corresponding amount. Similarly, if you decrease $z$, then you decrease $a$ by a corresponding amount.


SQL Server Stored Procedure to Insert 3-Level Hierarchy

Question: Given business objects similar to:
public class MyBase
{
    public int Id { get; set; }
}

public class Parent : MyBase
{
    public List<Child> Children { get; set; }
    // Additional objects with 1:1 relationship
}

public class Child : MyBase
{
    public Parent Parent { get; set; }
    public List<Grandchild> Grandchildren { get; set; }
    // Some other properties
}

public class GrandChild : MyBase
{
    public Child { get; set; }
    // Some other properties including a timestamp
}

I'm trying to replace bulk insert functionality originally written with Entity Framework with ADO.Net and stored procedures due to the poor performance of EF in this scenario.
Not being a DB expert, I first oriented myself with
http://www.sommarskog.se/arrays-in-sql-2008.html
Using that guidance I was able to create a well-performing (relative to EF) stored procedure that inserts a Child along with its List<GrandChild>.
CREATE TYPE tvpInt32List AS TABLE (n int NOT NULL)

CREATE PROCEDURE uspInsertChild @parentId INT, @fk1Id INT, @fk2Id INT,
@listValues tvpInt32List READONLY
AS
DECLARE @id INT

BEGIN TRANSACTION

BEGIN TRY
    INSERT INTO dbo.Children VALUES(@fk2Id, @fk1Id, NULL, 0, 1, NULL, NULL, NULL, NULL, NULL, @fk1Id, @parentId)

    SET @Id = SCOPE_IDENTITY()

    INSERT INTO dbo.Grandchildren SELECT n, '', GETDATE(), @id FROM @listValues

    COMMIT TRANSACTION
END TRY

BEGIN CATCH
    ROLLBACK TRANSACTION
END CATCH

However, I would like to take this a step further and create a stored procedure that accepts data for a Parent object and then creates the associated List<Child>, and the List<GrandChild> for each Child.
I'm conceptually at a loss as to how to approach that in a stored procedure.
What strategy can I use to pass in that type of data structure and process it in the stored procedure?
Comment: [Erland Sommarskog's](http://www.sommarskog.se/arrays-in-sql.html) articles are still very good.  We've had the best performance by passing the object graph as XML.  Table valued parameters are cleaner but slower.
Comment: I like Andromar's suggestion, you could pretty readily grab the Children and Grandchildren as XML using `SELECT` to traverse the hierarchical XML (good article [here](http://blog.bodurov.com/How-to-Traverse-Hierarchical-XML/)) then send the whole mess to a waiting sproc that has an `xml` type input parameter.
Comment: @Andomar: Erland states that XML can be a good deal slower than TVPs.  The import runs for 3 hours now (8 hours with EF), so I would like every performance edge possible (the data will grow significantly over the next 2-3 years, so runtimes will increase).  http://www.sommarskog.se/arrays-in-sql-2005.html#XML
Comment: Oh, and I thought you were looking to optimize web page loading :)  For large amounts of data have a look at [SqlBulkCopy](http://www.4guysfromrolla.com/articles/102109-1.aspx)  That works without a stored procedure and requires admin rights on the target server, but it's blazingly fast
Comment: It seems SqlBulkCopy only works on one table at a time.  http://stackoverflow.com/q/6442035/141172  Though, the accepted answer to that question does point to a possible solution.
Answer: Guess you write the stored procedure, in order to input parent and childs, one of the option would be to send your data in xml, which again could be extracted easily from your parent object and the utilize the power of Store procedure to do your transaction.
Comment: I don't think this covers the question as expained by OP.


Convergence of $\sum _{n=2}^{\infty }\:\frac{1}{n\ln\left(n\right)}$

Question: Is this convergent or not?
$$\sum _{n=2}^{\infty }\:\frac{1}{n\ln\left(n\right)}$$
I tried using the ratio test but the limit is giving me 1, which doesn't help me. I don't think I'm supposed to use the integral test, since we haven't studied it.
Comment: But the integral test? U-sub the ln...so easy...
Comment: @imranfat I specified that I'm not supposed to use it.
Comment: HINT: $$\ln(1)=0$$
Comment: @Dr.SonnhardGraubner That's what I also thought, but I was kind of inclined to believe that the OP made a typo, otherwise this question is not so interesting anymore :)
Comment: @MikhaelM I didn't read well. But....This is just  kind of silly, but obviously not your fault. However, using the integral test, you can see that the series is divergent. Maybe you can use that result to find a different way to "work" towards your answer. Also, would you mind changing the starting value to $n=2$. ?
Comment: @imranfat yup, my bad, starting value is 2. Still trying to look for alternative methods of proving divergence now.
Answer: If you are familiar with Cauchy Condensation Test, the condens series becomes
$$\sum_{n} 2^n \frac{1}{2^n \ln (2^n)}$$
If not, you can use the idea of the test:
$$\frac{1}{2 \ln2 } \geq \frac{1}{2 \ln 2 }  \\
\frac{1}{3 \ln 3 } \geq \frac{1}{4 \ln 2^2 }  \\
\frac{1}{4 \ln 4 } \geq \frac{1}{4 \ln 2^2 }  \\
\frac{1}{5 \ln 5 } \geq \frac{1}{8 \ln 2^3 }  \\
.....\\
\frac{1}{2^n \ln 2^n } \geq \frac{1}{2^n \ln 2^n } $$
By adding you get
$$s_{2^n} \geq \frac{1}{2 \ln 2 } +\frac{1}{2 \ln 2^2 } +...+\frac{1}{2 \ln 2^n }=\frac{1}{2 \ln 2} (1+\frac12+\frac13+...+\frac1n)$$
Answer: Define $x_n$ as :
$$x_n=\frac1{n\log n}\implies 2^nx_{2^n}=\frac{2^n}{2^n\log2^n}=\frac1{\log 2}\frac1n$$
You should be familiar with the condensation test.
Comment: Yup, we did study the condensation test. I'm looking into it now, thank you!
Comment: Glad to be of help !
Answer: People are mentioning the Cauchy Condensation Test, without saying what it is. Assuming you're not familiar with it, as a lot of people are not:
If $x_n>0$ and $x_{n+1}\le x_n$ then $\sum x_n<\infty$ if and only if $\sum_k2^kx_{2^k}<\infty$. Proving this is a good exercise; as has been pointed out, it shows your series diverges.
Comment: Thank you! I was familiar with the condensation test(as in, we did study it) but never actually used it so far.
Comment: It's a Good Thing (and if it's something you've covered it's surely what was intended for this problem). A person should be able to study sums without integrals...
Comment: Of course nobody says what it is, because there is no need to, since it's  always part of a handful of convergence criteria taught to first year undergrads in calculus.. As nobody ever feels the need to expand on $p$-series when they use it to provide bounds, why should there be need for  an explanation in this case?
Comment: Erm, it's _not_ always part of that course. It should be.


Finding 'conditional probability'

Question: Q-) The number of injury claims per month is modelled by a random variable N with:
                 P(N=n)= 1/(n+1)(n+2),where n>=0
Determine the probability of at least 1 claim during a particular month, GIVEN that there have been at most 4 claims during that month
A-) I tried punching in values of n.
So I got the conditional probability as =
   (I/6 +1/12+ 1/20+ 1/30)/(1/3 + 1/6 + 1/12 + 1/20 + 1/30)
But this isn't matching with the given answer. I am not sure what's wrong. If at all it is wrong.
Thanks in advance.
Comment: 'self-study' questions, if this is one, must have the tag saying `self-study`. See https://stats.stackexchange.com/tags/self-study/info
Comment: (Welcome to the site!) It would be also helpful to give a more detailed explanation of what you tried (which conditional probability you are evaluating, where do the numbers come from etc.) as well as the final answer vs. the given answer.  While you edit the tag and the answer, please also change the tag condition-number (presumably you meant conditional probability, condition numbers are something different)
Comment: Oh yes..my bad I will keep that in mind @juho kokkala
Comment: 1/3 is the value when n=0,@whuber
Comment: No I made a mistake ...
Comment: N=0 ..will be 1/2 ..I wrote it 1/3
Comment: My answer matches now..2/5. Sorry.
Comment: Where did "1/3" come from in the denominator?
Answer: $$
P(N=n) = \frac{1}{(n+1)(n+2)}
$$
$$
P(N \neq 0 | N \leq 4) = 1 - P(N=0 | N \leq 4) = 1- \frac{P(N = 0) \cdot P(N \leq4)}{P(N \leq 4)}
$$
$$
P(N \leq 4) = P(N=0, 1, 2, 3, 4) \\
= P(N=0) + P(N=1) + P(N=2) + P(N=3) + P(N=4) \\
$$
You can now solve the rest by yourself, since you know the formula for $P(N=n)$.
Comment: Thank you guys.I figured out my mistake. Wrong value of n=0.
Comment: But @whuber why do you think it will be a good idea find cdf here? It's a discrete random variable. I will have eventually have to work out and add all the values(and x>=0). Or is there a way to find a generalized cdf for a discrete random variable ?
Comment: *Every* random variable has a CDF.  In this case, it takes on a particularly simple form.  By doing that calculation at the outset, you likely would not have made the mistake you did.
Comment: But how would I find the cdf, as in, I have not quite understood how am I supposed to make use of your suggestion. I will have to find the cumulative probability for many values of X. Or you mean I should just first right down the cumulative probabilities till 4? Or can I
 use f(x) to find a generalized cumulative probability function for atleast this particular discrete random variable.
Comment: In the second line you appear to assume the events $N=0$ and $N\le 4$ are independent, but obviously that's not the case.
Comment: I apologize, I have not looked at this material in quite a long time.  Please offer your advice, I would genuinely be interested in knowing how you would approach the question.
Comment: I would apply the formula for conditional probability directly, much as in the question itself.  To simplify the answer I would first work out the CDF, which has a very simple form.

Finding 'conditional probability'


An algebraic topology proof of a result from analysis

Question: A colleague of mine recently brought up the following result from real analysis:
Theorem: If $f:\mathbb{R}^2\to\mathbb{R}^2$ is continuous and $|f(x)-f(y)|\geq |x-y|$ for all $x,y$, then $f$ is onto.
It feels like there should be a slick proof of this result using the fundamental or singular homology groups but I couldn't quite find a way to make it work. Does anyone know of a nice proof using algebraic topology?
Answer: Not sure if that's enough algebraic topology for you:
Since $\lvert f(x) - f(y)\rvert \geqslant \lvert x-y\rvert$, $f$ is injective, and by the invariance of domain ($\leftarrow$ algebraic topology), it is an open map. Hence $f$ is a homeomorphism between $\mathbb{R}^2$ and $U = f(\mathbb{R}^2)$. Let $g \colon U\to \mathbb{R}^2$ be the inverse. Since $g$ is Lipschitz continuous, it has a continuous extension $\hat{g}\colon \overline{U}\to \mathbb{R}^2$. This extension must still be injective: Suppose $x_1\neq x_2$ with $\hat{g}(x_1) = \hat{g}(x_2) = \xi$. There is an $x_0\in U$ with $g(x_0) = \xi$ since $g$ is surjective. Let without loss of generality $x_0 \neq x_1$. Let $V,W$ be disjoint neighbourhoods of $x_0$ resp. $x_1$. Since $g$ is open, $g(V)$ is a neighbourhood of $\xi$, and since $g$ is injective, $g(W\cap U) \cap g(V) = \varnothing$. But that means that $\xi \notin \overline{g(W\cap U)}$, and hence
$$\xi = \hat{g}(x_1) \in \hat{g}(\overline{W\cap U}) \subset \overline{\hat{g}(W\cap U)} = \overline{g(W\cap U)} \subset \mathbb{R}^2\setminus \{\xi\}$$
is a contradiction.
Since the extension $\hat{g}$ of $g$ is still injective, and $g$ is surjective, it follows that $\overline{U} = U$, and since $\mathbb{R}^n$ is connected and $U\neq\varnothing$ it follows that $U = \mathbb{R}^2$.
(Note: the same proof works in all $\mathbb{R}^n$.)
Comment: It does seem like a good idea to call upon invariance of domain (especially for the higher dimensional generalization), however, I was hoping for something a bit more algebraic.


Modify exp conformal map to have evenly spaced vertical lines

Question: I would like to construct a (conformal) map similar to the exp conformal map, but for which the vertical lines in the source space are evenly separated in the target space.
That is, in this simulator: https://www.geogebra.org/m/qCSzkRsP (have to change the function to exp(z)), I would like the red lines to be evenly spaced in the target space.
In the end, what I really want is the inverse transform of that (to be able to "unfold" an 2D object), so it will likely be a modified log conformal map. But I find it easier to imagine it with the exp conformal map first.
Note: I do care about the fact that there is a notch around the origin in the target space.
Answer: There's no such conformal map.
Suppose we had such a map, $f(x, y) = \rho(x, y) e^{i \alpha(x, y)}$. The condition that vertical lines in the domain are mapped to circles centered at the origin is $$\rho_y = 0 ,$$
and given that it is satisfied, the condition that evenly spaced vertical lines in the domain are mapped to evenly spaced circles is then $$\rho_x = C,$$ for some constant $C$, that is, $\rho_{xx} = \rho_{xy} = 0$.
In these coordinates, the Cauchy-Riemann equations are
$$(\log \rho)_x = \alpha_y, \qquad  (\log \rho)_y = -\alpha_x.$$
Substituting our conditions gives that
$$
\alpha_x = 0, \qquad \alpha_y = \frac{C}{\rho} .
$$
But these conditions imply that $\rho$, $\alpha$ are constant. (Why?) Thus, $f(x, y) = \rho e^{i \alpha}$ is constant, hence not conformal.
Dropping the conformality hypothesis In the comments o.p. mentioned they were also in interested a function that had the desired spacing property even without the conformality requirement. In that case, applying our conditions on $\rho$ imposes precisely that $\rho$ is an affine function of $x$ alone, that is, is of the function $$f : (x,y) \mapsto (A x + B) e^{ig(x,y)} .$$ Here, $A$ is the distance between the concentric rings that are the images of vertical lines $1$ unit apart, and $B$ is the radius of the circle to which the imaginary axis is mapped. In particular, we probably want $A \neq 0$, lest our function map all of $\Bbb C$ into the circle of radius $B$ centered at the origin). The Jacobian determinant of $f$ as above is
$$\det \operatorname{Jac}(f) = A (A x + B) g_y,$$ so if $A \neq 0$ and $g_y$ vanishes nowhere, the map is invertible everywhere except on the vertical line $x = -\frac{B}{A}$, which is mapped to the origin. The natural choice $B = 0$, $g(x,y) = y$ yields the simple map $$(x,y) \mapsto x e^{i y},$$ perhaps restricted to the right half-plane, $\{x > 0\}$.
Remark 2 If we only impose the condition $\rho_y = 0$, an analysis similar to ours shows that the only conformal maps that send vertical lines in the domain to circles centered at the origin are (locally) the maps $z \mapsto A \exp(b z)$.
Comment: Thank you for your answer!
How about a non-conformal mapping then? I don't care as much for it to be strictly conformal.
Comment: You're welcome. Looking at our conditions we see that we have a lot of freedom: any function $(x, y) \mapsto (A x + B) e^{i g(x, y)}$ should suffice, where $A$ is the distance between the concentric rings that are the images of vertical lines $1$ unit apart, so we probably want $A \neq 0$ (otherwise our function maps all of $\Bbb C$ into the circle of radius $B$ centered at the origin).
Comment: The Jacobian of the map is $A (A x + B) g_y$, so if $g_y$ is nonvanishing, the map is invertible everywhere except on the vertical line $x = -\frac{B}{A}$, which is mapped to the origin. A natural choice is $B = 0$, $g(x, y) = y$, giving $(x, y) \mapsto x e^{iy}$, perhaps restricted to the right half-plane, $\{x > 0\}$.
Comment: If these comments are useful to you, feel free to edit the original question and then comment here, and I'll update my answer accordingly.
Comment: Yes, that's what I was looking for ! Thanks a lot :)


Textbook for Bayesian econometrics

Question: I am looking for a theoretically rigorous textbook on Bayesian econometrics, assuming a solid understanding of frequentist econometrics.
I would like to suggest one work per answer, so that recommendations can be voted up or down individually.
Answer: Bayesian Econometrics, by Gary Koop (2003) is a modern rigorous coverage of the field that I recommend. It is in addition completed by a book of exercises: Bayesian Econometric Methods (Econometrics Exercises) by Gary Koop, Dale J. Poirier and Justin L. Tobias (2007).
Comment: Both of these books come with accompanying MATLAB programs, too, so they're also useful for people doing applied work.
Answer: I suggest "Bayesian Data Analysis" by Gelman et al.:
Gelman, A., Carlin, J., Stern, H., Dunson, D., Vehtari, A., Rubin, D. (2013). Bayesian Data Analysis, Third Edition. New York: Chapman and Hall/CRC.
Comment: Bayesian Analysis is a terrific book. However, it hardly classifies as an econometrics textbook.
Answer: An Introduction to Bayesian Inference in Econometrics
by Arnold Zellner (1971)
From the cover:

"This is the first book in econometrics to look at models and problems
  from the Bayesian point of view. [M]any comparisons of Bayesian and
  non-Bayesian results are presented. [...] An Introduction to Bayesian
  Inference in Econometrics will be of value as a guide to Bayesian
  Econometrics for graduate-level students and as a reference volume for
  researchers."
Comment: Ha! Well, that's arguable, so I won't go there.
Comment: Great reference, slightly (?) outdated for a textbook as it was written in the pre-computational era.
Comment: Agreed; the book is old and does not cover more modern computationally intensive techniques like, say, Bayesian Model Averaging. That said, out of all of the Bayesian Econometrics books that I own, I learned the guts of what I know from this classic piece of work by Zellner. Interestingly, a couple of FORTRAN programs for numerical integration are included in the appendix.
Comment: thanks. I am not certain FORTRAN programs are a plus nowadays...!
Answer: While it's made for marketing, I'd suggest Bayesian Statistics and Marketing by Rossi, Allenby & McCulloch for Bayesian inference in economic models.
Comment: Very dense but usefull text for people interested in modeling choice and demand. Since the authors acknowledge *Seymour Geisser*, *Dennis Lindley*, and *Arnold Zellner* as their influential teachers one might get an idea of what to expect. What makes this book very usefull is a set of 5 case studies complete with all data and R code for all models.
Answer: I might consider Contemporary Bayesian Econometrics and Statistics by John Geweke. It is relatively brief. The first three chapters cover the sort of foundational stuff you find in any Bayesian analysis book. The next chapter is the linear model with a tad of non-linear regression, followed by latent variables and missing data, then time-series and closed with model comparison and evaluation. There's not very much on panel data or semi/nonparametric estimation.

Textbook for Bayesian econometrics


Distributing negative fraction across parentheses

Question: At 13:26 in this youtube video why/how did he:

1) Change the three negative fractions to positive ones
2) Change the denominator from 4 to 8 on the last fraction

I think it is because he did a half multiplied by everything inside the bracket which turned them from negative into positive, and changed the denominators?
Comment: I am not interested in clicking through to a video and trying to find the problem.  Please write up the question using MathJax per the FAQ.  Writing it up may inspire you.
Answer: He had $y=\frac32-\frac12(-\frac14-\frac{3\sqrt{17}}4)$
He changes the negative fractions to positive ones by distributing the $-\frac12$ factor to each term in the parentheses; $4*2=8$ so the denominator of the fractions becomes $8$
Comment: Thanks. I thought so, that is what I tried to say in my paragraph under the question.


pg_restore taking much longer than pg_dump

Question: I am regularly saving and later restoring a smallish PostgreSQL database, which is used for testing. Its data is updated regularly as a result of tests, then a new dump must be made, and the dumps are regularly used to recreate the database in a well-defined state.
I noted that the dump (using pg_dump -Fc database) only takes a few seconds, but the restore (pg_restore -d database) takes about a minute. This seems weird. I would have expected both to take about the same time (assuming both tasks are I/O-bound).
Is there some problem with the restore? Could I maybe make it faster? Or is it normal for restore to take much longer than dump? (And if yes, then why?)
The dump file usually has about 3-4 MiB; the DBMS is PostgreSQL V8.4, running on a Pentium4 3GHz with 1GiB RAM under Ubuntu Linux.
Answer: The content of an index is not part of the backup, only the definition of the index. And that will only take a few bytes. When the index is created during restore and all data is indexed, it will be much bigger. This will take time, but it depends on your situation how much time.
pg_restore does have an option for concurrent restore (as of version 8.4), use --jobs=number-of-jobs
Comment: @sleske you might try with the [filesystem backup approach](http://www.postgresql.org/docs/8.4/static/backup-file.html). This should preserve indexes and, in addition, probably run a bit faster for both backup and restore
Comment: @Stefano: Interesting option; I didn't know this was possible. I don't think this is feasible for us, though, as has quite a few constraints (need to shutdown DBMS, need to dump/restore *all* databases). I fear this is only feasible if you have a PostgreSQL installation all to yourself, which I cannot assume.
Comment: @sleske yeap, I understand, on a 24/7 production server that definitely is not a good option. Only good to dump the FULL cluster too, which might not be handy if you only needed one db. We do use it ourselves from time to time, setting up a "maintenance" page for a couple of minutes, when we really want to replicate our full base for deeper tests on a dev machine...
Comment: @Stefano: Actually, production issues are not a problem, as I need the dump/restore for automated Q/A tests. However, the Q/A environment should be easy to set up (because ideally each dev should have his/her own, in addition to several company-wide environments), and requiring a dedicated DBMS installation with all kinds of backup scripts is something I would like to avoid.
Comment: Interesting, thanks. Is there a way to dump the index as well, to speed up the restore (at the cost of a larger dump file)?
Comment: No, the content of the index can't be part of the backup. For a very small database like yours (3-4 MiB), it shouldn't be a problem anyway.
Comment: Additional information: pg_dump doesn't have access to the content of an index. pg_dump uses SELECT statements to get all content of the tables and content of the system tables to create the backup. It's "just" a wrapper around some SELECT statements and some functions to write the results to disk.
Comment: @Frank: Thanks. Didn't know about pg_dump's implementation. In our case, speeding up the restore would be helpful, because it needs to run repeatedly as part of automated tests, so bringing it down from 1 minute to say 10s would help. But apparently that's not feasible. I'll have to find a different solution...
Comment: A 3 to 4 MiB backup file should be restored in a few seconds, not minutes. Even when using older hardware. Did you check http://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server for the configuration?
Answer: For a restore, the database has to do a lot of additional work:
Some things come to mind immediately:

Writing is slower than reading
Parsing the input takes time
Updating indexes and other internal structures
Maintaining referential integrity

Not sure if this amounts to that time difference, though.


Qual o erro nesse Código:

Question: Estou tentando compilar esse código,do use a cabeça C mas esta me retornando erros
#include <stdio.h>

    void go_south_east(int* lat, int* lon)
    {
        *lat = *lat -1;
        *lon = *lon - 1;

    }

    int main()
    {
        int latitude = 32;
        int logitude = -64;
        go_south_east(&latitude, &longitude);
        printf("Avast! Now at: [%i, %i]\n", latitude, longitude);
      return 0;

    }

Error:
root@kali:~# gcc testmains.c -o testmains testmains.c: In function 'main': testmains.c:14:28: error: 'longitude' undeclared (first use in this function) testmains.c:14:28: note: each undeclared identifier is reported only once for each function it appears in

Comment: Você declarou "logitude" (sic). Foi um simples erro de digitação.
Comment: Qual erro você está tendo exatamente?
Comment: Talvez você prefira [edit] sua pergunta para adicionar o erro, fica mais claro para ler.
Comment: Bem vindo ao [pt.so]. Poderia esclarecer qual é a sua dúvida?  Que erro o compilador está retornando? Aproveite e faça um [tour] pelo site e confira o guia de [ask].
Comment: Bem-vindo ao stackoverflow em Português! Tente explicar melhor o seu problema, o erro que lhe ocorre e o que pretende fazer, assim fica difícil alguém responder...
Comment: Nossa, porque negativaram?
Comment: Bom, eu não negativei, mas acredito que foi por que não está claro o que você está perguntando. A situação pode ser revertida facilmente, não precisa se preocupar. Comece por esclarecer sua dúvida: qual erro está tendo? O que espera que aconteça de verdade no seu código?
Comment: root@kali:~# gcc testmains.c -o testmains
testmains.c: In function 'main':
testmains.c:14:28: error: 'longitude' undeclared (first use in this function)
testmains.c:14:28: note: each undeclared identifier is reported only once for each function it appears in
Answer: Em um teste rápido observa-se as seguinte mensagens de erro:
prog.c: In function 'main':
prog.c:14:35: error: 'longitude' undeclared (first use in this function)
         go_south_east(&latitude, &longitude);
                                   ^
prog.c:14:35: note: each undeclared identifier is reported only once for each function it appears in
prog.c:13:13: warning: unused variable 'logitude' [-Wunused-variable]
         int logitude = -64;
         ^

Ou seja, a variável longitudenão foi declarada, e temos uma outra variável logitude que não é utilizada.
Imagino que você simplesmente escreveu errado o nome desta variável. Corrigindo isso o código compila e executa.
Comment: Se você prestar atenção às mensagens de erro e os avisos do compilador você consegue descobrir rapidinho qual é o problema.
Comment: Não estou conseguindo compilar....
Answer: Amigo, corrige o nome da variável :
int logitude = -64;
go_south_east(&latitude, &longitude);

Quando esta declarando está faltando um 'n' no longitude.
Comment: Use uma IDE para reduzir a chance desses erros acontecerem :)
Comment: Eu sou burro demais para perceber erros de digitação......

Qual o erro nesse Código:


What is the easiest way to upload video and audio content?

Question: I am creating a website archive that will allow users to upload various different types of media content including video, audio, images, documents and text. I want to make it easy for users to upload the media content to the site.
Is it better to upload directly to the website hosting itself or to use a third party video and audio hosting like YouTube and SoundCloud?
Either way how can it be made as easy as possible for the user to upload the media content?
Comment: Checkout media module.
Answer: Get a media management suite that integrates with as many third party hosting providers as possible. It means less work for you, less complexity, and less bandwidth on your server for which you have to pay.
Good suite's include, but are not limited to:
Scald

Scald is a popular and flexible way to handle media in Drupal.
Scald can handle images, video, audio, tweets and even Flash files.
  Scald works with YouTube, Vimeo, Soundcloud and other many other
  providers.

and Media

The Media module provides an extensible framework for managing files
  and multimedia assets, regardless of whether they are hosted on your
  own site or a 3rd party site - it is commonly referred to as a 'file
  browser to the internet'.

For a front end media solution you can look at MediaFront

The MediaFront module is a front end media solution for Drupal. It
  employs an innovative and intuitive administration interface that
  allows the website administrator to completely customize the front end
  media experience for their users without writing any code.
Answer: You can try filedepot module

The filedepot module is full featured Document Management module that
  has a google docs like feel. It fulfills the need for an integrated
  file management module supporting role and user based security.
  Documents can be saved outside the Drupal public directory to protect
  documents for safe access and distribution.
Comment: Thanks, I'll have a look at that.  Does it include a media player?
Answer: Some more modules not mentioned yet in any of the previous answers ...
Modules with a stable D7 release
Take Control (D6 and D7)
Here is a quote about the Take Control module (from its project page):

... is a set of set of modules for Drupal for managing various administrative tasks particularly related to the file system. Beginning with version 2.0, the module has been refactored into a core/add-on architecture, where a core module take_control provides common routines and settings, whereas the bulk of front-end user interaction comes from add-on modules (e.g. file browser etc).
Currently, there are 2 add-on modules:

File Browser: A complete File Browser/File Manager for Drupal. Allows you to manage your Drupal file-system directly through Drupal without needing FTP or your Hosting Control Panel access.

Quick Permissions: Many Drupal administrators are troubled by the: Drupal_Security_Do_Not_Remove_See_SA_2006_006
directive in Drupal file-system root's .htaccess file that effectively prevents write access to the file-system folder outside Drupal.
This module allows you to take control of the file-system folder by specifying custom permissions on it from Drupal. Additionally, you can specify custom permission / delete any directory/file owned by Drupal using this module.

Document (D6 and D7)
The Document module is a Document Management System for Drupal. Here is a quote about it (from its project page):

Features:

Complete integration with Drupal node system. This module adds a custom Node Type, Document. Each Document you create is a Drupal node, and hence enjoys all features available to a node.
Support for Document revisions/versioning - This module allows you to maintain multiple versions/revisions of the same document.
Views 2 Integration - The custom fields added by the module to the Document node type are accessible in Views, plus the module provides some useful out-of-the box Views.
Theming support
Searching - The documents being nodes are fully indexable by the Drupal search system. In addition, the module provides its own custom search for Documents.
A couple of blocks are available for document search that can be placed flexibly in your theme layout.

elFinder file manager (D7)
The elFinder module integrates with elFinder, which is a open source AJAX file manager.  Here is a quote about it (from its project page):

Features:

Integrated with WYSIWYG API capable editors: CKEditor, FCKeditor, TinyMCE, BUEditor (D6), jWYSIWYG (D6), YUI, WYMeditor.
Multiple file upload.
File copying/moving with Drag & Drop support.
Quick file and directory rename.
Image resizing.
Lightbox-preview.
Context menu with generic file/directory operations.
Inline text file editing.
Favourites directory list.
Directory selection history.
Working with archives.
File descriptions.

CMIS API (D7)
The CMIS API module aims to provide a generic API for integrating with CMIS compliant Enterprise CMS (ECM) systems.
Modules with an unstable D7 release or for D6 only
There are a few more modules that might look like a possible fit, though they are, in general, perceived as rather buggy / unstaled, or only support old (D6) Drupal releases so far. Below are some more details about those modules.
Media Browser Plus (D7, though only a beta version)
There is also the Media Browser Plus module, which is an enhancement module for the Media module, with additions such as:

Adding tags to media when uploading.
Searching media.
Hierarchical taxonomy based organization e.g. "folders".
Mirroring folder taxonomy to filesystem"
Drag & Drop to move files between folders.
Multi selection of files.
Bulk operations on files.
Media Basked to download multiple files at once.

Asset (D7, though only a beta version)
Here is a quote about the Asset module (from its project page):

... proposes a new approach to the media management in Drupal, resolving a long-standing problem of reusable media files (images, videos, documents, etc) that evolved into the problem of reusable media content (images/videos/documents/etc with the attached content like description/licence/etc).
The Asset module provides new entity called Media Asset and the set of Media Assets examples (Image, Video, Audio, Document, Image Gallery, Free HTML), which can be enabled optionally.

Web File Manager (D6)
The 'Web File Manager' module is for D6 only. And issue WebFM for Drupal 7 has status Closed (Won't fix). But there is also an ongoing discussion about a Ground-up rewrite of WebFM.


Only show what's new in a file

Question: I want to find out what was added to a log file between 2 tasks. Right now the way I do it is:
content of test.log initially
aaa
bbb

saving content of the log
$ cp test.log test.log.before

doing something
content of test.log after doing something
aaa
bbb
ccc

saving content of the log
$ cp test.log test.log.after

showing the difference
$ diff test.log.before test.log.after
2a3
> ccc

What I don't like with this method is that I get some noise from diff (2a3 and >) whereas I just want ccc.
Q: Is there a way I can just get the difference between the 2 log files (i.e. what is new in test.log.after, ccc)?
I had a look at diff's man page but I don't see anything obvious there.
Answer: If you always do a before and after such that the end of the after file will contain the new content then you could use comm.
$ cat before
aaa
bbb

$ cat after
aaa
bbb
ccc

$ comm -3  after before
ccc

Comment: But, the files should be sorted!
Comment: This works as expected if the files are the same up to the point that new stuff is added.
Comment: `comm` is OK but output comes out tabulated. I prefer the `grep`+`cut` alternative.
Comment: that's why I did `after before` so that the output (which contains the changes) is at the beginning of the line, doing `before after` would give you tabs to deal with.
Answer: If you want to get the additions only you can filter the output such as:
$ diff test.log.before test.log.after | grep "^>" | cut -c 3-

However, you will lose the deletions if any.

Only show what's new in a file


Override module function in my custom module?

Question: I am using module Mixpanel in my site. And I want to override function of this module. Here is link where we can see the function or code which I need to alter CODE NEED TO MODIFIED
Below is the code line which suggest that I can override this function :
    // Let other modules alter the defaults.
    drupal_alter('mixpanel_defaults', $properties, $account);

So from above line I am trying to override it with code as below, please let me know what I am doing wrong as it does not make any changes. However if I do same thing in main module it make changes but I don't want to make change in module but want to do in my custom module.
My custom module name: custom
function custom_mixpanel_defaults_alter($properties, $account) {

  $properties['distinct_id'] = $account->name;

}

When i see in system table weight of my custom module is 1000 and weight of Mixpanel is 0.
Please suggest! Thanks
Comment: Alter functions takes the variables as references. Try using `&$properties` instead of just `$properties`, and `&$account` in place of `$account`.
Comment: Thank you. as per your suggestion it worked :) I think you can post it as answer if you want to so that it can help other users as well.
Answer: The error is how you define the parameters, which should be defined as custom_mixpanel_defaults_alter(&$properties, $account).
PHP 5 automatically passes by reference any object passed to a function, but not the arrays. Since $properties is an array, you need to make the reference explicit.
Generally speaking, when you see a call to drupal_alter() like drupal_alter('node_view', $build), and you need to implement that alter hook, check the second and third parameter are object or arrays; in the case they are array, you need to explicitly declare the parameter as reference. In this case, hook_node_view_alter() is defined as hook_node_view_alter(&$build).
Comment: Thanks for explanation! and so it means we do not need to pass `$account as reference &$account` as its not array ?
Comment: Exactly: `$account` is an object, so PHP 5 will automatically pass it as reference.


How to get the root node in Stanford Parse-Tree?

Question: I have this parse tree here:

What I want is to get all words from a common parent given a word in the set of children of a subtree. For example if you take the word "bottles" then I want to get "the Voss bottles" or maybe even "the Voss bottles of water" but I don't know how to do that.
Annotation document = new Annotation(sentenceText);
this.pipeline.annotate(document);

List<CoreMap> sentences = document.get(SentencesAnnotation.class);

for (CoreMap sentence : sentences) {

    Tree tree = sentence.get(TreeAnnotation.class);

    List<Tree> leaves = new ArrayList<>();
    leaves = tree.getLeaves(leaves);

    for (Tree leave : leaves) {
        String compare = leave.toString().toLowerCase();
        if(compare.equals(word) == true) {
            // Get other nodes in the same subtree
        }
    }
}

Calling leave.parent() does not work. I also tried tree.parent(leave)  but that doesn't work either (returns null).
I also tried
for (Tree leave : tree) {
    String compare = leave.toString().toLowerCase();
    if(compare.equals(word) == true) {
        // ..
    }
}

but I get the same.

public Tree parent(Tree root) Return the parent of the tree node. This routine will traverse a tree (depth first) from the given root, and will correctly find the parent, regardless of whether the concrete class stores parents. It will only return null if this node is the root node, or if this node is not contained within the tree rooted at root.

How can I manage to do that? #EverythingIsBrokenAllTheTime
Answer: This example line should give you two levels up for a given word (note that there are nodes for POS tags, so you need to do parent twice ; the first parent returns the subtree with the POS tag as the root)
Tree root = (leave.parent(tree)).parent(tree);

"leave" should be the node for the word
"tree" should be the tree for the entire sentence
This method goes through the tree from the root, keeping track of the nodes it passes through.  When it hits the node you want (in this example "leave") it returns the appropriate parent.
full code:
import java.io.*;
import java.util.*;
import edu.stanford.nlp.io.*;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.trees.*;
import edu.stanford.nlp.trees.TreeCoreAnnotations.*;
import edu.stanford.nlp.semgraph.*;
import edu.stanford.nlp.ling.CoreAnnotations.*;
import edu.stanford.nlp.util.*;

public class RootFinderExample {

    public static void main (String[] args) throws IOException {
        // build pipeline
        Properties props = new Properties();
        props.setProperty("annotators","tokenize, ssplit, pos, lemma, ner, parse");
        StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
        String text = "We were offered water for the table but were not told the Voss bottles of water were $8 a piece.";
        Annotation annotation = new Annotation(text);
        pipeline.annotate(annotation);
        List<CoreMap> sentences = annotation.get(SentencesAnnotation.class);
        for (CoreMap sentence : sentences) {
            Tree tree = sentence.get(TreeAnnotation.class);
            List<Tree> leaves = new ArrayList<>();
            leaves = tree.getLeaves(leaves);
            for (Tree leave : leaves) {
                String compare = leave.toString().toLowerCase();
                if(compare.equals("bottles") == true) {
                    System.out.println(tree);
                    System.out.println("---");
                    System.out.println(leave);
                    System.out.println(leave.parent(tree));
                    System.out.println((leave.parent(tree)).parent(tree));
                }
            }

        }
    }

}

Comment: Like I stated in the question, calling `leave.parent(tree)` does not work as it throws an exception everytime
Comment: In the question you used "tree.parent(leave)".  I ran an example with leave.parent(tree) and was not getting null I"ll try to post later.
Comment: Ah sorry, that's just returning `null` but no exceptoin.


probability mass function of number of cards required until a club

Question:
Cards are drawn sequentially from a standard deck of $52$ cards until a club appears. Let X denote the number of cards required. Find the probability mass function of X.

My solution:
P(X=k)= $\frac{\binom{39}{k-1}}{\binom{52}{k-1}}$ * $\frac{13}{\binom{52-k-1}{1}}$
Is this correct?
Edit: Answer given in solutions is
$\frac{\binom{39}{k-1}}{\binom{52}{k-1}}$ * $\frac{13}{\binom{53-k}{1}}$ where $k \in\ {1,\dots\ ,40}$.
Hence the confusion.
Comment: The book answer is correct, check for a simple example, e.g. for k = 2. Obviously, the answer should be $\frac{\binom{39}{1}}{\binom{52}{1}} \frac{\binom{13}{1}}{\binom{51}{1}}$
Answer: Yes, but don't forget to indicate the support.
$$\mathsf P(X=k) = \dfrac{\binom{39}{k-1}\cdot 13}{\binom{52}{k-1}\cdot(51-k)}[k\in\{1,\dots,40\}]$$
Comment: But $\frac{\binom{39}{k-1}}{\binom{52}{k-1}}$ * $\frac{13}{\binom{53-k}{1}}$
where  $[k \in\ 1,\dots\,40]$
This is the answer given in solutions book!!!


Custom field Widget multiple values as a Table

Question: Hello I created a custom field type and field widget with multiple values, one entity reference and two checkboxes.
Everything's was working well, but to improve the usability of the fields, I would like to display the fields as a table, and that is when my problem begins.
I tried changing the field widget to be like a table, that visually worked to me, but now I will have problem because the keys of each field will be different than the defined in the field type, any suggestions in how to handle with this problem?
If i roll back and remove the 'multiple_route' key to create the table and set the $elements[''] like i orignally started the fields are saving correctly.
FieldWidgetType.php
class MultipleRouteWidgetType extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $element['multiple_route'] = [
      '#type' => 'table',
      '#header' => [
        t(''),
        t('checkbox 1'),
        t('checkbox 2'),
      ],
    ];

    $route_value = NULL;
    if (isset($items[$delta]->route)) {
      $route_value = \Drupal::entityTypeManager()->getStorage('node')->load(intval($items[$delta]->route));
    }

    $element['multiple_route'][0]['route'] = $element + [
      '#title' => t('Page'),
      '#type' => 'entity_autocomplete',
      '#target_type' => 'node',
      '#required' => TRUE,
      '#empty_value' => NULL,
      '#default_value' => $route_value,
    ];

    $element['multiple_route'][0]['checkbox_1'] = [
      '#title' => t('checkbox 1'),
      '#type' => 'checkbox',
      '#empty_value' => 0,
      '#default_value' => isset($items[$delta]->checkbox_1) ? $items[$delta]->checkbox_1 : 0,
    ];

    $element['multiple_route'][0]['checkbox_2'] = [
      '#title' => t('checkbox_2.'),
      '#type' => 'checkbox',
      '#default_value' => isset($items[$delta]->checkbox_2) ? $items[$delta]->checkbox_2 : 0,
    ];

    return $element;
  }

}

Visually this is my goal and worked:

But now the fields will not save because the keys are different than the definied in the schema, resulting in this error:

The website encountered an unexpected error. Please try again later.
Error: Cannot create references to/from string offsets in
Drupal\Component\Utility\NestedArray::setValue() (line 155 of
core/lib/Drupal/Component/Utility/NestedArray.php).
Drupal\Component\Utility\NestedArray::setValue(Array, Array, NULL)
(Line: 1254)

Field Type.php property definitions and schema:
class RouteFieldType extends FieldItemBase {

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['route'] = DataDefinition::create('integer')
      ->setLabel(new TranslatableMarkup('Page'))
      ->addConstraint('RouteConstraint', ['fieldName' => $field_definition])
      ->setRequired(TRUE);

    $properties['checkbox_1'] = DataDefinition::create('boolean')
      ->setLabel(new TranslatableMarkup('checkbox_1'));

    $properties['checkbox_2'] = DataDefinition::create('boolean')
      ->setLabel(new TranslatableMarkup('checkbox_2'));

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = [
      'columns' => [
        'route' => [
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
        ],
        'checkbox_1' => [
          'type' => 'int',
          'size' => 'tiny',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'default' => 0,
        ],
        'checkbox_2' => [
          'type' => 'int',
          'size' => 'tiny',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'default' => 0,
        ],
      ],
    ];

    return $schema;
  }

Answer: Your widget needs to massage the form values. Like this core widget which restructures the array by removing one level:
/core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php
  /**
   * {@inheritdoc}
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    // Since file upload widget now supports uploads of more than one file at a
    // time it always returns an array of fids. We have to translate this to a
    // single fid, as field expects single value.
    $new_values = [];
    foreach ($values as &$value) {
      foreach ($value['fids'] as $fid) {
        $new_value = $value;
        $new_value['target_id'] = $fid;
        unset($new_value['fids']);
        $new_values[] = $new_value;
      }
    }

    return $new_values;
  }

Answer: Thank you.
Before that to quick solve the issue and because my task was late, i emulate the form table with a markup on the suffix and prefix on the widget fields and returned the keys to the root of structure of $element:
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $prefix = '

          ' . t('Checbox 1') . '
          ' . t('Checbox 2') . '

    ';

    $route_value = NULL;
    if (isset($items[$delta]->route)) {
      $route_value = \Drupal::entityTypeManager()->getStorage('node')->load(intval($items[$delta]->route));
    }

    $element['route'] = $element + [
      '#prefix' => $prefix,
      '#suffix' => '	',
      '#title' => t('Page'),
      '#type' => 'entity_autocomplete',
      '#target_type' => 'node',
      '#required' => TRUE,
      '#empty_value' => NULL,
      '#default_value' => $route_value,
    ];

    $element['checkbox_1'] = [
      '#prefix' => '',
      '#suffix' => '	',
      '#title' => t('c'),
      '#title_display' => 'invisible',
      '#type' => 'checkbox',
      '#empty_value' => 0,
      '#default_value' => isset($items[$delta]->checkbox_1) ? $items[$delta]->checkbox_1 : 0,
    ];

    $element['checkbox_2'] = [
      '#prefix' => '',
      '#suffix' => '

',
      '#title' => t('c.'),
      '#title_display' => 'invisible',
      '#type' => 'checkbox',
      '#empty_value' => 0,
      '#default_value' => isset($items[$delta]->checkbox_2) ? $items[$delta]->checkbox_2 : 0,
    ];

    return $element;
  }


What is the order of operations in a given formula?

Question: My question is probably very basic. It's related to the order of operations in the following simple formula:
$$\frac{A}{B\times C}.$$
My question arises when I want to write this formula in a single line. For instance: $150/1.5\times 0.33$.
Should I write $150/1.5\times 0.33$ or $150/(1.5\times 0.33)$. Is the answer equal to $300$ or $33.3$? I mean, it's obviously $300$ according to the original formula. But I am a bit confused with the single line formula.
I remember that the multiplication has a preference over the division. So, the parenthesis is not needed... But then the answer might be $33.3$, which is not correct. I get stuck with this quite simple thing.
Comment: See [Order of operations](https://en.wikipedia.org/wiki/Order_of_operations).
Comment: Multiplication does not have precedence over division. Instead, $A/B\cdot C=(A/B)\cdot C\ne A/(B\cdot C)$.
Comment: "the multiplication has a preference over the division" - not really...
Comment: If writing in a programming language a sequence of / and * they should have the same precedence - in practice numerical precision will probably be affected, but mathematically you could execute any order of them. What division means is to multiply with the inverse element. So division is actually a multiplication-in-disguise, but with another element - the multiplicative inverse.
Comment: @mathreadler: Totally false. Read any reference for any mainstream programming language and you will find that the order of execution is **determined** even if two operations have the same precedence. Secondly, you could have tried the example in this question itself to see that mathematically your claim is bogus.
Comment: Not at all true. There's plenty of languages where you can make sure you get the same result either way you do the computation. Arbitrary precision arithmetics, bigints, languages which can do computer algebra. Often you can decide for yourself in the language if you would like to switch precedence even.
Comment: @mathreadler: Your claim "mathematically you could execute any order of them" was ridiculous. $\large\color{red}{(6/3)\times 2 \ne 6/(3\times 2)}$. And in numerous mainstream languages including C/C++/Java/Javascript the precedence is **not** the only factor, but also associativity. Go and read a programming language reference. Read the question carefully; it is not about rearranging the numbers but the order of executing operations on the numbers next to them.
Comment: They have the exact same precedence mathematically so you need to specify which goes first. That division is decided to go before multiplication in absence of parens is nothing but a **convention** that many programming languages conform to because without parentheses the expression will be ambiguous and requiring parentheses would make expressions very convoluted. It is also true that precedence does matter whenever you have limited precision arithmetics, as is the case in languages where it is assumed the symbols will evaluate conforming to various popular floating point standards.
Answer: The other answers here address the mathematics of "order of operations" - operator precendence in programming languages. They pretty much tell you to use the parentheses.
I want to address this point explicitly:

My question arises when I want to write this formula in a single line.

You are asking here about communication. The important issue is to make your meaning unambiguously clear. So when writing inline you should use the parentheses in the denominator, even if they are unnecessary because your reader or your compiler "knows what you mean".
Answer:
Grouping (fractions, parantheses, $a\choose{b}$, etc)
Exponents ($x^3$ and $\sqrt[a]{x}$)
Multiplication (and division)
Addition (and subtraction)

In $\frac{A}{BC}$ We can split it into $A \div (BC)$, first we do the grouping, the parentheses around $(BC)$, so we multiply $B$ by $C$. Then, we divide $A$ by $BC$.
This applies to all equations, across all mathematics.
Answer: Multiplication does not have precedence over division; they have the same precedence. And we perform operations with the same precedence from left to right. Same for addition and subtraction.
$
\def\lfrac#1#2{{\large\frac{#1}{#2}}}
$
Hence $A / B \times C = ( A \div B ) \times C$ which is different from $A / ( B \times C ) = \lfrac{A}{B \times C}$.
Curiously $\lfrac{AB}{C} = ( A \times B ) \div C = A \times B \div C = A \times ( B \div C ) = A \lfrac{B}{C}$.
But $\lfrac{A}{BC} = ( A \div B ) \div C = A \div B \div C \ne A \div ( B \div C ) = A \lfrac{C}{B}$.
Got it?
Comment: But be careful of "$a / bc$" which you may find in some books like [this one](https://books.google.co.uk/books?id=Il5wScV2JxUC&pg=PA67&lpg=PA67&dq="1/2π") (compare the earlier page), which may mean "$\lfrac{a}{bc}$". Some authors like this one would write "$1/2π$" for "$\lfrac1{2π}$" whereas others would write exactly the same thing to mean "$\lfrac12 π$".
Answer: To understand this we must first explain what division means.
Division is multiplication by an inverse element. In a group or a field there is ensured to exist an inverse element such that if you multiply it it becomes 1 : $\frac{a}{a} = a^{-1}a= aa^{-1} = 1$. What is important is to specify which element should be inverted before multiplication. In many programming languages there is a convention that division has higher precedence. That is just to make sure one knows which number we should find the multiplicative inverse for before performing multiplication with it.
$$\frac{a}{bc} = a(bc)^{-1}, \frac{ab}{c} = ab(c)^{-1}$$
Where $(bc)^{-1}$ is the multiplicative inverse to $bc$ and $(c)^{-1}$ is the multiplicative inverse for $c$.
The horizontal division sign ____ only helps us explaining this for commutative algebras as we otherwise need to also decide from which side the division occurs. Or in other words from which side we should multiply with the multiplicative inverse.
Comment: In what programming languages does division have precedence over multiplication? In Java and C-like languages multiplication and division have the same precedence, with left-to-right associativity. So in `a*b/c` the multiplication is done first. While this may make no difference in a pure math environment, in a programming language it may make a great deal of difference (due to overflow, for example).
Comment: I tried answering the question, explaining what multiplication and division is and how they are usually defined to work in algebra. If you look closely, you may find that there is no mention of any programming language in the question at all.
Comment: I commented on the answer, not the question, because the answer _does_ include a discussion of programming languages. Possibly the answer would be better if it didn't mention programming languages at all (though you also have some comments under the question with similar claims about precedence about which I have similar doubts--there are other things in addition to "precedence" that determine order of operations in programming).
Comment: I did mention them because they seemed to be a part of the confusion. We could keep at the programming technicalities, but I don't think it will help with the confusion at this point to expand more on it.
Comment: I agree that expanding on it the technical issues is not desirable. I think the solution would be rather to say a lot _less_ about programming languages; it may be best to remove basically everything that's already been said here about them (including my comments).


Derivations: Characterization

Question: Given a smooth manifold.
(In fact, it seems irrelevant to regard manifolds.)
Regard germs of functions:
$$\mathcal{C}_p^\infty(M):\quad f\sim g:\iff f\restriction\equiv g\restriction$$
and the two-sided ideal:
$$\mathcal{I}_p:=\{[f]:f(p)=0\}\subseteq\mathcal{C}_p^\infty(M)$$
(That is rather dirty notation. Sorry for that!)
Consider derivations:
$$D:\mathcal{C}_p^\infty(M)\to\mathbb{R}:D([fg])=D([f])g(p)+f(p)D([g])$$
They vanish on constant germs and on the square of the ideal:
$$D([c1])=0\quad D([ij])=0$$

Why is actually every such linear functional a derivation:
  $$L([c1])=0,\,L([ij])=0\implies L([fg])=L([f])g(p)+f(p)L([g])$$
Comment: You can write every germ as a constant (the value at $p$) plus something in $\mathcal{I}_p$. Expand everything out!
Comment: @Hoot: Ah of course, thanks!! :)
Comment: @Hoot: Do you mind posting a short answer about your comment? *(I'd like to check it off.)*
Answer: Let me post an answer on behalf of hoot.
Every function has a decomposition:
$$f\in\mathcal{C}_p^\infty(M):\quad f\sim f(p)1+(f(p)-f)$$
(So one can reduce the problem to the constant germ and the ideal.)

Derivations: Characterization


Select first N items in a Google BigQuery Repeated Field

Question: Is there a way to select the first n items in a Google BigQuery Repeated field?
Looking at an example from Google's documentation:
WITH items AS
    (SELECT ["apples", "bananas", "pears", "grapes"] as list
    UNION ALL
    SELECT ["coffee", "tea", "milk" ] as list
    UNION ALL
    SELECT ["cake", "pie"] as list)

SELECT list, list[OFFSET(0)] as offset_1, list[OFFSET(1)] as offset_2
FROM items;

gives the following:

The OFFSET() function returns a single (Non-Repeated) element.
Is there a elegant way to select the first n (say n=2) elements in a Repeated field?  Looking at row 1, the output should be a Repeated field with two elements: apples and bananas.
Comment: Can you include the expected output as well?
Answer: Below is for BigQuery Standard SQL
#standardSQL
WITH items AS (
  SELECT ["apples", "bananas", "pears", "grapes"] AS list UNION ALL
  SELECT ["coffee", "tea", "milk" ] AS list UNION ALL
  SELECT ["cake", "pie"] AS list
)
SELECT
  list AS original_list,
  ARRAY(SELECT item FROM UNNEST(list) item WITH OFFSET pos WHERE pos < 2) new_list
FROM items

with output as
Row original_list   new_list
1   apples          apples
    bananas         bananas
    pears
    grapes
2   coffee          coffee
    tea             tea
    milk
3   cake            cake
    pie             pie


Max area for a box

Question: I am really stupid and I can't get this on my own. If $1200 cm^2$ is used to make a square box with open top what is the largest volume the box could be?
I set it up like so $$v = l w h$$
$$v = w^2 h$$
$$1200 = w^2 + 4wh$$
Where do I go from here? Everything I try in wrong.
I tried to make it like so
$$h = 300/w 0 w/4$$ to eilimate h but it didn't help give an answer that is correct.
Comment: I presume the constraint is area = 1,200 cm squared?
Comment: Yes that is correct.
Answer: If the surface area is fixed at $1200$ cm$^2$, then
$$
1200 = w^2 + 4wh \quad \Rightarrow\quad h = \frac{1}{4w}(1200 - w^2).
$$
Then you can find the maximum volume from:
$$
V = w^2h = w^2\frac{1}{4w}(1200 - w^2) = \frac{1}{4}w(1200 - w^2)
$$

If the volume is fixed at $1200$ cm$^3$, then
$$
1200 = w^2h\quad \Rightarrow\quad h = \frac{1200}{w^2}.
$$
Then you can find the minimum area from
$$
A = w^2 + 4wh = w^2 + 4w\frac{1200}{w^2} = \dots
$$
Answer: There is a nice trick you can use here, to avoid calculus altogether: If you make two such boxes, you can turn one of them upside down and rest it on the other one, to get a closed box. This closed box will have the maximum volume for a surface area of 2400 $\text{cm}^3$, which is a cube of side 20. (You can prove this without calculus, just using the fact that for fixed $a$, $x(a-x)$ is maximised when $x=a/2$.)
So each open box has a volume of $20 \times 20 \times 10 = 4000 \text{cm}^3$.

Max area for a box


Projection of vector on $(x_1,x_3)$-subspace

Question: If I have a three-dim. vector
$$
(x_1,x_2,x_3)\in\mathbb{R}^3,
$$
what then is its projection onto the $(x_1,x_3)$-subspace?
I am not sure.
Answer: The picture represents the idea:

Red point is the three dimensional position $(x_1,x_2,x_3)$ and yellow one is the projection onto the two dimensional subspace (you mention) and has the specifications $(x_1,0,x_3)$.


Functions For One-Time Use

Question: In any language, is it better to use functions which are a bit long to write on the main function if you're only going to use it a few times? I heard that in Python, doing so will make the function faster. Is it also true in Javascript or in any other language?
Example:
function main(){
    blahblahblahblah1();
    blahblahblahblah2();
    blahblahblahblah3();

    blahblahblahblah1();
    blahblahblahblah2();
    blahblahblahblah3();
}
setInterval(main,1);

Is it better to group the code (blahblahblah) to make it look like this:
function blahblahblah(){
    blahblahblah1();
    blahblahblah2();
    blahblahblah3();
}
function main(){
    blahblahblah();
}
setInterval(main,1);

Answer: The performance impact of this decision is too small to measure in any language I'm aware of - the interpreter/compiler optimizes this away. The only cases where this may matter is if you're writing software for extremely constrained devices like embedded systems (but you wouldn't be doing that in Python or Javascript), or where you're writing software with extreme performance requirements like graphics engines for video games (but again, you wouldn't be using Python or Javascript for that).
Instead of optimizing for performance, I'd encourage you to optimize for readability, testability and bug resistance. Your second example is not equivalent to the first (it only executes the functions once, the first example executes them twice). Assuming you meant to have them equivalent, the second example is a little more readable, because the logic of executing the three functions is abstracted into a higher-level function.
Answer: if you use a logic only once in your code, you shouldnt create a function - the compiler/interpreter will optimize the code anyway. if you plan to reuse the logic, then create a function - it makes the code smaller and better to maintain for you - even its minimal slower for the extra functionlookup and call, these are minimal performance effects...

Functions For One-Time Use