scales on the guitar

Question: I'm new to learning music theory, so i'm sorry if the following question seems strange and obvious to some.
From what i understand, a scale is a logical combination of 8 notes. On the guitar, however, there are many more notes on the scale. For example, the G major scale pattern, root at the third fret, contains 16 notes. The first 15 notes are clear to me, as the last 8-15 are the same same notes as the first 1-8, just an octave higher. But the last note of the scale bothers me (the A notes, highest E string 5th fret). Why is it there, why not just stop at the third fret of the highest E string, which is a G note?
Answer: In your example, you refer to 16 notes, which are all in the key of G major. But properly speaking, the G major scale has seven notes and then the octave. What you are playing is the G major scale across two octaves and a second. You are playing a slightly-more-than two-octave pattern based upon a certain scale.
A scale is a sequence of pitches that proceed, in progressive order, from a low pitch to the same pitch one octave higher. A scale, conventionally, is something that repeats at each octave.
Look up some references on scales and modes. According to the theory of contemporary Western music, there are 12 keys, and for each key, there are diatonic scales that can be constructed from each tonic key from among 7 modes (with special attention paid to the distinction between the natural minor, harmonic minor and melodic minor variations in that one mode).
Each of the Western diatonic scales has seven notes and then the octave.
There are other kinds of scales from different systems of music: for instance, various pentatonic scales, which have only 5 notes and then the octave. The whole-tone or octatonic scale has 8 notes and then the octave, and the chromatic scale has 12 notes and then the octave.
Footnote: To further complicate things, outside of the realm of contemporary Western music, there are instruments and scales with pitches in them that do not fall into the 12 pitches you can play on a modern guitar or piano (which are tuned according to the system we call equal temperament). Some of what we call non-Western music contains certain notes and pitches that are notably flatter or sharper and fall between the 12 equally-spaced chromatic pitches on the modern guitar or piano.
Answer: You have misunderstood what a scale is. It doesn't matter what instrument you play, the scale is chosen from the 12 semitones available, and is in this case the 7 notes of the Gmajor scale, and onwards.
You can play the G major scale from G to G or you can keep going as far as you want up to the upper limit of your instrument. As long as it uses notes from that scale it is fine. Stop at that G on the E string if you want, or keep going.
Comment: Geekkid - you were fooled by the term 'octave', denoting a note of half or twice,basically, the frequency of another note.E.g. A is 440Hz, a lower A is 220 Hz and a higher A is 880Hz.Between one octave note and the next are 12 semitones and 7 of these notes in order constitute a scale- be it maj. or min.HOWEVER a pentatonic scale only uses 5 of these semitones before reaching the octave.The term octave actually refers to a diatonic scale in Western terms, and is somewhat a misnomer with regard to other scales.
Comment: Thank you. I thought it was a strict rule that a scale is 8 notes. But as i now understand, there isn't any set number of notes in a scale. A scale just represents the notes ordered by some algorithm (i'm a programmer, so .. :D).
Comment: Well, there are actually lots of variations - I have described western conventional scales, which have 12 semitones, but there are a range of others in other cultures.
Answer: If you mean this "scale pattern",
I believe the additional A at the top is for rhythmic purposes. It allows the final G to land on a beat for a more reassuring sense of finality.
Consider the result without the extra A, .
It just trails off. It doesn't land on the tonic, rhythmically weak. This would be difficult to execute, and troublesome to loop.
A third, slightly more rhythmically satisfying option is, .
This puts the root on a stronger beat, but you don't get to exercise your pinky for that A; it doesn't fill the measures like the first. It doesn't emphasize the tonic as much as the first, because you've lost that 9 -> 8 change. So it doesn't exercise your ears as much either.
The third measures of the second and third examples are just too weird. You would not want to start at those spots. Unless you're going for that extra challenge. Perhaps that's the real reason: so the third measure starts on the tonic.
Comment: MuseScore + Snipping Tool are my new friends.
Answer: On a lot of guitar tutoring sites, 'scales' are written using the boxes guitar players visualise and use. They often contain ALL of the notes from a particular scale, e.g. the G major you ask about may even 'start' on the F#, 6th string 2nd fret,as that note is fingerable within the box.As such, it'll sound like a Locrian mode, and it could be shown to go up to an A on top(thin) string, 5th fret, finishing more like a Dorian.  This is confusing to beginners,as they expect a scale to go from tonic to a higher tonic and probably back to the start again.This sounds more complete and is how scales are played in an exam situation.
Answer: There is only one scale, the chromatic scale. All other "scales" are modes of this scale with some pitches more important than others.
Any "major scale" is actually 12 notes(actually more). The first 7 notes of the scale are the most important(the tonic triad notes are even more important).
The key of C has the notes
C C# D D# E F F# G G# A A# B
If we arrange them in a matter of importance, more or less, then
(C G E) (D A F B) (A# G# C# D# F#)
The patterns on the guitar(All the skipping and stuff) is simply avoiding the avoid notes.
There are many ways to play the 7 main notes and you can extend them several octaves up the neck.
Scales are just patterns used to develop technique and some logical concept of melodies. Melodies and music are not scales.
When someone creates a cool melody from creativity they are not using a scale to do so but may use the scale to avoid hitting those "bad notes".
Ultimately you don't have to and don't want to rely on scales but want to just have the melodies flow out. In this case you will be using the chromatic scale simply because the guitar is a fretted instrument. Usually to get close to this goal you end up having to practice scales for both a technical aspect and to reduce complexity(after all, it's easier to visualize 7 note patterns than 12).
Note that a scale doesn't have to start and end on the tonic/root. Jazz players tend to end them on the 9th. It usually helps to tend them on the tonic since it solidifies the mode. If you resolve on a clunker it will sound bad, mainly because you are emphasizing something that clashes with the tonic area.
Scales help being able to play a pattern and sound halfway like you know what your doing if you play in the right key.
Before you learn your 7 note scales work on your 3 note scales(arpeggios) and 5 note scales(pentatonic). The reason is these scales are more important in practice than 7 note scales because they encode chord information better... and most of the time you'll be playing over chords. (a chord is just a pattern with all the notes played at the same time or arpeggiated)
e.g.,
If you are playing over a C chord then the first 3 notes you need to be able to call up instantaneously are C E G(The chord tones). After that you need to be able to call up any add tones(D A F B) which you can get from your pentatonic. e.g., C major pent over a C chord gives you the D and A tones(also known as a Cmaj6/9 chord) while G major pent over a G chord gives you your B D A extensions... but guess what? C major pent and G major pent are the same patterns!!!
So essentially by learning just one major arpeggio shape you can get all kinds of music from country to jazz. It would be very rudimentary at first but if you really worked on it, it would take you further than your avg guitarist.
e.g., Over a C major chord, The G major arpeggio gives you the G B D notes which allows you to get a major9 type of sound. Ab major arpeggio gives you the notes Ab C Eb, which gives you a sort of bluesy sound if you use it right. D major arpeggio gives the notes D F# A which gives you a Cmaj13 type of sound...
But realize, all these arpeggios (shapes) are the same. Just the basic triadic arpeggio (shape). There are just a few of these major triad arpeggio shapes on the guitar. The biggest drawback to the guitar is that the B string makes us learn 3 times as many shapes but it also is what allows us to play 3 times as many chords.
But if you play likes this, unless you happen to be very advanced at it, you'll sound quite a bit polytonal and as if you are playing in the wrong key in some instances. To be able to make it work you have to add more notes.
The C major arpeggio + the G major arpeggio = C E G + G B D which gives you your Cmaj9 sound... same as a above. But this time you can learn this as a pentatonic = C E G B D scale!!! By learning this pattern you'll consolidate your visualizing into larger chunks on the fretboard... But note, it's still simply a C major arpeggio and a G major arpeggio.
The basic idea here is that you have 12 notes to work with. Most of the time you will be using 3 to 5 note "patterns" since these are easy to remember. Since it is on the guitar, if you learn one pattern you basically learn 12 since you can use it in 12 different keys by just playing it at different places on the neck. A piano player doesn't have that ability, for example.
If you know two 5 note patterns you can combine them to form new patterns. If many cases you'll not end up with a 10 note pattern but something smaller due to the patterns overlapping. e.g., C major = C D E F G A B can be thought of as a C major 7 arpeggio + a G7add13 arpeggio = C E G B + G B D F A or a C major 9 arpeggio + F major 7 = C E G B D + F A C E...
Or, Cmajor6/9 + Dmin = C E G B D A + D F A. The first can be thought of as the pentatonic.
With all these choices it becomes a matter of using the right "pattern" to draw your melodic ideas from. Using the wrong pattern can sound bad/wrong or very cool. The main point to get from all this is that you have 12 notes to choose from but you have to break them down into manageable pieces and understand how those pieces fit together.
Comment: Geekkid has JUST started to learn theory.Major 7s and 9s or 6/9s are hardly beginner material.G7add 13 - G13 always has 7 in it !This answer is not particularly helpful to Geekkid - or most people !
Comment: I disagree. It was helpful to me. @Tim A G7add13 is more commonly known as a G7/6 chord and different from a G13 as it does not imply the 11th.
Comment: Down voted because there is quite a bit of incorrect information in this answer.
Comment: Are we really talking BEGINNER theory here?That's what the questioner was asking.To me, on guitar at least, G13 sounds better voiced with 7th and 6th and 9th only, leaving out 11th, but this is advanced theory.
Comment: @Uiy My music degree and EVERY book written on theory disagree with you.  As I said in the comment, YES, you CAN use other notes in C Major besides CDEFGAB, but they are NOT in the key.  They have other names and functions.  Some of these are: chromatic passing tones, chromatic neighbor tones, altered chord tensions, or as used in passing chords or the preparation for a modulation.

scales on the guitar


New content pane (in view) not showing up for adding to panel

Question: Added new content pane as part of my view. Even after saving, and clearing the cache, this pane is not showing up on the available panes list when adding content to Geary type panel/column in Drupal 7. Could this be a configuration issue?
Answer: Turns out you have to save prior changes to the panel in question. In the list of panels you'll see a padlock icon and a hover-caption of "you have locked this panel, until you save these changes."
Once you save the panel in question, you'll see new content panes that you've created in a View.


Por que o fetch está retornando uma promise e não os dados?

Question: Pessoal estou fazendo um fetch para pegar os dados de um JSON, porém a variável está ficando com o valor da promisse e não dos dados retornados.
var data = fetch('./data/data.json')
    .then((response) => response.json())
    .then(result => { return result; });

console.log(data);

Como eu poderia fazer para retornar os dados e não a promise?
Answer: Você está fazendo errado, exemplo de retorno json
fetch('./data.json')
  .then(response => {
    return response.json()
  })
  .then(data => {
    // Work with JSON data here
    console.log(data)
  })
  .catch(err => {
    // Do something for an error here
  })

ou seja, nesse código tem um método then tem um console.log(data) e o resultado que esperado, e não é o data que realmente é um promisse, no seu código:
var data = fetch('./data/data.json')
    .then((response) => response.json())
    .then(result => { console.log(result); });

a variável result é o retorno que precisa que vai trazer os dados do json.
Referencia: Doc. Usando Fetch
Como o usuário quer de resgatar o valor faça um callback function:
function res(data) {
    // utiliza o valor aqui ...
}

var data = fetch('./data/data.json')
    .then((response) => response.json())
    .then(result => { res(result); });

ou então async/await:
var data = await fetch('./data/data.json');
var result = await data.json();

se estiver dentro de uma função tem que colocar um async para resolver as promisses exemplo:
async function resultJson(){
    var data = await fetch('./data/data.json');
    return await data.json();
}

Referencia: Async And Await to the Rescue
Vale lembrar que tudo isso depende de como está implementando e também verifique a melhor forma de fazer para o seu contexto.
Comment: Virgilio Novic muito obrigado pela atençao, mas como eu jogo os dados para fora do escopo do fetch? A intenção seria que var data estaria em um escopo global.
Comment: respondido @user8811593 ...


Toolbars not showing in visual studio ultimate 12

Question: I have recently downloaded trial version of visual studio ultimate 12 it is working fine when i am coding but i can not view the toolbox which was there in visual studio 10 to drag and drop buttons ... and other controls .
Am i missing some thing ??
Answer: Ok i got it .
It came from the hot keys alt+ctrl+x.


Azure Cognitive Services - Face API Response: Reserved Fields or Bugs?

Question: In the Azure Cognitive Services Face API (see e.g. https://azure.microsoft.com/en-us/services/cognitive-services/face), the following response fields never seem to trigger:

headPose:pitch (reserved field)
foreheadOccluded
eyeOccluded

Am I misusing these, or is there a plan for them, or is there no plan to activate them?
Comment: PS Moderators: I know that this is service specific, but Azure is making use of stackoverflow for technical questions. Also: If the question is unclear, please suggest constructive improvements rather than simply downvoting. Thanks!
Answer: If you look at the API documentation here:

For the headPose, it says:

EDIT 13/06/2019: doc was saying

HeadPose's pitch value is a reserved field and will always return 0

Now changed to:

headPose: 3-D roll/yaw/pitch angles for face direction.

For the foreheadOccluded value, I successfully got true value in the following test, where there is a cap on the head (sorry for the sample, did not find anything else quickly!):

URL: https://westeurope.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=occlusion
Content sent: { "url": "https://www.knijff.com/markmatters/wp-content/uploads/2015/10/Trump-Red-Hat.jpg" }

Reply received:
[{
  "faceId": "e6ae42a6-b008-4859-9bf5-1ae22e4b71a7",
  "faceRectangle": {
    "top": 118,
    "left": 212,
    "width": 276,
    "height": 276
  },
  "faceAttributes": {
    "occlusion": {
      "foreheadOccluded": true,
      "eyeOccluded": false,
      "mouthOccluded": false
    }
  }
}]

For the eyeOccluded value, I successfully got true and false values in the following test where the same person appears 2 times, one with a rectangle over the eyes:

URL: https://westeurope.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=occlusion
Content sent: { "url": "https://jov.arvojournals.org/data/Journals/JOV/933685/i1534-7362-14-13-14-f09.png" }

Reply received (please note that 1st face is the right one):
[{
  "faceId": "4c2eb52e-2fd4-456c-bdae-694df1adc571",
  "faceRectangle": {
    "top": 204,
    "left": 683,
    "width": 297,
    "height": 297
  },
  "faceAttributes": {
    "occlusion": {
      "foreheadOccluded": false,
      "eyeOccluded": false,
      "mouthOccluded": true
    }
  }
}, {
  "faceId": "5b9dc938-e6cf-4fe9-8e6c-8649fef44e7a",
  "faceRectangle": {
    "top": 213,
    "left": 107,
    "width": 275,
    "height": 275
  },
  "faceAttributes": {
    "occlusion": {
      "foreheadOccluded": false,
      "eyeOccluded": true,
      "mouthOccluded": false
    }
  }
}]

Comment: Yes, good point! the doc says now `headPose: 3-D roll/yaw/pitch angles for face direction.`. Will edit my reply
Comment: Nicolas R - looks like headPose pitch can now be non-zero?! :) They don't really advertise such facts very well....


how to hide and display a menu using javascript?

Question: this is a menu item i need to display the menu only when browserName='mybrowser' otherwise i need to hide the menu. please help me how to hide and DISPLAY the menu? i m using a javascript code for checking the condition.

HOSTING SERVICES

PRICE MATCH

IRC/UNIX

SUPPORT

ABOUT SANTREX

Comment: Why aren't you using CSS for this?
Answer: Code to hide menu:
document.getElementById('ddtopmenubar').style.display = 'none';

Code to display menu:
document.getElementById('ddtopmenubar').style.display = 'block';

Answer: Detecting browser:
var isOpera = !!(window.opera && window.opera.version);  // Opera 8.0+
var isFirefox = testCSS('MozBoxSizing');                 // FF 0.8+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    // At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !isSafari && testCSS('WebkitTransform');  // Chrome 1+
var isIE = /*@cc_on!@*/false || testCSS('msTransform');  // At least IE6
        if(isIE==true)//If IE, change it to any other as per need
        document.getElementById('ddtopmenubar').style.display = 'none';

Each test is fully independent of the other one, except for the Safari-Chrome test. To detect Chrome in a reliable way, you have to exclude Safari, since both share the webkit prefixes. But, if you only want to know whether the user is using Chrome 15+, the following can also be used:
 var isChrome = !!(window.chrome && chrome.webstore && chrome.webstore.install);

Fiddle here : http://jsfiddle.net/9zxvE/9/
or if you don't need browser detection
if( browserName='mybrowser' )
 document.getElementById('ddtopmenubar').style.display = 'none';

Comment: Question is about showing and hiding menu in javascript and not detecting browser.
Answer: See Demo: http://jsfiddle.net/rathoreahsan/cQPtk/2/
Javascript:
    var mybrowser = navigator.appName;

    if (mybrowser == 'Netscape') /* Change browser name accordingly */
        { document.getElementById('ddtopmenubar').style.display = 'block' }
    else
        { document.getElementById('ddtopmenubar').style.display = 'none' }

Answer: document.getElementById('ddtopmenubar').style.display = 'none';
document.getElementById('ddtopmenubar').style.display = 'block';

Answer: Use jQuery.
Here's one way to do it:
http://jsfiddle.net/S8rtj/
Comment: `jQuery !== Javascript`, otherwise, with type coercion, jQuery will probably equal javascript nowadays :D
Comment: `jQuery != JavaScript` OP said nothing about jQuery.
Comment: @anonymousdownvotingislame Of course jQuery is JavaScript; what else would it be? C++? PHP? Plus, OP never said *not* to use jQuery either. By your logic we should never use any libraries or third-party code what so ever.


Adicionar vários produtos em um sessionStorage

Question: Eu adiciono o produto através de um select, mas quando eu tento adicionar outro ele apaga o que está no sessionStorage atual. Como que eu faço para adicionar os dois?
Tenho o select em html que traz o produto, e quando é clicado ele adiciona o seguinte conteúdo:
$('#produto_pedido').on('change', function()
{
filterLimit++;
let id_produto = $('#produto_pedido option:selected').val();
let nome_produto = $('#produto_pedido option:selected').text();
let itemHTML = "";

$('.btn-finalizar-pedido').css('display','none');
$('.produto_selecionado').css('display','block');

itemHTML += "
Informações do Produto
";
itemHTML += "<input type='hidden' name='id_produto' id='id_produto' value='"
 + id_produto + "' />";
itemHTML += "
";
itemHTML += "Nome do Produto*";
itemHTML += "";
itemHTML += "
";
itemHTML += "<input type='text' name='nome_produto' id='nome_produto'
placeholder='Digite o nome do produto' class='form-control' value='" +
nome_produto + "' readonly/>";
itemHTML += "
";
itemHTML += "
";

$('.produto_selecionado').html(itemHTML);

});

 /*depois quando clica no botão salvar ele grava no session storage*/

$(document).on("click", ".btn-salvar-produto-pedido", function () {

 let produto_pedido = $('#produto_pedido').val();
let frete_pedido = $('#valor_frete').val();
let comprimento_pedido = $('#comprimento_pedido').val();
let largura_pedido = $('#largura_pedido').val();
let espessura_pedido = $('#espessura_pedido').val();
let novo_preco_produto = $('#preco_produto_pedido').val();
let quantidade_pedido = $('#quantidade_pedido').val();
let nome_produto = $('#produto_pedido').find(':selected').text();
let preco_produto = $('#produto_pedido').find(':selected').attr('data-preco-
 produto');
let produtosArray = "";

if (quantidade_pedido == '')
{
$('.pedido-alert-error').css('display','block');
$('.pedido-alert-error .mensagem-erro').html('Quantidade é obrigatória');
 }
  else
   {
  if (novo_preco_produto == '')
  {
  novo_preco_produto = 0.00;
  }

let objeto = [];
let obj = new Object();

obj.id_produto = produto_pedido;
obj.quantidade = quantidade_pedido;
obj.comprimento = comprimento_pedido;
obj.largura = largura_pedido;
obj.espessura = espessura_pedido;
obj.novo_preco = novo_preco_produto;
obj.preco_produto = preco_produto;
obj.nome = nome_produto;

objeto.push(obj);

produtosArray = JSON.stringify(objeto);
sessionStorage.setItem('dadosproduto', produtosArray);

alert('Produto salvo com sucesso. Você pode finalizar o pedido');
$('.btn-finalizar-pedido').css('display','block');
$('.produto_selecionado').hide();

}
});

Answer: Do jeito que está o seu código você sobrescreve o array de objetos sempre que salva um produto.
Você tem que verificar se já existe produtos no sessionStorage e se já tiver recuperar o array de produtos.
Segue o trecho que você deve modificar:
let objetos = [];
//caso já existam produtos na sessao
if(sessionStorage.getItem('dadosproduto')) {
    objetos = JSON.parse(sessionStorage.getItem('dadosproduto'));
}
//continuação do seu código
let obj = new Object();
...

Outra forma de fazer é já criar a variável object de acordo com a existência da chave dadosproduto na sessão.
let objetos = sessionStorage.getItem('dadosproduto') || [];


How do you know from what population a sample comes?

Question: My question is say you take a sample say of people weight and you get in pounds right [100,220,230,240] many people say this sample come from a normal distribution population.
But my question is from a sample how does you tell that it belong to a certain population???
Comment: You can't. People who claim to know that this comes from a normally distributed population don't have much of a clue (unless you're misrepresenting what they actually say).
Comment: I think that the role of model assumptions is routinely misinterpreted in statistics. The theory requires model assumptions. In practice these are never precisely fulfilled. An important question is whether there is anything in the data or any knowledge of how they were collected that gives an indication that the confidence interval will be invalid. This is what we can know, we can't know more. (Meaning that there's always a chance that there is a problem that we miss.)
Comment: Some answers of mine related to this: https://stats.stackexchange.com/questions/518183/how-to-answer-critiques-about-the-inapplicability-of-the-framework-of-frequentis/518454#518454 https://stats.stackexchange.com/questions/162738/confidence-interval-from-a-non-probability-sample/503112#503112
Comment: but dont you need to assume then that your sample comes from a normal distribution to build a confidence interval?
Comment: Weight may just be an arbitrary example but weight distributions for large groups tend to be skewed positively. As is well known, very low and high weights both come with health risks, including higher death rates, but the situation isn't symmetrical even.
Comment: If you have no further information, there's no way. You'd need an infinitely-sized sample for that. However if you are working with a limited set of options (for example, if you know your data follows some normal distribution), then you can use your data to narrow the options down
Answer: Suppose you have little information, from the sample or the context in which it was sampled, about nature of the population. Then you might want to try one of several kinds of nonparametric bootstrap confidence intervals.
Suppose you have $n = 20$ observations in a vector x in R
with summary statistics and boxplot as shown below.
summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   3.00   13.50   25.50   30.00   51.25   60.00
boxplot(x, col="skyblue2", horizontal = T)

The data are moderately right-skewed. One indication is that the median is closer to the minimum than to the maximum. Maybe the skewness is a little more than we would expect from normal data. Also, points in a normal probability plot seem more curved than linear.
qqnorm(x);  qqline(x, col="blue")

Assume normal data, use t confidence interval. If we are willing to guess that the data were sampled from a normal population, then a 95% t confidence interval for the population mean $\mu$ [from the procedure t.test in R] is $(20.4, 39.6).$
t.test(x)$conf.int
[1] 20.41577 39.58423
attr(,"conf.level")
[1] 0.95

Nonparametric bootstrap confidence intervals. This is not the place for a detailed explanation of bootstrapping. But the general idea is to take a moderately large number of 're-samples'
of size $n=20$ with replacement from x in order to assess
the variability of the mean of x and thus to make a 95% nonparametric bootstrap. (Here, the word nonparametric means that we have
made no assumptions about the shape of the population distribution. We do assume that the population distribution has a mean $\mu.)$ One simple style of a bootstrap CI (shown below) gives the interval $(21.5, 38.6).$
For many practical purposes it would not make much difference which
95% CI is used. [Because re-sampling is a random process, results of the bootstrap CI differ slightly from one run to the next---unless the same seed is set. Two additional runs gave $(21.4, 38.2)$ and $(21.1, 38.5)$.]
set.seed(1234)
a = replicate(2000, mean(sample(x,20,rep=T)))
quantile(a, c(.025, .975))
    2.5%    97.5%
21.49875 38.55375
hdr = "Bootstrap Dist'n of Sample Means"
hist(a, prob=T, col="skyblue2", main=hdr)
 abline(v = c(21.50,38.55), col="red",
        lwd=2, lty="dotted")

Note: There are better styles of bootstrap CIs--- especially if the bootstrap distribution shown above were markedly skewed. Another style of bootstrap results from re-sampling deviations from the sample mean, as shown below. The
result is $(21.4, 38.9);$ again not very different from
the previous CIs.
a.obs = mean(x)
set.seed(614)
d = replicate(2000, mean(sample(x,20,rep=T))-a.obs)
LU = quantile(d, c(.975, .025))
a.obs - LU
   97.5%     2.5%
21.45000 38.90125

Note on data: The data used in the discussion above were sampled in R
as shown below. If we knew that the population distribution is gamma, then a parametric CI based on the particulars
of that family would be preferable. The true population mean is $\mu = 30.$
set.seed(2021)
x = round(rgamma(20, 3, 1/10))


Developing TypeScript without an installed IDE or editor

Question: I work in a place that restricts me from downloading and installing any applications, regardless of job roles. I have several web apps that I want to migrate to Angular 2 with TypeScript. I'm a C# developer in my own time and TypeScript is very appealing as it's statically typed and just compiles down to JavaScript.
How can I develop with TypeScript without having access to an installed IDE or code editor? Are there any online environments that allow the use of TypeScript definition files that provide code help/intellisense?
Answer:
How can I develop with TypeScript without having access to an installed IDE or code editor

I am hoping you can do npm install typescript. If you can just run npm install typescript -g and then run typescript as tsc -w -p tsconfig.json in your code directory. This will allow you to run the compiler in the background leaving you free to use even notepad if you have to.
Alternatively you can just download the zip file from : https://github.com/Microsoft/TypeScript/releases and if you have node you can run node ./bin/tsc etc from the extracted directory.
Comment: Sadly command prompt is even restricted here. I work as a developer in a call center, and all the group policies for the usual phone rep are also applied to myself and coworkers. The same goes for running any non-whitelisted applications. Thank you for your answer though.
Answer: You can try the playground: http://www.typescriptlang.org/Playground
Although it doesn't allow references to other files.
Answer: Use Codenvy:
It needs some manual tweaks but somebody figured them out already: https://groups.google.com/a/codenvy.com/forum/#!topic/codenvy/R4myXA9MygA


RecyclerView first and last item are changed, when clicking only one

Question: I'm using a recyclerview to display a list of interests one could choose from. Clicking the very first item makes the very last item also selected
Selecting first item:

Last item is also selected:

The selection is done with this code:
@Override
public InterestViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    TextView v = (TextView) LayoutInflater.from(parent.getContext())
            .inflate(R.layout.interests_textview, parent, false);
    v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView textView = (TextView) v;
            if (textView.getCompoundDrawables()[2] == null) {
                textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.checkmark, 0);
            } else {
                textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            }
        }
    });
    return new InterestViewHolder(v);
}

Also the very first item is also selected, when clicking the very last item.
Who knows what could cause this?
Comment: can you share your item xml with adapter
Comment: Have you found the solution? I'm struggling with the same issue...
Answer: You are inflating a layout into a TextView. Change it to View v and it should work:
View v = LayoutInflater.from(parent.getContext())
        .inflate(R.layout.interests_textview, parent, false);

Also you need to use findViewByID() in order to get the correct TextView from your layout:
Instead of
TextView textView = (TextView) v;

Do this:
TextView textView = findViewById(<id of your textview in the layout>);

Casting the View to a TextView is not what you want to do.
Comment: None of your tips were helpful, i'm afraid to say. But i did manage to resolve this issue, by just saving the click state in an object, then checking the status (chosen/not chosen) in onBindViewHolder.

The root cause of this issue was that RecyclerView had recycled the view and hence added a checkmark on the next recycled item.
Comment: Your castings definitely are not 100% correct, but if you found a solution, you could write an answer to our own question and later accept it. This will help the next user with a similiar problem. I then will delete my answer, so your comment wont be lost until then.
Answer: I have a Checkbox to select items and the following String Arrays
data : holds all my items
checkedData: holds all checked items
To solve this try editing the onBindViewHolder(holder , position)
 @Override
public void onBindViewHolder(@NonNull ProgrammminViewHolder holder, int position)
{

    String title =data[position];
    holder.textTitle.setText(title);

    //logic to solve first and last (multiple) selection issue
    CheckBox chk = holder.chk;
    String current  = data[position];
    chk.setChecked(false);
    for(String st : checkedData){
        if(st.equals(current)){
            chk.setChecked(true);
        }
    }

    holder.setItemClickListener(new ItemClickListener()
    {
        @Override
        public void onItemClick(View v, int pos)
        {
            //here analomay occured 19:36 Custom Reycler view CheckBoxes | anomaly is now cleared.
            CheckBox chk = (CheckBox) v;//.findViewById(R.id.chk);

            if(chk.isChecked())
            {
                   checkedData.add(data[pos]);
            }else if(!chk.isChecked())
            {
                checkedData.remove(data[pos]);
            }

        }
    });
}

Explanation
What it will do is every time the data gets binded to holder in onBindViewHolder you previously uncheck the checkbox and then check if the corresponding string of that holder is present in checkedData array if yes set checkBox to true.


How can I send direct input to games, specifically Roblox, using Python?

Question: I've been trying to use Python to send inputs to Roblox, but to no avail. What I know so far is that Roblox requires DirectInput, as most games do.
I've seen people successfully send keystrokes, but haven't seen any example of mouse movements or mouse clicks; to complete my goal, I need to be able to move the mouse, send clicks, as well as keyboard inputs, to an active Roblox window.
I'm currently using Python 3.9, if that's of any help.
Answer: i believe PyDirectinput works to click Roblox
<code>import pydirectinput

pydirectinput.click()
</code>


Form custom with method GET remove form_build_id and op from GET variables

Question: If I create a custom form with get method:
$form['#method'] = 'get';

When I click the submit button, many variables are populated with GET
Can I remove them cleanly according to the drupal logic?
Answer: You need to alter the form after it has been built, for example
$build = [];
$build['filter'] = $this->formBuilder->getForm(LibrarySearch::class);
$build['filter']['form_id']['#access'] = FALSE;
$build['filter']['form_build_id']['#access'] = FALSE;
$build['filter']['form_token']['#access'] = FALSE;

Once the form has been turned into a render array, you can set the access to FALSE for those items. This is also documented in the core Search module.
Answer: For me, unsetting inside form_alter didn't work. I had to do it in a different way.
Add this inside form_alter hook.
  $form['#after_build'][] = 'function_name';

Later add a separate function and unset inside that.
function function_name($form){

  // Unset variables to cleanup the url after submission
    unset($form['form_token']);
    unset($form['form_build_id']);
    unset($form['form_id']);
    return $form;
  }

Answer: Another way to solve this problem.
Implement a hook form alter in your corresponding module in the
[name_of_your_module].module file, just add
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Need to don't see the parameters 'form_build_id' and 'form_id' in the url.
 */
function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  unset($form['form_build_id'], $form['form_id']);
}

Answer: Needs to alter the form to unset  form_id and form_build_id. In bellow code formid is the id of the form where you want to remove form_id and form_build_id.
function mymodule_form_formid_alter(&$form, &$form_state, $form_id) {
unset($form['form_build_id'], $form['form_id']);
}


Sort the entity obtained from the Query class with values from the Statistics module

Question: I am using the following code to sort the published nodes basing on the value stored from the Statistics module.
$query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->range(0, 5)
      ->sort('totalcount', 'DESC' );

$result = $query->execute();

The code is causing the following exception.

Drupal\Core\Entity\Query\QueryException: 'totalcount' not found in Drupal\Core\Entity\Query\Sql\Tables->ensureEntityTable() (line 316 of core/lib/Drupal/Core/Entity/Query/Sql/Tables.php).

How do I sort nodes basing on the totalcount value stored from the Statistics module?
Answer: The code you are showing doesn't work because totalcount is not a Node property the node entity. That is a value saved in a different database table, not used from the Node entity. See statistics_get(), which retrieves the value you are looking for.
if ($nid > 0) {
  // Retrieve an array with both totalcount and daycount.
  return db_query('SELECT totalcount, daycount, timestamp FROM {node_counter} WHERE nid = :nid', array(':nid' => $nid), array('target' => 'replica'))->fetchAssoc();
}

Since the entity query doesn't allow to join tables, you need to:

Add a tag to the entity query you are using
Implement hook_query_TAG_alter() to alter the queries with the tag you added (Replace TAG with the tag you added to the entity query)

node_query_node_access_alter() is the implementation of that hook done from the Node module to allow an entity query to return just the nodes the currently logged-in user has access. You can use its code as guide to write your own implementation.
For example, I would start trying with the following code.
The code for the query
$query = \Drupal::entityQuery('node')
  ->addTag('statistics_totalcount')
  ->condition('status', 1)
  ->range(0, 5)
  ->sort('totalcount', 'DESC');

$result = $query->execute();

The hook implementation
function mymodule_query_stastics_totalcount_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  $query->join('node_counter', 'nc', '%alias.nid = n.nid');
}

Answer: In case this helps anyone else, for me, I had to move the sort clause into the hook_query_TAG_alter() function because of a validation issue on the entity query object.
$query->leftJoin('node_counter', 'nc', '%alias.nid = node_field_data.nid');
$query->orderBy('totalcount', 'DESC');


Upload e Download de arquivos - Open source

Question: Alguém tem um sistema de upload e download de arquivos open source?! Um que de pra manipular os arquivos, como por exemplo separando-os por pastas, movendo-os para outras pastas, etc...
Answer: Da uma olhada nesse plugin:
CKFinder
Aparentemente, esse é o mais completo, porém ele é premium, o que eu utilizo é o FileRun, mas é meio chato pra fazer ele rodar:
FileRun


Remove jquery script

Question:
Possible Duplicate:
How do I update jQuery to the latest version I can download?

In Firefox I get an unresponsive script error from Google hosted jquery but can't echo the problem on other browsers.
I just looked at the source of drupal and it's loading v1.4 of jquery automatically. I applied my own Google Hosted link to jquery v1.8 in html.tpl.php so in  the page is loading 2 versions of jQuery.
I think this could be the reason for the crash. In any case, I still want to remove the redundant script.
How would I go about removing the the automatically added jquery script? I want to print $scripts as some modules have dependents there.
Comment: No i don't want to update Drupal jquery. I want to use google hosted jquery so I want to remove core's output of jquery script in the header.
Comment: Make sure you read the linked answer fully, it'll tell you how to remove the core jquery files
Answer: You should use jQuery Update module. Here is a quote about it (from the module's project page):

Upgrades the version of jQuery in Drupal core to a newer version of jQuery.
Updates:

Drupal 5 to jQuery 1.2.6
Drupal 6 to jQuery 1.3.2
Drupal 7 to jQuery 1.5.x, 1.7.x, 1.8.x, 1.9.x, 1.10.x and jQuery UI 1.10.2
Drupal 8: TBD

Remove jquery script


Erro no retorno do Cursor Android

Question: public boolean insertData( int id_item, String nome, int quantidade) {
    String preco_unitario = "0";
    String id_pedido = "0";
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    String sql1  = "SELECT MAX(id) AS id FROM "+ TABLE_PEDIDO ;
    Cursor cursor1 = db.rawQuery(sql1, null);
    if(cursor1.getCount() > 0) {
        id_pedido =    cursor1.getString(cursor1.getColumnIndex(COL_0_PEDIDO));
    }
    contentValues.put(COL_1_ITEM_PEDIDO, id_pedido);
    contentValues.put(COL_2_ITEM_PEDIDO, id_item);
    contentValues.put(COL_3_ITEM_PEDIDO, nome);
    contentValues.put(COL_4_ITEM_PEDIDO, quantidade);
    String sql2 = "SELECT preco FROM " + TABLE_PRECO + " WHERE id_item = " + id_item;
    Cursor cursor2 = db.rawQuery(sql2,null);
    cursor2.moveToFirst();
    if(cursor2.getCount() > 0){
        preco_unitario = cursor2.getString(cursor2.getColumnIndexOrThrow(COL_3_PRECOS));
    }
    double total = quantidade * Double.parseDouble(preco_unitario);
    contentValues.put(COL_5_ITEM_PEDIDO, preco_unitario);
    contentValues.put(COL_6_ITEM_PEDIDO, total);
    long result = db.insert(TABLE_ITEM_PEDIDO, null, contentValues);
    if (result == -1) {
        return false;
    } else {
        return true;
    }

Está dando um erro nesta parte:
if(cursor1.getCount() > 0) {
    id_pedido =    cursor1.getString(cursor1.getColumnIndex(COL_0_PEDIDO));
}

Mensagem de erro:

android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
Answer: Quando usar um cursor deve primeiro testar se ele não é nulo e depois testar se tem registos ao mesmo tempo que o move para o primeiro.
Por outro lado, o cursor resultante de
String sql1  = "SELECT MAX(id) AS id FROM "+ TABLE_PEDIDO ;
Cursor cursor1 = db.rawQuery(sql1, null);

tem apenas um registo com uma coluna do tipo int.
A melhor forma de obter o valor dessa coluna é usar cursor1.getInt(0);
Note que o erro se deve a cursor1.getColumnIndex(COL_0_PEDIDO) estar a retornar -1.
Altere essa parte do código para:
if (cursor != null){
    if(cursor.moveToFirst())//Move para o primeiro

        id_pedido = cursor1.getInt(0));

    }
}

Declare id_pedido como int:
int id_pedido;

Comment: Compreendi. É realmente esse valor que está retornando da query é um int  que seria o ID. Muito obrigado pela colaboração.
Answer: Faltou mover o cursor para o primeiro item, como você fez com o cursor2.
cursor1.moveToFirst()

Comment: Acabei de observar isso. Muito obrigado.
Comment: Celso, na verdade seria:
    cursor1.moveToLast();
Pois eu preciso do ultimo ID, dessa forma, ja mando o cursor para o ultima linha. De qualquer forma, muito obrigado pela ajuda.

Erro no retorno do Cursor Android


Equality of times blocks of size $k$ appear in a partition with the number of distinct parts appearing $\geq k$ times?

Question: I've been reading up on combinatorics in my spare time recently. Suppose $\lambda$ is a partition of $n$, and $f_k(\lambda)$ the number of times that $k$ appears as a part of $\lambda$. Also, let $g_k(\lambda)$ be the number of distinct parts of $\lambda$ which occur at least $k$ times in $\lambda$. Why is it that $\sum f_k(\lambda)=\sum g_k(\lambda)$ for fixed $k$, if we let the sums run over all partitions $\lambda$ of a fixed $n$?
I think the general idea is that for any partition $\lambda$ of $n$, and any part $p$ occurring at least $k$ times, one needs to associate some partition $\delta$ of $n$ so that the total number of times given $\delta$ occurs is the same as the number of parts of $\delta$ which are equal to $k$. Is there a way to flesh this out? Thank you.
Comment: I don't understand.  Did you mean to write "$f_k(\lambda)$ is the number of times a *block of size* $k$ appears in $\lambda$?"  (I don't see how $k$ itself can appear more than once in a given partition.)
Comment: @williamdemeo Yes, I mean it in that sense. For example, taking $n=13$ and $k=3$, then for the partition $\lambda=(1,1,2,3,3,3)$, I would say $f_3(\lambda)=3$.
Comment: Oh, okay.  I was thinking of partitions of an $n$-element set; e.g. for $n=3$, $\lambda = |0|1,2|$ is a partition.
Comment: Your second paragraph doesn't read well. The number of distinct combinations $(\lambda,p)$ should equal the total number of occurrences of $k$, so "so that the total number of times given $\delta$ occurs is the same as the number of parts of $\delta$ which are equal to $k$" should be just "and an occurrence of a part $k$ in $\delta$".
Answer: For convenience let $$F_k(n)=\sum_{\lambda\vdash n}f_k(\lambda)\;\text{ and }\;G_k(n)=\sum_{\lambda\vdash n}g_k(\lambda)\;.$$ I'm pretty sure that it can't be done by pairing up partitions of $n$. However, I can show that $$F_k(n)=F_k(n-k)+p(n-k)\tag{1}$$ and $$G_k(n)=G_k(n-k)+p(n-k)\tag{2}\;,$$ from which the result follows by induction.
$(1)$ is fairly easy. If $\lambda\vdash n$ has a part $k$, removing that part leaves a partition $\lambda'\vdash n-k$, and clearly $f_k(\lambda)=f_k(\lambda')+1$. If $\lambda\vdash n$ has no part $k$, then $\lambda$ does not contribute to $F(n)$. Thus, $$F_k(n)=\sum_{\begin{array}{}\lambda\vdash n\\k\in\lambda\end{array}}f_k(\lambda)=\sum_{\begin{array}{}\lambda\vdash n\\k\in\lambda\end{array}}\Big(f_k(\lambda')+1\Big)=F_k(n-k)+p(n-k)\;.$$
$(2)$ is a little harder. Start with a partition $\lambda\vdash n-k$, and let $\lambda'$ be the partition of $n$ obtained by adding $k$ $1$-parts to $\lambda$; every partition of $n$ with at least $k$ $1$-parts is obtained in this way, so there are $p(n-k)$ partitions of $n$ with at least $k$ $1$-parts. To put it a little diffently, $1$-parts contribute $p(n-k)$ to $G_k(n)$.
Now suppose that $\lambda\vdash n$ has at least $k$ $r$-parts, where $r>1$. Let $\lambda_r'$ be the partition of $n-k$ obtained by subtracting $1$ from each of $k$ $r$-parts of $\lambda$; clearly $\lambda_r'$ has at least $k$ $(r-1)$-parts. Conversely, if $\lambda\vdash n-k$ has at least $k$ $s$-parts for some $s\ge 1$, the partition $\lambda_s^*\vdash n$ has at least $k$ $(s+1)$-parts. It follows that for $r>1$, the contribution of $r$-parts to $G_k(n)$ is equal to the contribution of $(r-1)$-parts to $G_k(n-k)$ and hence that the total contribution to $G_k(n)$ of $r$-parts for all $r>1$ is $G_k(n-k)$. Putting the pieces together yields $(2)$.
To get the induction started, note that $G_k(k)=1=F_k(k)$, via the partitions $1+\dots+1$ and $k$, respectively, and of course $G_k(n)=F_k(n)=0$ if $k>n$.


Differential Equation Word Problem involving y=Ce^(xk) (y=y')

Question: "The rate of change of y is proportional to y. Write and solve the differential equation that models the verbal statement."
This part of the problem is easy. My work is such:
$y'=ky$
$\frac{dy}{dx} = ky$
$dy = ky dx$
$\frac{dy}{y} = k dx$
Then by integrating, I get:
$y = e^{kx + c}$, where $c$ is some constant
Which can also be written as:
$y = e^{kx} e^c$
$y = ce^{kx}$
The next part is rather confusing though:
"Use this statement to find the value of y when x=10, if it satisfies when x=0, y=2, and when x=4, y=8"
How can you find a particular solution of this differential equation when you are missing information about c, k, and y? If it helps, I just started Calculus 2.
Thank you for your time in advance.
Comment: Try putting $x=0$ into your equation $y = ce^{kx}$. Since $y=2$ then you get $c$.  You now have one of the two constants.  Do you see what to do with $x=4, y=8$?
Answer: Seeing as you have the data points (0,2) and (4,8) your only real unknowns are c and k. The fundamental theorem of algebra says that we need two equations in order to solve for these 2 unknowns. Even Without knowing that you can see:
2 = cek * 0
2 = c
plugging in this as well as (4,8) to the equation yields:
8 = 2*e4k
e4k = 4
ln4 = 4k
k ≈ 0.345
from here now that all of our values are solved for plug in (10,y)
y = 2e0.345 * 10
y ≈ 63
Done!
EDIT: I want to mention that the points (0,2) and (4,8) are conditions for the equation and not something the question wants you to show. Without them you wouldn
't have enough information to solve
Answer: We are told that when $x=0, y=2$ so $2=c e^{0} \Rightarrow c=2$. In addition, we are given that when $x=4, y=8$, so we have $8=2e^{4k} \Rightarrow k=(\ln 4)/4$. The $y$ value you want when $x=10$ can now be figured out:
$$y=2 e^{10\frac{ \ln 4}{4}}=64$$
Comment: I thought the question was to plug in x=10 to the equation first, and then to see if x=0, y=2 and x=4, y=8 would satisfy the equation.
Comment: From what I understood, they wanted the y value when $x=10$ given that the equation satisfied the two other conditions. I'm not sure what you mean though. Could you explain please?
Comment: Nevermind. I thought about what I just said and it's totally nonsensical. I guess the way my professor wrote the question just confused me a bit. I appreciate your help.
Comment: Yup, I agree. The wording was a bit confusing! You're welcome. :-)


How many of the NFL tiebreakers have actually been used?

Question: The NFL has a long list of tie-breaking procedures. There are seven separate lists of rules depending on possible tie situations. However, it seems incredibly unlikely that two teams would have:

Tied head-to-read records
Equal win-loss-tie percentages within their division
Equal win-loss-tie percentages against common opponents
Equal win-loss-tie percentages within their conference
Equal strength of victory
Equal strength of schedule
And other identical statistics

How many of the NFL tiebreakers have actually been used to break a tie?
Answer: The first, and only, case of a tiebreaker deciding a playoff spot prior to the AFL-NFL merger was a notable one. In 1967, the Baltimore Colts entered the final week of the regular season at 11-0-2, trying to become the first team to go undefeated since the 1929 Green Bay Packers. However, they had to travel to Los Angeles to face the 10-1-2 Rams, their Coastal Division rival. The Rams won that game, and the tiebreaker, on net points scored in the two head to head matchups, and advanced to the playoffs. The Colts, despite tying for best record in the league, stayed home.
In Divisional tiebreakers, five three way ties have been used. Four were determined affirmatively by head to head record (that is, one team had either a 3-1 or 4-0 record combined against the other two), and one, the AFC East in 2002, was determined in the negative by kicking out Miami based on division record (2-4 versus 4-2 for both the Jets and Patriots).
Virtually all the divisional tiebreakers have been decided by either head to head, division record, or conference record, with head to head being the most common.
I hope this helps :)
http://www.pro-football-reference.com/blog/?p=976


Dedicate every element in a list to a variable

Question: So let's say we have the lists a = [1,2,3,4] and s = ["q", "w", "e", "r"].
I want to dedicate every element in s a value in a, so that print(w) prints 2 and so on. You could write
for u in range(0, len(a)):
   s[u] = a[u]

But here print(w) makes no sense and we get an error.
Comment: use a `dict` to map elements as you want!
Answer: A dict does exactly this:
In [1261]: d = dict(zip(s, a))

In [1262]: d
Out[1262]: {'e': 3, 'q': 1, 'r': 4, 'w': 2}

To get the value associated with e, simply use dict indexing:
In [1263]: d['e']
Out[1263]: 3

Answer: The following solution does exactly what you have specified, using the built-in exec() function. However, you should never ever ever use it! It is hideously unsafe, and I am only posting it for completeness' sake. Use the solution after it instead.
for i in range(len(s)):
    exec(s[i] + "=" + str(a[i]))

What you should do is use a dictionary:
myDictionary = dict(zip(s, a))

What this does is it matches each element of the lists s and a into key-value pairs in a dictionary by their index (meaning that they are matched based on their order).
And then you can do:
>>> print(myDictionary["w"])
2


Show that $A$ is a closed $^*-$subalgebra of $l^\infty(T)$.

Question:
Let $A\subset l^\infty(T)$ be the subalgebra consisting of those functions $f:T\rightarrow \mathbb{C}$ such that the function $t\rightarrow f(e^{it}), t\in \mathbb{R}$ has left and right limits at each point of $\mathbb{R}$. Show that $A$ is a closed $^*-$subalgebra of $l^\infty(T)$.

I proved that  $A$ is a $^*-$subalgebra. To prove it is closed I took a sequence $f_n$ in $A$ such that it converges uniformly to $f$ in $T$. So let $t_0\in \mathbb{R}$. Let $\lim_{t\rightarrow t_0^+} f_n(e^{it})=F_n$. Then $\lim_{t\rightarrow t_0^+} f(e^{it})=\lim_{t\rightarrow t_0^+} (\lim_{n\rightarrow \infty}f_n(e^{it}))=\lim_{n\rightarrow \infty}(\lim_{t\rightarrow t_0^+} f_n(e^{it}))=\lim_{n\rightarrow \infty}F_n$. But now how do we know that $\lim_{n\rightarrow \infty}F_n$ exists? Any help is appreciated.
Comment: For $f\in A$ and $t_0 \in \mathbb{R}$, you have $\lvert \lim_{t\to t_0^+} f(e^{it})\rvert \leqslant \lVert f\rVert_{l^\infty(T)}$.
Comment: Ok, that means $F_n's$ are bounded. But boundedness does not gurantee convergence.
Comment: More than that. It implies that $(F_n)$ is a Cauchy sequence.
Comment: Sorry I am confused. Can you please elaborate?
Comment: Or else can I go with a convergent subsequence of $(F_n)$?
Answer: There are many ways to prove that $A$ is closed. Along the lines you started on, note that for every fixed $t_0 \in \mathbb{R}$, the map
$$L_{t_0} \colon A \to \mathbb{C};\quad f \mapsto \lim_{t \to t_0^+} f(e^{it})$$
is a continuous linear form with $\lVert L_{t_0}\rVert = 1$. Continuous linear forms are uniformly continuous (even Lipschitz continuous), so they map Cauchy sequences to Cauchy sequences.
In your situation, the sequence $(f_n)$ is a Cauchy sequence in $A$, and hence the sequence $(F_n)$ is a Cauchy sequence in $\mathbb{C}$. Note however, that the interchange of the limits
$$\lim_{t\to t_0^+} \biggl(\lim_{n\to\infty} f_n(e^{it})\biggr) = \lim_{n\to\infty}\biggl(\lim_{t\to t_0^+} f_n(e^{it})\biggr)$$
requires a justification.
Another way is to show that the complement of $A$ is open. If $f \in l^\infty(T)\setminus A$, then by definition, there is a $t_0\in \mathbb{R}$ such that the left- or right-hand limit of $f(e^{it})$ at $t_0$ doesn't exist. Without loss of generality, assume the right-hand limit doesn't exist. And without loss of generality, assume that the right hand limit of $\operatorname{Re} f(e^{it})$ doesn't exist. Then
$$\delta := \limsup_{t \to t_0^+} \operatorname{Re} f(e^{it}) - \liminf_{t\to t_0^+} \operatorname{Re} f(e^{it}) > 0.$$
Now look at the ball with radius $\delta/3$ and centre $f$ to see that $f \notin \overline{A}$.
Comment: Can I say that the interchange of limits is valid since $f_n$ converges uniformly?
Comment: If you can refer to a proof of that fact (earlier in the course/book, in some other course you took/book you read), then that's okay. If you don't have a reference to a proof, you should prove it. But the argument is indeed that the uniform convergence justifies the interchange.


How to get one value from a Codable struct with multiple values?

Question: I have a large JSON response and inside
{
    "availabilityResultList": [
        {
            "availabilityRouteList": [
                {
                    "availabilityByDateList": [
                        {
                            "originDestinationOptionList": [

there are 3 separate
 "originDestinationOptionList": [
    {
    "fareComponentGroupList":[...]
    },
    {
    "fareComponentGroupList":[...]
    },
    {
    "fareComponentGroupList":[...]
    },
],

I can access the values in the first 'fareComponentGroupList' with Codables
as
root.availabilityResultList.first?.availabilityRouteList.first?.availabilityByDateList.first?.originDestinationOptionList.first?.fareComponentGroupList.first?.xxx

How do I access values the second and third fareComponentGroupList ?
(I am sorry about these silly questions but I am new with swift Codables)
Answer: Since originDestinationOptionList returns an array of dictionary, just fetch it from there by index.
let originDestinationOptionList = root.availabilityResultList.first?.availabilityRouteList.first?.availabilityByDateList.first?.originDestinationOptionList

let firstobject = originDestinationOptionList[0]["fareComponentGroupList"]
let secondObject = originDestinationOptionList[1]["fareComponentGroupList"]

let firstObjectsFirstItem = firstObject[0]

If the above gives error, this works ( Swift 5)
let originDestinationOptionList = root.availabilityResultList.first?.availabilityRouteList.first?.availabilityByDateList.first?.originDestinationOptionList

let firstobject = originDestinationOptionList[0].fareComponentGroupList.first

let firstObjectsFirstItem = firstObject?. (add the remaining part)

Comment: can you post your codable struct class ?
Comment: It gives error
"Value of type 'OriginDestinationOptionList' has no subscripts" ?
on
let firstobject = originDestinationOptionList[0]["fareComponentGroupList"]

I think it should be let firstobject = originDestinationOptionList[0].fareComponentGroupList
Comment: @PratapThank you, I figured it out with help from above code, I dunno if its something with swift 5, I had to use the other way, mentioned in my previous comment


A bit confused on usage of cross products.

Question: I'm reading about angular momentum in physics, and we are given the definition that
$\vec{\tau} = \vec{r} \times \vec{F}$
where $\vec{\tau}$ is torque, $\vec{r}$ is displacement from the origin, and $\vec{F}$ is an incident force.
They later use this result in problem solving, but rather than using a cross product, they simply say
$\tau = Fr$
where these are no longer vectors.
My question is simply this; if all we care about is the magnitude of the result of a cross product, can we just take the answer as a normal scalar product? That is, is it true that
$|\vec{a} \times \vec{b}| = |\vec{a}|*|\vec{b}|$
which is what they seem to have done here?
Comment: $\tau = Fr$ is a simplification that assumes that the force is applied at a right angle to the lever arm.  Or $F$ is the component of force at a right angle to the lever arm.  $\tau = F \times r$ is the more general definition.
Answer: No. The magnitude of the cross product is
$ |\vec{a} \times \vec{b}| = |\vec{a}| |\vec{b}| \sin(\theta)$
where $\theta$ is the angle between the vectors. So $\tau = Fr$ is true for $\theta = \pi / 2$.
However, the magnitude of the scalar product is different, it is
$|\vec{a} \cdot \vec{b}| = |\vec{a}| |\vec{b}| \cos(\theta)$.
Comment: Ah, I see, $\vec{F} $ and $\vec{r}$ were orthagonal. thank you very much.


Conditional expectation of two correlated RVs

Question: $X$ and $Y$ are two correlated random variables. I am trying to estimate $E(X\mid Y)$ given $E(X)$, $E(Y)$, $\rho(X,Y)$, $\sigma(X)$ and $\sigma(Y)$. Could someone point me how to go about it. What if $X$ and $Y$ are vectors of RVs with $\Sigma_X$ and $\Sigma_Y$ being their covariance matrices.
Comment: If you are trying to do some simulations and can sample both $X$ and $Y$, I believe you can still numerically compute $\mathbb E[X|Y]$. I don't think a general closed-form expression is possible though
Comment: It is incorrect to write $\Sigma_x$ rather than $\Sigma_x$ here. When one writes things like $f_X(x),$ the choice of capital versus lower case is as it is for important reasons.
Comment: The only way to succeed is to make a parametric assumption strong enough so that these five properties pin down the joint distribution.  This is the case for the family of Binormal distributions, for instance, but there are many such families.
Comment: @whuber so implicitly assuming normal distribution my solution below is correct?
Comment: Yes: your solution is known as *regression.*  It is considered *the* basic result about ordinary regression: namely, the conditional distribution in the Binormal family is linear.  For some insight about this see my post at https://stats.stackexchange.com/a/71303/919.  It derives this result assuming only the circular symmetry of the standard Binormal distribution.
Answer: I do not believe this is possible without more information regarding the relationship between the two variables.
For example, let's say that if X is positive, Y is negative, and vice-versa, and independently, they are two normally-distributed variables with a mean of $0$ and variance of $1$. You sample both of them, and then if their signs are the same, then flip one of them, e.g., by always choosing Y.
The correlation of these two variables will be negative, about $-0.63$. However, the only information you get from knowing X or Y is the sign. The expected value in either case would be roughly $0.8$ or $-0.8$.
If you have two normally-distributed variables that can be described using a standard correlation matrix $\Sigma_{xy}$, then you will have a unique value of $E(X|Y)$ for every value of $Y$.
There is definitely a more robust way of demonstrating more general cases of how this problem needs more constraints, but this is probably the easiest to visualize.
Here's a plot showing how two normal, correlated distributions can have a vastly different joint PDF, even if you know the correlation, their expected values, and standard deviations.

<code># code to generate plot
X = rnorm(10000)
Y = rnorm(10000)

Y = -abs(Y) * sign(X)

plot(X,Y,main='Signs are opposite')
cor(X,Y)

XYc = MASS::mvrnorm(
  10000,
  mu=c(0,0),
  Sigma=matrix(c(1,cor(X,Y),cor(X,Y),1), nrow=2)
)

par(mfcol=c(1,2))
plot(X,Y,main='Opposite-signed X and Y',pch='.')
plot(XYc, xlab='X',ylab='Y', main='Correlated X and Y',pch='.')
```
</code>
Comment: See the plots I added if this makes it a bit easier to understand. Both of the plots have the same exact underlying statistics, but their joint distribution is different, which changes $E(X|Y)$
Comment: what do you mean when you say X is positive and Y is negative but E[X] = E[Y] = 0?
Comment: you already know $\rho(X,Y)$. Would it not be sufficient?
Comment: I am not sure if I fully follow you. Perhaps if you could look at my solution and point what did I miss. Wouldn't $\rho(X,Y)$ as I described one of the inputs in the question be same as $\Sigma_{XY}$ as you said will be sufficient to arrive at $E[X|Y]$?
Comment: In your solution, you assumed that $\hat{X} = \hat{\beta}_0+\hat{\beta}_1Y$ (for $n=1$), which wasn't a condition stated in the original question.

If we add the condition/constraints of your example, however, then you should have sufficient information to solve for the BLUE (best linear unbiased estimator). The information you have in your question is a bit stronger than required, as you have the "true" expected values/covariances, rather than sample estimates, but you can still plug those in and get the conditional expected value.
Answer: Thinking a bit about it (for non-vector case) what's the problem with following approach:
$\hat{\beta}$ in OLS $\hat{X} = \hat{\beta}_0 + \hat{\beta}_1 Y_1 + \cdots + \hat{\beta}_n Y_n $ is estimated as follows:
$$ \hat{\beta}_i = \frac{ Cov(Y_i, X) }{\sigma^2(Y_i) }$$
$$ \hat{\beta}_0 = E[X]$$
Above OLS equation can be re-written as:
$$E[X | Y_1, ..., Y_n] = E[X] + \Sigma_i\frac{ Cov(Y_i, X) }{\sigma^2(Y_i)}E[Y_i]$$
In case $n=1$ and say $Y_1 = Y$:
$$E[X | Y] = E[X] + \frac{ Cov(Y, X) }{\sigma^2(Y)}E[Y]$$
$$E[X | Y] = E[X] + \frac{ \rho(Y, X) \sigma(X) \sigma(Y) }{\sigma^2(Y)}E[Y]$$
$$E[X | Y] = E[X] + \frac{ \rho(Y, X) \sigma(X)  }{\sigma(Y)}E[Y]$$
Comment: Actually now I am thinking how $\hat{\beta}_0$ from the expression of $\hat{\beta}_i$ above by setting $i=0$. That is how $\hat{\beta}_0 = \frac{ Cov(Y_0, X) }{\sigma^2(Y_0) } = E[X]$ ?where, $Y_0 = 1$.
Comment: Minor style comment, but I've seen $k$ used more for enumerating variable indexes (here $Y_1$, $Y2$,..., $Y_k$) and $n$ used for row numbers/indexes.


If $\text{gcd}(a,561)=1$, then $a^{560}=1\mod 561$

Question: We have the factorization $561=3*11*17$. Because $\text{gcd}(a,561)=1$, there are integers $x,y$ such that $ax+561y=1$. So $ax=1\mod 561$. Since the gcd is $1$, we have $a\not \in 3\mathbb{Z}, 11\mathbb{Z}, 17\mathbb{Z}$. Therefore, $a^{560}\not \in 3\mathbb{Z}, 11\mathbb{Z}, 17\mathbb{Z}$. So $b^{560}=1\mod 561$. Is my reasoning correct? I have seen a problem that was similar to this that used Fermat's Little Theorem, but that can only be used when the number we  mod out by is prime.
Comment: To solve, work separately modulo $3$, $11$, and $17$. In each case use Fermat's Theorem.
Comment: The proof is not correct. If it were, we would have $a^{32}\equiv 1\pmod{33}$  if $\gcd(a,33)=1$. But this is not true. We cannot jump from $ax+bm=1$ to $a^{m-1}\equiv 1\pmod{m}$.
Comment: If you don't like the "original" I picked, then take a look at [this](http://math.stackexchange.com/q/708556/11619) instead. This and related questions have been asked so many times, that it might be better to delete the quesion. Leaving the decision to regular users though.
Answer: HINT:
Use Carmichael function, $\lambda(561)=$ lcm$(2,10,16)=80$
For $(a,561)=1,a^{560}=(a^{80})^7\equiv1^7\pmod{561}$
Comment: this is for an algebra class, haven't seen this number-theoretic function


Using pure erlang OTP instead of elixir back-end with React.js and phoenix framework

Question: I'm currently designing a web app and was planning on using a React.js front end, and was hoping to using Erlang OTP for the management of the server.
I've heard this is possible using the phoenix framework, but there's not a lot of information on using Erlang instead of the default Elixir,
Any tips welcomed :)
Comment: *but there's not a lot of information on using Erlang instead of the default Elixir,

Any tips welcomed* -- Erlang comes with an http sever called `inets`.  There are also third party servers called `Yaws`, `Cowboy`, `ChicagoBoss`, etc.  See here: https://elixirforum.com/t/yaws-vs-cowboy-and-phoenix/3348/3.  You might want to ask your question there.
Comment: *but there's not a lot of information on using Erlang instead of the default Elixir,*  That's because Phoenix is a framework that uses the Elixir programming language.  Your question is sort of like asking, I want to use Ruby on Rails, but there isn't a lot of information on using Python instead of the default Ruby.   That's not quite a fair comparison because in the Elixir programming language you can actually call erlang functions.  However, you still need to learn Elixir to use the Phoenix framework.
Answer: A few tips and hints:

To a large extent, elixir is just erlang with a different (some say more modern) syntax. And macros.
Elixir and erlang both run their code on the same BEAM virtual machine.
Elixir is built upon erlang and gives you the same cool features that erlang has.
Elixir provides you with a lot of erlang based OTP libraries like Agent, GenServer, Supervisor, hot-code-reloading, etc.
Elixir has some very nice built-in/first-class tools like mix and ex_unit that you will learn to appreciate.
The Phoenix framework is written in elixir, so you have to use the elixir compiler to use Phoenix.
All information and tutorials about Phoenix you will find on the web will be using elixir, not erlang.

Long story short: if you want to use the Phoenix framework, you have to use Elixir.


Show L'Hospital limit for exponential function and power series

Question: Given a series $$f(t):=\sum_{k=0}^{\infty} \frac{t^{2k}}{\sqrt{(k!)}},$$
then since by first term expansion we have $f(t)\ge 1+t^2$, we get that $f(t) \rightarrow \infty$ for $t \rightarrow \infty.$
But now I want to compare the growing rate of this function to the expoentnial one and show that for any $a>0$ we have:
$$\frac{\text{exp}(a\ t^a)}{f(t)} \rightarrow 0$$ for $t \rightarrow \infty$. Is there a way to show this completely rigorously?
Comment: For $a<2$, this can be shown by $f(t) \ge \exp(t^2)$.
Comment: @Hetebrij how exactly does $f(t) \ge exp(t^2)$ imply this?
Comment: As $at^a -t^2 \to - \infty$ when $t \to \infty$ you have $\exp( at^a -t^2) \to 0$.
Answer: Lets review first what you need to calculate your limit.
Obviously the power series
$$
f(t):=\sum_{k=0}^{\infty} \frac{t^{2k}}{\sqrt{(k!)}}
$$
Converges
since lets look at
$$
g(x):=\sum_{k=0}^{\infty} \frac{x^{k}}{\sqrt{(k!)}}
$$
Its obvious that $f(t)=g(t^2)$ And looking at $g(x)$
we see from
$$
\lim_{k\rightarrow +\infty} \frac{a_k}{a_{k+1}}=+\infty
$$
That $g(x)$ converges from $(-\infty,+\infty)$
That said we know $f(t)$ converges and we also know that we can differentiate term by term and that it such a series converges in the interior of $(-\infty,+\infty)$  (so it converges on $(-\infty,+\infty)$
Ok so we know that now we can say that
$$
f'(t)=\sum_{k=0}^{\infty} \frac{2kt^{2k-1}}{\sqrt{(k!)}}
$$
However this leads us nowhere (at least not that i see)
We will use that
$$
(e^{at^{a}})=\sum_{k=0}^{+\infty} \frac{a^k t^{ak}}{k!}
$$
Note that that infinite sum also converges for $t\in (-\infty,+\infty)$
And that therefore we can add/subtract those two sums.
So we know that
$$
f(t)-exp(at^a)=\sum_{k=0}^{+\infty} \frac{\sqrt{k!}t^{2k}-a^kt^{ak}}{k!}
$$
For big enough k we will have that $k>a $ hence $t^2k > t^{ak}$ and also $\sqrt{k!} > a^k$ again starting from some k.
From there i think you can solve the rest.


Understanding note stems as written in Mozart's K.331 Andante Grazioso

Question: I have difficulties in interpreting two peculiar notes in Mozart's K.331 Andante Grazioso. I hope you can help in improving my performance.
First question is about the D note evidenced with the arrow:

How should I play that? It seems part of the previous chord, but the score shows it detached, so I am not sure how to approach that.
Another, maybe easier, question is about the very last A of the score (before the variations), you can see that with an arrow.

It shows both up and down stems. Is there a particular way I should interpret it?
Comment: Since it's the root note of the key, and the final note of the whole phrase or line, it'll be more emphasised anyway. But having two tails doesn't mean it's twice as loud!
Comment: Your second question is answered here already: [why-does-this-note-have-a-stem-pointing-up-and-another-pointing-down](https://music.stackexchange.com/questions/33948/why-does-this-note-have-a-stem-pointing-up-and-another-pointing-down)
Comment: @Arsak thanks! I've read the answers before posting, and I was wondering not about the reason (which I understood from that Q), but the interpretation of that note. If something should be "expressed" more with that (I'm a rookie!).
Answer: In the first case, because the D has its head so close to the E, it needs to be printed as it is. Otherwise it would be a big blob. Also, it belongs to the lower part of the tune, so its stem is pointing down. You play D, E, G♯ and B all together.
Although it's not all written out satb, there are parts where stems go up, stems go down, but not in the usual tidy way. The last A note'belongs' to both s and a parts, thus has two stems. It gets played as the one note, A.
Comment: @senseiwa The notes played are the same.  The stemming is solely there because the part is written for multiple "voices".  While it may not directly affect performance, it imparts understanding to the multiple melodic lines occurring simultaneously -- namely that both the soprano and alto voices resolve to a unison note.  If it were notated with a single stem, the impression would be that one of those voices just doesn't resolve.
Comment: Thanks! I still have a doubt about whether the A expresses something more since it belongs to two parts. Is expression here a little different than one with a simple A with just one stem?
Answer: This 3 part setting becomes devided in 4 parts in the last bar where as the down stemmed notes in the upper stave are the continuation of the tenor voice. The chord with the D you're asking is containing even 5 tones and in cases like this one note has to be placed a few behind the others for better reading and for notation reasons.
The final A of this section belongs to the sopran and alto as Tim explained and no, you can't play it in a special way. But in the first example you might actually emphasize the tenor line of the last bar with that D as sixth parallels of the soprano.
Comment: You've mistaken the blunt end of the arrow as important. It isn't. The issue is at the sharp end of the arrow (isn't it always?!)
Comment: You're right, Tim. But I understood the *previous* chord. I see now it was concerning the problem of notation ... I will edit the first part of my answer.
Answer: Like most piano scores, this one contains both literal 'what note to play' instructions and musical explanation.  Looking at your second example, the final A is played only once.  It is the culmination of two musical lines - the little C#, B, A rundown and the G#, A under it.  The composer considers it useful to show this, and I agree.
A similar 2-part texture is happening in your first example.  The D is offset for a simply practical reason.  See below for the (obviously unacceptable) alternative.
Comment: I'm used to seeing the D slightly to the right of the other 3 notes, but still attached to the same stave, so neither the way your image shows it nor the way it's written in the question above. If you look at the following link, the second to last bar on the first page you'll see what I mean. The A is slightly to the right, but still attached.: https://www.slideshare.net/tzinde/piano-sheet-music-nightwish-ever-dream
Comment: @GrandAdagio The edition you showed us in your earlier post DOES have the D.   What it lacks is the E.  It's not harmonically necessary as it doubles the bass note, and it thickens the texture from 4-note to 5-note for that one chord.   I think we can class it as a mistake, or at least a poor decision, from the editor of that version.
Comment: Yes, @MeanGreen, this also happens, when there's no desire or need to indicate polyphony.
Comment: Laurence are you around? :) My Urtext edition does not have the D note in measure 8 (is that measure 8?).
Comment: Thanks Laurence. Yes it's missing the E not D, my error.
Comment: I find just one place with all the 4 notes, which is the last measure of Var. 1.


What is $\rho$ in Hartshorne's exercise II.5.15(c) on extensions of coherent sheaves?

Question: Let $X = \operatorname{Spec} A$ be a noetherian affine scheme, $U \subseteq X$ open, and $\mathscr{F}$ a coherent sheaf on $U$. Furthermore assume $\mathscr{G}$ is quasi-coherent on $X$ so that $\mathscr{F} \subseteq \mathscr{G}|_{U}$ is a subsheaf. We then want to show that there is a coherent subsheaf $\mathscr{F}' \subseteq \mathscr{G}$ so that $\mathscr{F}'|_{U} \cong \mathscr{F}$. Let $i: U \to X$ be the inclusion morphism.
Hartshorne's hint is to use the canonical $\rho: \mathscr{G} \to i_*(\mathscr{G}|_U)$ which comes from adjunction since $\mathscr{G}|_U = i^*\mathscr{G}$ by definition. This morphism makes sense(is canonical) as a morphism of sheaves on $X$. Hartshorne then wants you to then consider $\rho^{-1} i_* \mathscr{F}$.
My confusion here is that I don't know what it means to take the pullback sheaf along a sheaf morphism. Is this just asking to take the preimage on any open subset of the sections $i_*i^* \mathscr{F}(U)$ to obtain a subsheaf of $\mathscr{G}$? What does $\rho^{-1}$ mean?
EDIT: Below there is a mistake. It essentially spoils the whole solution but I will leave it. $\rho$ does not need to be an isomorphism, I misquoted the exercise.
This is how I thought to solve this, although it seems too easy to be correct so I think I made a mistake. In the previous part, you show that $i_*\mathscr{F}$ is quasi-coherent and find a maximal coherent subsheaf $\mathscr{F}' \subseteq i_* \mathscr{F}$. I then showed that this sheaf turns out to restrict to $\mathscr{F}$. As such, the only thing missing in this part is to show that $\mathscr{F}'$ is a subsheaf of $\mathscr{G}$, and to do so, we just need to show that $i_*\mathscr{F}$ is a subsheaf of $\mathscr{G}$.
This follows quickly from the fact that $\rho$ is an isomorphism (Liu exercise V.1.1(b)) since $i$ is an open immersion, and that $i_*$ is left exact, right?
After all, $\mathscr{F} \subseteq i^*\mathscr{G}$ so that applying $i_*$ gives $i_*\mathscr{F} \subseteq i_*i^*\mathscr{G}$ by left exactness. Then composing through the isomorphism $\rho$ we get an injective $i_* \mathscr{F} \to \mathscr{G}$ so that $i_*\mathscr{F}$ is indeed a subsheaf of $\mathscr{G}$.
Is this composition with $\rho$ the intention behind the hint?
Thanks!
Answer: I do not know if OP has solved it on his own, but the following is the definition.

Let $\rho:\mathcal{F}\rightarrow\mathcal{G}$ be a morphism of sheaves of abelian groups on a topological space $X$ and suppose $\mathcal{H}$ is a subsheaf of $\mathcal{G}$. Then the inverse image $\rho^{-1}\mathcal{G}$ is the subsheaf of $\mathcal{F}$ defined by
$$(\rho^{-1}\mathcal{H})(U):=\rho_U^{-1}(\mathcal{H}(U))$$
for each open subset $U$ of $X$.

Then one can check that it is indeed a sheaf from the commutative diagram:
$\require{AMScd}$
\begin{CD}
\rho_U^{-1}(\mathcal{H}(U)) @>>> \rho_V^{-1}(\mathcal{H}(V))\\
@VV{\rho_U}V @VV{\rho_V}V\\
\mathcal{H}(U) @>>> \mathcal{H}(V)
\end{CD}
When $\rho$ is a $\mathcal{O}_X$-module morphism and $\mathcal{F},\mathcal{G},\mathcal{H}$ are $\mathcal{O}_X$-modules, the sheaf $\rho^{-1}\mathcal{H}$ is a $\mathcal{O}_X$-submodule of $\mathcal{F}$.


Calling git command from PowerShell

Question: When I call git from a PowerShell script I start to run into problems when I run more complex commands:
    # Work fine
    git log

    # Gives error
    git log `git describe --tags --abbrev=0 HEAD^`..HEAD --oneline --count

Error:
fatal: ambiguous argument 'git': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

Is there a good way to encapsulate these long commands when calling them from PowerShell?
Comment: Are you certain that the inner command, `git describe --tags --abbrev=0 HEAD^`, works by itself?
Answer: You can use $() to perform the substitution within a string to get this to work.
git log "$(git describe --tags --abbrev=0 HEAD^)..HEAD" --oneline --count

The backtick character is used as an escape character in PowerShell much like backslash is used in Unix shells.

Calling git command from PowerShell


Try block being called twice

Question: So I have a function that retrieves data from a database, and outputs it. It's encased in a try block, so that the error from running out of rows to process is dealt with.
Here's the function that is called on load (to make the initial output), and called later on to update the log box.
Problem is, whenever I call the function again, it outputs the data twice. Since only the data is in the try block, and not the headers, this points to the try / catch being the issue.
Apologies for the messy / hacky code:
    private void NavigateRecords()
    {
        da.Fill(ds1, "LogOutput");
        textlog4.Text = "Date \t\t Time \t\t Floor\r\n";
        try
        {
            for (int i = 0; i <= 20; i++)
            {
                DataRow dRow = ds1.Tables["LogOutput"].Rows[i];
                for (int i2 = 1; i2 <= 3; i2++)
                {
                    textlog4.Text += dRow.ItemArray.GetValue(i2).ToString() + "\t\t";
                }
                textlog4.Text += "\r\n";

            }
        }
        catch { textlog4.Text += "----------------------"; }
    }

This is the code that does part of the connecting, and may be of use:
        string sql = "SELECT * From tblLog";
        da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
        NavigateRecords();

Initial output:
Date         Time        Floor
6/12        18:18:22        1
----------------------

Output next time it is called:
Date         Time        Floor
6/12        18:18:22        1
6/12        18:46:19        2
6/12        18:18:22        1
6/12        18:46:19        2
----------------------

Comment: If I were to guess, I would say that the table has duplicate information in it, not that the `try` is being called twice. For the record, I'm not wild about you relying on an exception for program logic.
Comment: Do you clear ds1 before calling the NavigateRecords for the second time?
Comment: how is `NavigateRecords()` called and where is `ds1` used?
Comment: Are you using a debugger? Step through you code and you will see what's happening. There is not a problem with try/catch.
Comment: I agree that's probably an issue with `DataSet` not being cleared before subsequent uses of `Fill()` method. This is not related to the question, but please also avoid concatenating string with `+=`. Use `StringBuilder` class instead. More info here: http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx.
Comment: What is it that you want to do exactly in your program as i think this needs a re-think. The main fault is the fact that your adding data into teh DataTable on top Data that already exists. you need to add DS.clear() at the beginning of your Navigate Records method, so that it clears out the dataset before you fill the Adapter each time..
Comment: @Artemix Perfect. Just needed to move the ds1 definition into the method's scope.
Comment: Where are the values `20` and `3` coming from in your for loops? Why not loop through `ds1.Tables["LogOutput"].Rows.Count`? It's terrible to rely on a catch to handle more logic. Also, it's terrible to `pokemon catch` anywhere. What happens if there's actually an exception you weren't expecting?
Answer: its not an issue with your try catch , its an issue with your variables.  Clear out the variable before you add the new data to it.  I do not see your variable declared in the scope of the method so it retains the data you original put in it.

Try block being called twice


mq_open giving "too many open files"

Question: I created a message queue with following code. First few times it works properly.
int main()
{
    mqd_t mqdes;
    char mq_name[10] = "/mq";
    int oflag = O_CREAT | O_RDWR, ret;
    struct mq_attr attr;

    attr.mq_maxmsg = 1024;
    attr.mq_msgsize = 2048;

    mqdes = mq_open(mq_name, oflag, 0766, &attr);
    if(mqdes == -1) {
            perror("mq_open");
            if(errno == EMFILE)
                    perror("EMFILE");
            exit(1);
    }

    printf("mqueue created, mq_descriptor: %d\n", mqdes);

    ret = mq_close(mqdes);
    if(ret == -1) {
            perror("mq_close");
            exit(2);
    }
    printf(" mq closed successful\n");

    return 0;
}

After that, it's giving following error
mq_open: Too many open files
EMFILE: Too many open files

But why i'm getting this error? How can I see possix message queues like ipcs is for system V?
Comment: Regarding your question _How can I see possix message queues like ipcs is for system V?_  [THIS](http://www.linuxforums.org/forum/red-hat-fedora-linux/93230-what-posix-equivalent-ipcs-m.html) link talks a little about it.  I do not see anything else in what you posted that would suggest that you should have too many files open.
Comment: Are you getting the `mq closed successful\n` message at the end of the session?  [HERE](http://stackoverflow.com/a/3056992/645128) is another example of using mq_open, maybe you can see something there that you are not doing.
Comment: @ryyker: how can it goes to end of the program? mq_open fails and giving error.
Answer: Try to set the resource limits:
#include <sys/resource.h>

struct rlimit rlim;
memset(&rlim, 0, sizeof(rlim));
rlim.rlim_cur = RLIM_INFINITY;
rlim.rlim_max = RLIM_INFINITY;

setrlimit(RLIMIT_MSGQUEUE, &rlim);

Comment: Worked for me thanks, but not sure why increasing limit from ulimit command did not helped me.
Answer: I had the same issue while trying something. If you have by accident too many open message queues left on your system, you can try deleting your mqueue's in directory /dev/mqueue. This worked for me.
Also you might want to use mq_unlink(const char *name) after the mq_close() to ensure that the queue is removed from the system as described here.
Answer: I had the same problem and I solved it by increasing RLIMIT_MSGQUEUE via setrlimit.
If the hard limit (rlim_max) is too low as well (which was the case for me), you will have to give your process the CAP_SYS_RESOURCE privilege so that you can set the hard limit before you set the process limit (rlim_cur). Either run $ setcap 'CAP_SYS_RESOURCE=+ep' /path/to/executable over an executable or edit /etc/security/capability.conf to give CAP_SYS_RESOURCE to a user/group.

mq_open giving "too many open files"


I want help in formulating a mixed integer linear problem formulation

Question: I want the following help in linear fashion (In my previous question, I asked the same but the solution was not generic. Please check it : Prev.Question).

I have an arbitrary vector: $P(n) = [1, 2, 3, 4, 5,...,n]$. It can be $[10, 9, 5, 5,4, 3]$ , basically any arbitrary vector , which will be defined beforehand.
I have binary variables with length of $P:y(1),y(2).....y(n)$. These variables, y(i) can only take $0$ or $1$.

A new vector $Q(n)$ is needed, such that, if $y(i)$ is $1$, then the $i^{th}$ element in $Q(n)$ should be $0$. And in rest of the places, the $P(n)$ should get repeated.

Example : if $P = [8,5,6,1,2,3]$ and $y(1)$ and $y(4)$ are $1$ ,then $Q(1)$ and $Q(4)$, should be $0$. The vector, $Q$ will be as follows :

$Q =$[0 8 5 0 8 5].

Another example : if $y(3)$ is $1$, then $Q$ should be:

$Q =$[8 5 0 8 5 6 1].
Basically, beside the zeros on $i^{th}$ position, the vector $P$ should repeat itself starting from $P(1)$ in non-zero positions of $Q$.
Answer: Define a directed acyclic graph with nodes $N=\{0,1,\dots,n+1\}$ and arcs $(i,j)$ for $0 \le i < j \le n+1$.  Let binary decision variable $x_{i,j}$ indicate whether $y_i=y_j=1$ and $y_{i+1}=\dots=y_{j-1}=0$.  Let $L_i$ and $U_i$ be constant lower and upper bounds on $Q_i$.  (In the linked question, $L_i=0$ and $U_i=i$.)  Impose linear constraints
\begin{align}
y_i &= 1 &&\text{for $i\in\{0,n+1\}$} \tag1 \\
\sum_{j=i+1}^{n+1} x_{i,j} &= y_i &&\text{for $i\in\{0,\dots,n\}$} \tag2 \\
\sum_{j=0}^{i-1} x_{j,i} &= y_i &&\text{for $i\in\{1,\dots,n+1\}$} \tag3 \\
L_i(1-y_i) \le Q_i &\le U_i(1-y_i) &&\text{for $i\in \{1,\dots,n\}$} \tag4 \\
Q_k &= \sum_{(i,j): i < k < j} P_{k-i} x_{i,j} &&\text{for $k\in \{1,\dots,n\}$} \tag5
\end{align}
Constraints $(1)$ through $(3)$ yield a directed path from node $0$ to node $n+1$.
Constraint $(4)$ enforces $y_i=1 \implies Q_i=0$.
Constraint $(5)$ enforces $x_{i,j}=1 \implies Q_k = P_{k-i}$.

For your sample data, take $L_i=0$ and $U_i=\max_j P_j = 8$.  The constraints look like this:
\begin{equation}
y_{0} = 1 \\
y_{7} = 1 \\
x_{0,1} + x_{0,2} + x_{0,3} + x_{0,4} + x_{0,5} + x_{0,6} + x_{0,7} = y_{0} \\
x_{1,2} + x_{1,3} + x_{1,4} + x_{1,5} + x_{1,6} + x_{1,7} = y_{1} \\
x_{2,3} + x_{2,4} + x_{2,5} + x_{2,6} + x_{2,7} = y_{2} \\
x_{3,4} + x_{3,5} + x_{3,6} + x_{3,7} = y_{3} \\
x_{4,5} + x_{4,6} + x_{4,7} = y_{4} \\
x_{5,6} + x_{5,7} = y_{5} \\
x_{6,7} = y_{6} \\
x_{0,1} = y_{1} \\
x_{0,2} + x_{1,2} = y_{2} \\
x_{0,3} + x_{1,3} + x_{2,3} = y_{3} \\
x_{0,4} + x_{1,4} + x_{2,4} + x_{3,4} = y_{4} \\
x_{0,5} + x_{1,5} + x_{2,5} + x_{3,5} + x_{4,5} = y_{5} \\
x_{0,6} + x_{1,6} + x_{2,6} + x_{3,6} + x_{4,6} + x_{5,6} = y_{6} \\
x_{0,7} + x_{1,7} + x_{2,7} + x_{3,7} + x_{4,7} + x_{5,7} + x_{6,7} = y_{7} \\
0 \le Q_{1} \le 8(1-y_{1}) \\
0 \le Q_{2} \le 8(1-y_{2}) \\
0 \le Q_{3} \le 8(1-y_{3}) \\
0 \le Q_{4} \le 8(1-y_{4}) \\
0 \le Q_{5} \le 8(1-y_{5}) \\
0 \le Q_{6} \le 8(1-y_{6}) \\
Q_{1} = 8x_{0,2} + 8x_{0,3} + 8x_{0,4} + 8x_{0,5} + 8x_{0,6} + 8x_{0,7} \\
Q_{2} = 5x_{0,3} + 5x_{0,4} + 5x_{0,5} + 5x_{0,6} + 5x_{0,7} + 8x_{1,3} + 8x_{1,4} + 8x_{1,5} + 8x_{1,6} + 8x_{1,7} \\
Q_{3} = 6x_{0,4} + 6x_{0,5} + 6x_{0,6} + 6x_{0,7} + 5x_{1,4} + 5x_{1,5} + 5x_{1,6} + 5x_{1,7} + 8x_{2,4} + 8x_{2,5} + 8x_{2,6} + 8x_{2,7} \\
Q_{4} = x_{0,5} + x_{0,6} + x_{0,7} + 6x_{1,5} + 6x_{1,6} + 6x_{1,7} + 5x_{2,5} + 5x_{2,6} + 5x_{2,7} + 8x_{3,5} + 8x_{3,6} + 8x_{3,7} \\
Q_{5} = 2x_{0,6} + 2x_{0,7} + x_{1,6} + x_{1,7} + 6x_{2,6} + 6x_{2,7} + 5x_{3,6} + 5x_{3,7} + 8x_{4,6} + 8x_{4,7} \\
Q_{6} = 3x_{0,7} + 2x_{1,7} + x_{2,7} + 6x_{3,7} + 5x_{4,7} + 8x_{5,7}
\end{equation}
For your sample solution with $y_0=y_1=y_4=y_7=1$ and all other $y_i=0$, the constraints imply that $x_{0,1}=x_{1,4}=x_{4,7}=1$ and all other $x_{i,j}=0$.  Now compute $Q$ based on these values of $x$ and $y$ to help understand how the formulation works.

Edit: You can omit $(4)$, which is already implied by $(2)$, $(3)$, and $(5)$.
Comment: No, those two constraints are correct.  And we do want $y_0=y_7=1$, but no other $y_i$ are forced.  Note that the two constraints you mentioned can both be satisfied by taking $x_{0,7}=1$ and all other $x_{i,j}=0$.
Comment: I did not understand about : $y$ here. In this case, our decision variable is $x(i,j)$. What are $y(i)$ and $y(j)$ here? Are these also binary variables? And are we defining additional variable $x(i,j)$ for our convenience? Also, I cannot understand, using $arc(i,j)$. Where are we using the directed acyclic graph in equations?
Comment: The $y_i$ is your original binary decision variable.  I updated the summation indices in $(2)$ and $(3)$ to make the arcs explicit.
Comment: If $y(i)$ is my binary decision variable, why condition # $(1)$ says $y(i)=1$. I may also have $y(i)=0$
Comment: Constraint $(1)$ forces $y_i=1$ only for the two artificial nodes $0$ and $n+1$, which are the endpoints of the directed path.
Comment: In second line of solution , it is written as $0 \le i < j \le n+1$. It mean maximum of $i$ is $n$. Then should the first constraint be changed as : $y(0)=1$.
Comment: The arcs $(i,j)$ satisfy $i\le n$, but the nodes $i$ and $j$ are in $\{0,1,\dots,n+1\}$.  Constraint $(1)$ is correct as written.  You want both $y_0=1$ and $y_{n+1}=1$.
Comment: Thank you for your clarification. Now I understood almost all things. I have partially implemented it. I will reply here with my results. Thank you very much for your valuable help !
Comment: Dear Dr. RobPratt , I m trying to understand and implement the above solution. however I think, it is beyond the scope of my understanding. Can you please tell me , what should i specifically read to understand above ?
Comment: I just added to my answer the explicit constraints for your example.  I recommend substituting the fixed values of $y$ and $x$ and using the constraints to deduce the values of $Q$ as a helpful learning exercise.  It is also useful to deduce $x$ from the fixed values for $y$.
Comment: Thank you very much for your answer. I could successfully formulate it. However, I am solving an MILP (mixed integer linear programming). I wanted to use the $Q$ generated above. However, now a different problem is raised. $Q$ is multiplied by another variable. Thus the problem has become nonlinear again. I used to thought, we have made up the $Q$ using a known vector, $P$ and only binary variable $y$. Unfortunately, I cannot linearize my system.  Therefore, I was about to use McCormick method to get done. Can you please shade some light on it ? Or the system, thus, is inherently nonlinear ?
Comment: Please post a new question for your new problem.
Comment: I think there is a correction in the formulae mentioned : $x_{0,1} + x_{0,2} + x_{0,3} + x_{0,4} + x_{0,5} + x_{0,6} + x_{0,7} = y_{0}  $ and $x_{0,7} + x_{1,7} + x_{2,7} + x_{3,7} + x_{4,7} + x_{5,7} + x_{6,7} = y_{7} $ should be avoided. I removed these and then I am getting correct answers.. Otherwise some $y(i)$ are forced to be 1.
Comment: Dear Dr. Rob . Please see this question: https://math.stackexchange.com/questions/4236859/linearization-of-product-of-a-continuous-and-a-discrete-variable
Comment: Can there be any generalized way to make one zero , two zeros.... in this formulation (e.g. $[8,5,0,8,5,6,1],[8,5,0,0,8,5,6], [8,5,0,0,0,8,6,1]$)
Comment: The arc definitions control how many consecutive zeros are allowed.  To disallow a certain number, omit the corresponding arcs from the problem, thereby reducing the number of $x_{i,j}$ variables.
Comment: The solution approach is extremely well. However, if taken in a larger sense, the number of binary variables are very large. It takes enormous time to solve the model.
Comment: What is your objective? Also, if you have bounds on the length of the gap between values of $1$ for $y$, you can omit some of the arcs and thereby reduce the number of $x$ variables.
Comment: The objective is to find optimum $y_i$, which will reduce a cost function, which has $y_i$s in it ( linear). I omitted many arcs, as per one of your suggestions. In actuality, $y_i$ denotes a schedule of on and off of a machine. I have several such machines. Here, $i$ denotes time. I have $y(Machine,time)$. The model , since consists a lot of such machines for large duration, the number of binary variables exploding.  The objective is to minimize the addition of operating costs of all machines and profit. The profit requires all machines to run whereas the op.cost requires machines to be off
Comment: In addition to above, the states of machine changes with time ( as shown by vector $P$ in our problem).
Comment: I have, to be very frank, have understood the logic behind the formulation, I have modified the formulation ( reducing arcs, reducing the linear inequality equations to the minimum level). I assume that there is no scope to reduce the problem further. Somewhere, in the literature I have read that MILP always have to face this issue of large computational durations. I'm using CPLEX. I tried several options. When the nos of machines is small, problem converges in minutes, however as I add more machines and time, it takes exponential time to converge.


How do I forecast quarterly public expenses based on annual budgets and potentially other variables?

Question: I have some time series data from 2008 and forward (see below) on quarterly public expenses and annual public budgets. I would like to forecast the last two quarters of 2018 as precisely as possible, but I am unsure about what methods I should use.
I have been considering a vector autoregressive model, but there is an issue with different frequencies on the data. I guess I could split the budget into 4 equal parts.
I have also considered computing the deviation between the two series and then use a univariate model instead, but that would rule out adding additional explaining variables such as demography.
If possible I would like some suggestions on what type of models I should look into. I am not an expert in times series analysis and especially not the multivariate ones, but I hope it is possible.
I hope you can help. Thank you!
<code>+------------+-----------------+
|    Date    |    Expenses     |
+------------+-----------------+
| 2008-01-01 | 66.386.086.765  |
| ...        | ...             |
| 2016-01-01 | 78.200.910.570  |
| 2016-04-01 | 167.604.150.482 |
| 2016-07-01 | 251.017.792.801 |
| 2016-10-01 | 337.595.471.006 |
| 2017-01-01 | 77.580.707.994  |
| 2017-04-01 | 166.599.846.864 |
| 2017-07-01 | 251.331.721.551 |
| 2017-10-01 | 337.247.375.085 |
| 2018-01-01 | 76.467.286.000  |
| 2018-04-01 | 166.634.900.000 |
| 2018-07-01 | ?               |
| 2018-10-01 | ?               |
+------------+-----------------+
+------+-----------------+
| Date |     Budget      |
+------+-----------------+
| 2008 | 2184.108.40.2067 |
| ...  | ...             |
| 2016 | 3188.8.131.525 |
| 2017 | 346.244.633.739 |
| 2018 | 346.127.455.000 |
+------+-----------------+
</code>
Comment: Those are *cumulative* quarterly expenses, not actual quarterly expenses, right?
Comment: Yes, you are right. I have change it to actual quarterly expenses in my model now
Answer: There are several ways to approach this issue ranging from simple heuristics to rigorous econometric models.
Among the heuristics is to simply interpolate the values for higher temporal levels down to a more disaggregate periodicity. Many software packages offer automatic methods for doing this.
A more rigorous approach for mixed temporality is Ghysels' MIDAS regression. He and some colleagues have developed an R module for this, Mixed Frequency Data Sampling Regression Models: The R Package midasr which is referenced here...
https://www.jstatsoft.org/article/view/v072i04/v72i04.pdf
Comment: Thanks for the comments. I've mostly been looking at a SARMAX model so far as suggested by IrishStat, but also shortly at a MIDAS model. It seems to me like MIDAS models are a solution when the regressors have higher frequency the independent variable and not the other way around. Is that correctly understood? Because if that is the case, then a MIDAS model is not feasible solution
Comment: My understanding is that it's bi-directional as a function of how the data is operationalized.
Answer: Aside of the issue of converting data to a higher level of frequency, your approach should be to build a SARMAX model incorporating predictors and the history of predictors, the history of Y itself while incorporating pulses, level/step shifts , seasonal pulses and local time trends. Follow  https://autobox.com/pdfs/A.pdf to get a useful https://autobox.com/pdfs/SARMAX.pdf . Stay way clear of simple ols regression as suggested here https://autobox.com/pdfs/regvsbox-old.pdf unless suggested (i.e. not proven to be inadeqaute ) by the analytics.