Computing Large Powers

Question: So this is my question:
Compute $7^{818} \pmod {1637}$ using no more than 14 multiplications mod 1637. (You should of course verify that 1637 is prime if you plan to use Fermat's Theorem.)
I would know how to do this problem if the power that 7 is raised to is higher than 1637. So if I had this:
$$ 2^{200}\pmod{101}$$
I could just do: $2^{100}\equiv 1\pmod{101}$ and go from there to solve. But if I have 1637 then I have to do:
$$7^{1636}\equiv 1\pmod{1637}$$
Then I would have:
$$7^{1636}7^{-818}...$$
But I know this is totally wrong. How do I go about this problem?
Comment: You can get from $7$ to $7^{818}$ by a cleverly ordered sequence of steps, each of which consists either of squaring the result of the previous step, or multiplying it by $7$. The binary representation of $818$ is part of the cleverness. Can you see it?
Comment: @GerryMyerson I think you mean we can do something like $((7^2)^2)^{...}$. But I still don't get how this helps to solve the problem.
Comment: The problem is to compute $7^{818}$ using no more than $14$ multiplications. So, how many multiplications do you use, doing what I suggested?
Answer: Using the binary representation of 818, yields:
$$818_{10} = 1100110010_2$$
There are ones in the $2^{1}, 2^{4}, 2^{5}, 2^{8}, 2^{9}$ positions.
So we can write:
$$7^{818} \pmod {1637} = 7^{(2+16+32+256+512)} \pmod {1637}$$
Using repeated squaring (this hugely reduces your workload), we have:
$$7^{2} \equiv 49 \pmod {1637}$$
$$7^{16} \equiv 899 \pmod {1637}$$
$$7^{32} \equiv 1160 \pmod {1637}$$
$$7^{256} \equiv 765 \pmod {1637}$$
$$7^{512} \equiv 816 \pmod {1637}$$
So, we just multiply these, arriving at
$$7^{818} \pmod {1637} \equiv 49 \cdot 899 \cdot \ 1160 \cdot 765 \cdot 816 \pmod {1637} \equiv 1636 \pmod {1637}$$
Regards
Comment: Excellent demonstration! +1
Answer:
$7^2=7\times 7$
$7^3=7^2\times7$
$7^6=7^3\times7^3$
$7^{12}=7^6\times7^6$
$7^{24}=7^{12}\times7^{12}$
$7^{48}=7^{24}\times7^{24}$
$7^{51}=7^{48}\times7^3$
$7^{102}=7^{51}\times7^{51}$
$7^{204}=7^{102}\times7^{102}$
$7^{408}=7^{204}\times7^{204}$
$7^{816}=7^{408}\times7^{408}$
$7^{818}=7^{816}\times7^2$

It takes at least 12 multiplications to calculate $7^{818}$
Answer: Code in Pari/GP
<code>{powmod(base,expon,modul)=local(a,vb,result,fk,j);
  vb=binary(expon);  \\ a vector containing the binary
                     \\ representation of the exponent
  result=1;
  fk=base;
  j=#vb+1;        \\ supplement index which goes from the tail of
                  \\ vb to its head instead of going like k
  for(k=1,#vb,j--;
        if(vb[j]==1 ,result = (result * fk) % modul);
        fk =  (fk*fk) % modul
     );
  return(result);}

  \\ test it
powmod(7,818,1637)
 %931 = 1636

powmod(7,818818818818,1637)
 %934 = 1636

powmod(7,100000000000,1637)
 %935 = 908

powmod(7,10^32 ,1637)
 %936 = 379
</code>

Computing Large Powers


How can I assign a dynamic IP address to subdomains?

Question: How can I assign IP addresses dynamically to subdomains created on my domain?
Comment: Which operating system is your server using ?
Answer: A domain itself has no IP, it is associated with one via DNS records. You do the same with any subdomain. www.mydoamin.com can point to xxx.xxx.xxx.xxx while mail.mydomain.com can point to yyy.yyy.yyy.yyy and so on, just adding A records.

I only mention the above because DNS is something that tends to propagate slowly. If you were to continually change your DNS records, you would end up with DNS servers all over the place that are still catching up and could possible have people going to 2, 3, 4 or more addresses instead of the one you intend them to go, depending on how quickly you change those A records.

Can you possibly explain why you want to do this? there may be a better suggestion that can be offered if we knew more about what you were trying to do.
Answer: I don't understand what you are trying to achieve via dns. But for your question title assigning ip should be done via DHCP not via DNS. I don't understand how dns can assign ip. As far as i know, dns is for translating name to ip and vice versa. But setting the hostname and ip address is the done via dhcp. I think you are looking at the wrong place or can you explain better.


Guitar effects routed to IEM before recording in Ableton

Question: I've been trying all sorts of routes but I can't get the app to work the way I want and at this point I'm wondering if this is even possible.
SETUP:

Ableton Live 10
Focusrite 6i6
BiasFX guitar effects on x2 audio tracks (clean and distorted)

When live looping I would like to hear the distorted guitar sound from BiasFX into my headphones, before recording it to an audio track. This will allow me to get into the groove and experiment a little bit "in my head" before recording the clip with my idea.
When I'm done with the first track I would switch to the next track (with a different effect). I would hear that effect through my headphones, jam a little bit without the audience listening to my jam and then when I'm ready I would record my idea. Obviously, when I play the clips I want to hear the clips with their corresponding guitar effects on.
Here is also an image of how I have my Ableton at the moment.

The problem at the moment is that I can hear just the clean input from the guitar without the effects.
Answer: You'll have to change something. Let's put facts together and see where it leads us:

(1) The track where you record clips will have to have its Monitor switch set to Off, because you want it to only start outputting when you're finished recording a clip and the clip starts playing.
(2) The channel/track where you have the effects will have to have its Monitor switch set to In (or Auto with recording enabled), because that's the only way to get it to pass through audio from its input to its output.
(3) A track's Monitor switch can only be in one position at any given time. For example, it cannot be both Off and In at the same time.

--> From these facts I can only conclude that the track that has the effects and the track that records and plays back the clips cannot be the same track.
I propose the following kind of setup:

TRACK 1: EFFECTS

Audio From: your guitar input
Audio To: Headphones
Monitor: In

TRACK 2: RECORDED CLIPS

Audio From: TRACK 1
Audio To: Master (audience)
Monitor: Off

Track 1 should have an Audio Effect Rack where you create two chains, one for the Clean sound and another for Distortion, and configure these so that you can switch between chains. How to do that is a bit complicated, but all the required steps are explained in this guide: https://help.ableton.com/hc/en-us/articles/360000727359-How-to-switch-chains-in-a-Rack-using-the-chain-selector
The above scheme doesn't take advantage of the Cue mode and switches. It might be useful for switching the monitoring of your guitar on/off as needed.
Disclaimer: I didn't actually test this with a guitar and headphones etc. I'll have to try it later, it seems like an interesting way to use Ableton.
Comment: @Ando Did I understand correctly that you don't want the audience to see and hear your live playing while you're recording a clip? That would mean that they will actually _never_ see and hear you play live even for one second, because everything that's heard comes from playback of clips. Personally, this feels a bit strange, because it kind of takes away one of the most important aspects of playing live - that it happens completely in realtime and the performer's actions are exposed.
Comment: Piiperi thanks! That's what I wanted to achieve. I was able to replicate this to other tracks. Really, really exciting stuff.
Comment: yes, that's exactly what I'm looking for. Your solution works well by the way.


What does it mean : the finite dimensional distribution determine the random process?

Question: In the book Random perturbation of dynamical system of Fredlin and Wantzell (2nd edition) page 17, it's written :
Let $(\Omega ,\mathcal F,\mathbb P)$ a probability space and $(\xi_t)_{t\in T}$ a stochastic process with state space $(X,\mathcal B )$. If $T$ is countable, then the finite dimensional distributions determine the random process to the degree of uniqueness usual in probability. If $T$ is an interval, we can have two process (one continuous and ond discontinuous) with the same finite dimensional distribution.

I'm not sure if I completly understand this... does it mean (in the countable case), that if for all $B\in \mathcal B$, $$\mathbb P\{X_n\in B\}=\mathbb P\{Y_n\in B\}$$
for all $n\in\mathbb N$, then $X_n=Y_n$ a.s. ?
Answer: No.
It means that if two stochastic processes $\xi^1$ and $\xi^2$ are such that
$$
\forall t_1,\cdots,t_n\in T,\forall A_1,\cdots,A_n\in\mathcal B,\mathbb P(\xi^1_{t_1}\in A_1,\cdots,\xi^1_{t_n}\in A_n)=\mathbb P(\xi^2_{t_1}\in A_1,\cdots,\xi^2_{t_n}\in A_n),
$$
then $\xi^1$ and $\xi^2$ have the same distribution, that is to say
$$
\forall A\in\mathcal B^{\otimes T},\mathbb P((\xi^1_t)_{t\in\mathbb R}\in A)=\mathbb P((\xi^2_t)_{t\in\mathbb R}\in A).
$$
The short way of saying this is that if two processes $\xi^1$ and $\xi^2$ have the same finite dimensional distributions, then they have the same distribution. In the general case, you cannot deduce the almost sure equality between the two processes.
Let us now illustrate the last sentence. Let $T=[0,1]$, $U$ be a random variable uniformly distributed on $[0,1]$ and $\xi^1$ and $\xi^2$ be defined for all $t\in T$ by $\xi^1_t=0$ and $\xi^2_t=1_{\{U=t\}}$ (that is $1$ if $U=t$ and $0$ otherwise). Then for all $t\in [0,T]$, $\xi^1_t=\xi^2_t$ a.s. (since $\mathbb P(U=t)=0$) so we easily deduce that $\xi^1$ and $\xi^2$ have equal finite dimensional distributions and therefore equal distributions. However, $\xi^1$ is clearly continuous and $\xi^2$ discontinuous.
Comment: Thank you for your answer, but my question was rather for $T=\mathbb N$ (or $\{1,...,n\}$). The statement looks stronger. (I know that for the case $T=[0,1]$ is not true that the process are a.s. equal when they have same distribution)
Comment: Everything I said (except the last paragraph of course) is valid for $T$ countable. If $T=\mathbb N$ or $\{1,\cdots,n\}$ you can deduce the equality of the distributions but not the equality a.s.


When to use index join?

Question: I was wondering what is the best scenario to use index join when joining two tables besides nested loop join and merge-sort join?
Comment: This is determined by the query optimizer.  Although most databases support hints for such things, it is better to depend on the optimizer.
Answer: Usually you don't tell the SQL engine how to actually execute the join.  The query optimizer will parse your query, and then examine the stats for the tables you are joining and it will choose whether to do merge, nested loops, etc.  The query optimizer determines what indexes can/should be used at this time as well, based on the lowest predicted cost of each possible algorithm.

When to use index join?


How to put data from firebase database into input text field?

Question: Hello I would like to ask if how to put data from firebase database into input text field?
I tried it in any text label like, Label, h1, strong or anything and they getting it but when I put it in input text field its not changing or detecting.
This is the code my input text field.

First Name*

<input class="md-form-control" type="text" id="firstname" name="firstname" placeholder=" " required>

and this is the javascript or my firebase code to move it in the input field but nothings happening.
firebase.auth().onAuthStateChanged(function(user)
  {
      if(!user)
      {
          window.location.href = "../signin.html";
      }
      else
      {
        var dbUser = firebase.auth().currentUser.uid;

    firebase.database().ref('Freelancer/' + dbUser).once('value').then(function (snapshot){

    var okay = snapshot.val().name;
    var okay1 = snapshot.val().email;
    var okay2 = snapshot.val().pass;
    var okay3 = snapshot.val().roles;
    var okay4 = snapshot.val().userID;

    console.log(okay);
    console.log(okay1);
    console.log(okay2);
    console.log(okay3);
    console.log(okay4);

    document.getElementById("firstname").innerHTML=okay;
    document.getElementById("lastname").innerHTML=okay1;
    document.getElementById("phone").innerHTML=okay2;
    document.getElementById("roles").innerHTML=okay3;

});

Hope someone can assist me or help me thank you!
Answer: For <input> elements, you need to use the value property when setting (or getting) the text in the field.
document.getElementById("firstname").value = okay;

Comment: Oh my gosh. It's working thank you so much!


Strategies for learning all 60 seventh chords in root position (5 qualities in 12 keys)

Question: I am attempting to learn all 60 root position seventh chords.  I would like to do this in a way that advanced my playing ability most efficiently.
I've heard I should focus on 3 things: motor memorization of chords so that my fingers automatically know where to go, hearing chord qualities so that I can discern if I need to make an adjustment, and knowing the notes of the chords so that I can learn the theory.
It seems my mind can only handle one thing at a time. Do you have any strategies to get these chords under my fingers in a way that gets the motor, sound, and theory cemented into my brain?  Any particular exercises?
As of right now, I am just going up and down in one key to practice all major sevenths.  Then I do all minor sevenths, and so on.  This allows me to focus in on the chord quality sound and motor memory, but the theory escapes me as playing chromatically doesn't help my understanding I think.
Ideas?
Also, do you think I should continue to only work on root position until I have them all down and then do inversions?
Answer: I wouldn't do them that way, personally. It's quicker to learn things if you find ways to apply them as you go; otherwise, you lose track of why you decided to learn them in the first place.
So, learn some chords in one key, and then learn some basic progressions with those. Find the ways that those progressions are easiest to play. Once you have a progression down in one key, start transposing it to other keys.
For example, start with C, a I-IV-V-I progression. Play the chords in root position first, and take note of what type of seventh chord each one is. I and IV are major 7th chords, and V is a dominant 7th. Now, look at inverting the chords in such a way that they fall easily under your hands. If you're just blocking the chords like this, it's most common is to play I in root position, and IV and V in second inversion:

This minimizes the amount of movement you have to do from chord to chord. Even if you don't care much for the sound, it's a good idea to learn this, because if you're aware of the easiest inversions involved in moving from one chord to another in a progression, you'll find it easier to harmonize music at sight.
If you're working with a bass line, start by playing all the chords in root position. Something like this:

These chords are understood to be in root position, since the bass notes are.
Once you have found something that you like, you can start playing it in a bunch of different keys, and putting melodies above it.
So, by all means, go ahead and learn all 60 7th chords, but find ways to apply your knowledge as you gain it.
Comment: @DavidBowling 60 is indeed a somewhat arbitrary number. If the chord can be any of major, minor, augmented and diminished, and the 7th can likewise be any of the four, there are 192 possible permutations in the scale. Beginning theory teaches (correctly IMO) that there are five seventh chords most commonly in use: MM7 (major) Mm7 (dominant), mm7 (minor), dM7 (half-diminished) and dm7 (diminished). Then you could add in +m7 and +M7 (augmented and augmented major) and get 84. Then you could add in ... but I thought I might leave all that alone to avoid confusing the OP. 60 is a good start. :)
Comment: Are those tonic chords in your left-hand example what you intended?
Comment: @Richard Not quite sure what you mean by the tonic chords in my left-hand example. The first chord (beats 1 and 2 in the first bar) is tonic, and the fourth chord (beats 3 and 4 in the second bar) is also tonic. The other two chords are subdominant and dominant, in that order. It doesn't look like I put them in wrong (?).
Comment: Oh, I misread; I thought you were aiming for triads, not seventh chords. My mistake!
Comment: Oh, that makes sense. Yeah, those would be some pretty strange triads. I'd suggest to the OP to learn triads first, but he did specifically ask about 7th chords.
Comment: Dominant, minor, major, minor/major sevenths - that's 48. What am I missing?!
Comment: @Tim -- diminished, augmented... oops, now we are up to 72


grafico com dados de um service REST

Question: Tenho um serviço REST feito em PHP e este me retorna dados em JSON.
Ao consumir a url da API em REST, preciso exibir os dados em gráficos feitos em javascript.
Alguém conhece algum framework em JS que gere gráficos de uma API REST e que seja free?
consigo fazer uma requisição em AJAX, como no exemplo abaixo, jogando a url do serviço e tratar os dados no gráfico.. como o exemplo acima.. baseado no Exemplo.. é possível?
    $(document).ready(function () {
    //chama o ajax após a pagina ser carregada
    $.ajax({
        type: 'post',
        url: 'http://servico/dados',
        success: function (dados) {
            //gera o grafico
            var options = {
                responsive:true
            };
            var ctx = document.getElementById("GraficoBarra").getContext("2d");
            var BarChart = new Chart(ctx).Bar(dados, options);
        }
    });
});

edit:
json
[{"GERENCIA":10,"EMPRESA":"1","FILIAL":"1"}]

Comment: Dá uma olhada aqui pelo site, procurando por `grafico`: http://pt.stackoverflow.com/search?q=grafico
Comment: eu entendo.. mas eu preciso de um que tenha suporte para consumir o serviço...
Comment: Se tens um JSON creio que qualquer um pode ser facilmente adaptado.
Comment: certo... dá uma olhada por favor no meu edit na pergunta.. é possivel?
Comment: Coloque um exemplo do formato do JSON de retorno do seu serviço.
Comment: ok... coloquei o exemplo
Answer: Como você não especificou nenhuma biblioteca, deixo um exemplo usando Chartjs:

var json = [{"GERENCIA":10,"EMPRESA":"1","FILIAL":"1"}];
json = json[0];//primeiro indice do JSON
var labels = [];//array com as labels
var dataChart = [];//para criar a série
for(i in json){//percorre o json e monta as labels e a série
 labels.push(i);
  dataChart.push(json[i]);
}
var data = {
    labels: labels,
    datasets: [
        {
            label: "Meus dados",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 1,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: dataChart,
        }
    ]
};

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'bar',
    data:data,
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});

<canvas id="myChart" width="250" height="100"></canvas>
Comment: que show!... vou testar
Comment: uma pergunta... estou trazendo meu json através do angular... como eu faria pra colocar o json que vem através do scope na variavel "json" que vc criou?
Comment: @novato Se entendi bem é só vc atribuir na variável `var json = $scope.json;`, seria isso?
Comment: ok... mas como seria se o json tivesse mais de uma linha?
Comment: ok... mas como seria isdso? jogo o script dentro da tag que tem o ng-Controller?
Comment: @novato Se tiver mais de um índice vc precisa percorrer todas criando outro for exemplo https://jsfiddle.net/mnf1rveq/.
Comment: @novato sim você pode colocar no controller, veja um exemplo aqui. http://stackoverflow.com/questions/30267438/chart-js-angular
Comment: massa... tem como eu escrever algum texto na barra do grafico? pequisei e é algo relacionado ao tooltip.. mas nao achei nada exato
Answer: É muito simples, depois de vc recuperar os seus dados num JSON, pode enviar para javascript D3. POde ser usando AJAX ou não.
Aqui o link da biblioteca D3.
Nota, no D3 os códigos já estão prontos, basta copiar e colar. São gratuitos.
Exemplo:

Faça a sua consulta REST e recupere o resultado em JSON. Isso seu código já esta ok.
Aqui vc pode seguir 2 caminhos. Ou grava seu JSON como um arquivo separado para ser lido depois ou guarda seu JSON numa variável para ser lido no processo seguinte.
Cria o tipo de grafico desejado entre os muitos que existem no D3.js carregando a biblioteca d3.js e aponta para os seus dados. Seja no arquivo, seja na varável.

Assim:
//Digamaos que esse é seu JSON, bem simples
[
  {
  "name": "Top Level",
  "parent": "null",
  "children": [
    {
      "name": "Level 2: A",
      "parent": "Top Level",
      "children": [
        {
          "name": "Son of A",
          "parent": "Level 2: A"
        },
        {
          "name": "Daughter of A",
          "parent": "Level 2: A"
        }
      ]
    },
    {
      "name": "Level 2: B",
      "parent": "Top Level"
    }
  ]
}
]

//Esse vai ser o seu arquivo html ou php com javascript
<!DOCTYPE html>

    <meta charset="utf-8">

    <title>Collapsible Tree Example</title>

Exemplo extraído da página
Comment: Podes dar um exemplo de utilização da D3 neste caso?
Comment: exato.. pode informar um exemplo?

grafico com dados de um service REST


How do I to calculate note's frequency using no intervals?

Question: To calculate frequency of a note you should know the amount of semitones between the note and A4.

2x/12 * ffixed = fgiven

where:
x – is the quantifier, based on amount of semitones between given note and fixed one (A4);
ffixed – is the frequency of fixed note (~A4 = 440 Hz);
For example, since C4 is nine semitones lower than A4, the quantifier for it will be -9.

So, whether it is possible to calculate its frequency without knowing of this interval? Is there any other frequency-of-a-pitch equation that doesn't use intervals in it?
Comment: I have no idea, how you want to specify the tone for which you want the frequency if not counting to some reference. You could use a MIDI mapping from note number to frequency but even MIDI counts semitones.
Comment: There are no inherent mathematical properties in the letters A-G that can enable them to be translated to frequencies without the use of a constant. The letter assignments are completely arbitrary; thus you need some kind of constant to define them — 440 Hz. Your equation makes use of the number 12, so you clearly have the ability to define a constant value in your equation; if all you're trying to do is create a function definition f(p) where p is the pitch, the frequency of which is being calculated, then this is really an algebra question.
Comment: I do think this is an XY problem, frankly. What are you trying to accomplish by answering this question? Are you just having trouble translating note names into numeric values?
Comment: The answer to your question as written is "No, it's not possible." This is because a pitch->frequency conversion actually requires a second argument that defines the tuning system in use. When you omit this, we assume that the tuning system will be 12-tone equal temperament at A=440Hz, and so this information must be embedded in your formula as constants.
Comment: What problem are you trying to solve?  Is this an XY problem? http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem
Comment: f(given) = 2^((given-A4)/12) * 440
Comment: My function doesn't have a 'number of semitones' argument. It just takes a given pitch. You MUST, as part of the formula/function, find the difference of that pitch from A4 in order to complete the calculation.
Comment: Listen Dmitry, you have two options. One is map the pitches and avoid any kind of calculations. Two is calculate each based on some kind of reference pitch in semitones. There is no third options as how a pitch is defined in the system is by referencing other pitches in the system you are using. These's got to be some correlation between the input you give and the pitch of the output in a given system.
Comment: I can write you a JavaScript function that takes an absolute pitch and outputs a frequency. It should be obvious how to do this from the information already here. But any reasonable solution would make use of subtraction arithmetic from constant values. It is unclear what your constraint is--is this some kind of programming riddle?
Comment: @DmitryParzhitsky the content of your comment to NReiling (about Objects and whatnot) indicates to me that you are trying to solve a problem that is not laid out in the body of this question --  what are the constraints that prevent you from just doing the math laid out in this question?  They should be in there.
Comment: @guidot: Maybe, you understood me wrong. It definitely must be regular note, such as C4, or G2 doubly flat, or another. But within my initial conditions (which are out of stage here) I will not be able to define the interval.
Comment: @NReilingh: All I want is to get 261.6255… for `C4` without using `amount of semitones` variable. And it doesn't seem to be algebra-question.
Comment: @NReilingh: Yep. As I said, it's __not__ that is needed.
Comment: @Dave: I'm sure, it is not XY-problem :)
Comment: @NReilingh: No, no. I'm a JavaScript programmer. There are `Objects` there (kinda computeral beings). In my case, each `Object` has a property named `frequency`. Now Iam creating algorithm, that will calculate frequency of for given note. Unfortunately, I can't use intervals, due to the very initial conditions of my issue, — it is defined directly. So I must resolve it, or say, that it is unsolvable
Comment: Agreed with Dave. Ultimately, without a rationale for the constraints this question appears to be nonsense.
Comment: The question is answered now. I don't really understand  why downvote it, but, anyway, — valid answer has been given: "Not possible".
Answer: You either needed a reference pitch to calculate all other notes or you need to have all the pitches defined. Every  formula to obtain a pitch needs a reference pitch and you need to know how that pitch relates  to the one you are calculating.
The pitch you are using is relative to a system whether it is equal temperament, just, Pythagoras, ect. The pitches you build off each  Not even every A4 is 440 Hz. There are a lot of different  groups that use other frequencies like 435 or 441.
As long as you have a way to figure out which of the 12 notes you are dealing with (if you are using equal temperament like you seem to be) the rest is easy. You must have some method to know the difference between an A, A#, B, C, ect.
After you figure out the 12 base reference pitches of each note the calculations are simple as you only need to calculate one octave then double the frequencies to get an octave up and half to get an octave down which is valid regardless of system. For example, A3 which is an octave below A4 would map to the pitch 220 Hz and A5 which is an octave above A4 would map to 880 Hz.


How to auto scale font size in echarts?

Question: I don't really have a question but just to share my knowledge here.
This is a knowledge sharing on how to auto scale font size in echarts.js based on the div size.
Answer:

let myChart = echarts.init(document.getElementById('myChart'));

function autoFontSize() {
  let width = document.getElementById('myChart').offsetWidth;
  let newFontSize = Math.round(width / 11);
  console.log(`Current width : ${width}, Updating Fontsize to ${newFontSize}`);
  return newFontSize;
};

const fruits = [{
    value: 100,
    name: "Apple(s)"
  },
  {
    value: 200,
    name: "Banana(s)"
  }
];

const sum = fruits.reduce(function(prev, current) {
  return prev + current.value
}, 0);

let myChartOption = {
  grid: {
    left: 0,
    top: 0,
    right: 0,
    bottom: 0
  },
  tooltip: {
    trigger: 'item',
    textStyle: {
      fontSize: '15',
    },
    formatter: 'You have {c} {b}'
  },
  legend: {
    orient: 'vertical',
    x: 'right',
    y: 'bottom',
    padding: 0,
    itemGap: 0,
    textStyle: {
      fontSize: '15',
    },
    formatter: function(name) {
      var targetValue = 0;
      fruits.forEach(function(c) {
        if (c.name == name) {
          targetValue = c.value;
        }
      });
      return targetValue + ' ' + name;
    }
  },
  series: [{
    name: 'fruits',
    type: 'pie',
    center: ['50%', '40%'],
    radius: ['50%', '60%'],
    avoidLabelOverlap: false,
    label: {
      position: 'center',
      textStyle: {
        fontSize: autoFontSize(),
        fontWeight: 'bold'
      },
      color: 'black',
      formatter: '' + sum,
    },
    labelLine: {
      normal: {
        show: false
      }
    },
    data: fruits,
    itemStyle: {
      emphasis: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    }
  }]
};

myChart.setOption(myChartOption);

$(window).on('resize', function() {
  if (myChart != null && myChart != undefined) {
    myChart.resize({
      width: 'auto',
      height: 'auto'
    });
    myChart.setOption({
      series: {
        label: {
          textStyle: {
            fontSize: autoFontSize()
          }
        }
      }
    })
  }
});
#myChart {
  width: 100%;
  min-height: 330px;
  margin: 0 auto;
}

How to auto scale font size in echarts?


How to append the first element of a matrix onto a list over a loop?

Question: I have two loops that runs for a different x and y coordinates and for each different (x,y) coordinates, a linear equation is being solved for force 1 and force 2 using matrices method i.e. finding the inverse of A if Ax = C. For each loop it gives an answer as a matrix where first element is force 1 and 2nd element is force 2 at those specific coordinates. Here's my code:
import numpy as np
from scipy import linalg
def Force():
    Force1 = np.zeros((160,90))
    Force2 = np.zeros((160,90))
    for x in np.arange(0,16.1,0.1):
        for y in np.arange(1,9.1,0.1):
            l1 = np.hypot(x,y)
            l2 = np.hypot(15-x,y)
            A = np.array([[(x/l1),((x-15)/l2)],[(y/l1),(y/l2)]])
            c = np.array([[0],[70*9.81]])

            F = linalg.solve(A,c)
            Force1[x,y] = F[0]
            Force2[x,y] = F[1]
            print("Force 1 = {} \nForce 2 = {}\n".format(F[0], F[1]))

so at each point (x,y) a matrix [[Force 1],[Force 2]] is solved. Now I would like to append all the Force1(s) into a list of Force1[x,y] and similarly for Forces2(s) so that I can do
plt.imshow[Force1]
plt.imshow[Force2]

to plot a 2 heatmaps. How would I go about doing that?
Comment: You mean
mylistF1 = []
mylistF2 = []
mylistF1.append(Force1[x,y])
mylistF2.append(Force2[x,y])

??
Comment: If your final goal is to get 2 heatmaps, just use `plt.imshow(Force1)` and `plt.imshow(Force2)`.
Comment: I don't get your question, you already have your force arrays. Just type `plt.imshow(Force1)` for example.
Comment: I can't because it won't allow me, it gives me this error "only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices" for Force1[x,y] = F[0]
Answer: This solves your issue - you were trying to assign to indices in Force1 and Force2 of type float. I've changed the for loops to use enumerate instead, and tweaked the assignment so it assigns F[0][0] and F[1][0].
import numpy as np
from scipy import linalg
def Force():
    Force1 = np.zeros((160,90))
    Force2 = np.zeros((160,90))
    for i, x in enumerate(np.arange(0,16,0.1)):
        for j, y in enumerate(np.arange(1,9,0.1)):
            l1 = np.hypot(x,y)
            l2 = np.hypot(15-x,y)
            A = np.array([[(x/l1),((x-15)/l2)],[(y/l1),(y/l2)]])
            c = np.array([[0],[70*9.81]])

            F = linalg.solve(A,c)
            Force1[i, j] = F[0][0]
            Force2[i, j] = F[1][0]
#            print("Force 1 = {} \nForce 2 = {}\n".format(F[0], F[1]))
    plt.imshow(Force1)
    plt.show()
    plt.imshow(Force2)
    plt.show()

Force()

The generated plots are:

and


Mvc Release Candidate "File" ActionResult

Question: K... I'm doing something obviously wrong. I have a simple page with a file input control on and a submit button. I'm trying out the new "File" ActionResult that was released with the Mvc RC...
All, I want to happen is when the submit button is clicked the selected file is uploaded to the database. This all works fine...
Then, after the page refreshes I want a image to display the resulting image that was uploaded. The issue, is that the image is not rendering... I get the broken image...
This is the portion that is getting the file and sending it back to the view...
        var a = Helper.Service.GetAttachmentById(id, MembershipProvider.SecurityTicket);

        if (a == null)
        {
            return View(new ImagePlaceHolderViewData(new { Id = id }));
        }
        return View(new ImagePlaceHolderViewData(new { Id = a.Id, Image = a, FileContent = File(a.Data, a.ContentType) }));

Then in the view I have a image tag like so...
<img src="<%=Model.FileContent.FileContents %>" />

I have also tried...
<img src="<%=Model.FileContent%>" />

Thoughts..??
Answer: FileResult returns the ASCII or binary contents of the file.  When you say do the following:
<img src="<%=Model.FileContent.FileContents %>" />

You are attempting to push the binary image data into the src attribute.  That will never work, because the src must a URL or a path to an image.
There are several ways of doing what you want, and the most correct solution in this case, would be to create a new controller that returns the binary data like you are attempting, and then you set the src attribute to be the path to correct action on your new controller. E.g:

This points to the following (really simple and incomplete) example controller:
public class ImageController : Controller
{
    public ActionResult Result(int resultID)
    {
        // Do stuff here...

        return File(..);
    }
}

Note that the name I chose for the action is most likely not any good, but it serves its purpose as an example.  Hope this was helpful.
Answer: I think it's pretty simple: the src attribute of your img tag requires an URL. What you're doing here is just putting the FileStream object in there (which implicitly calls the ToString method on that object). Your resulting html is probably something like this:

Did you check your html source?
What you probably should do is provide a method which returns the data, and pass the route to that to your view. Your resulting html 'should' then look something like this:

So, steps you have to do are:

Create a method on your controller that returns a FileContentResult
Pass your image ID to your view
Use Url.RouteUrl to generate an url which you can put in your img tag, which points to the method returning your image data.
Comment: There doesn't exist any (extension) method on HtmlHelper called RouteUrl.  That method is part of UrlHelper (Url.RouteUrl.)
Answer: There's also another solution:

<img src="data:image/gif;base64,<%=Convert.ToBase64(Model.FileContent)%>"/>

which works in some browsers, and doesn't in some browsers(IE! of course). But the stable solution is what Thomas J mentioned.
Comment: I updated my post. You'll notice that I am now able to get the image to appear on the 1st upload but, if I go and upload a 2nd image it should replace the first but, it does not.The image does not refresh to the new one but, I can see on the db site the record has been updated/replaced. Thoughts...?
Comment: May be it's browser's cache which still holds the old image. Clear the  cache and check if the problem still exist.


Sampling with replacement in R randomForest

Question: The randomForest implementation does not allow sampling beyond the number of observations, even when sampling with replacement.  Why is this?
Works fine:
rf <- randomForest(Species ~ ., iris, sampsize=c(1, 1, 1), replace=TRUE)
rf <- randomForest(Species ~ ., iris, sampsize=3, replace=TRUE)

What I want to do:
rf <- randomForest(Species ~ ., iris, sampsize=c(51, 1, 1), replace=TRUE)
Error in randomForest.default(m, y, ...) :
  sampsize can not be larger than class frequency

Similar error without stratified sample:
rf <- randomForest(Species ~ ., iris, sampsize=151, replace=TRUE)
Error in randomForest.default(m, y, ...) : sampsize too large

Since I was expecting the method to take bootstrap samples when given replace=TRUE in both cases, I was not expecting this limit.
My objective is to use this with the stratified sampling option, in order to draw a sufficiently large sample from a relatively rare class.
Comment: Well, that was my word choice not the documentation's, but your point is well-taken.  Still, this is inconvenient when trying to re-balance the distribution and I don't know a reason why this is a helpful restriction to impose.
Comment: I'm not sure what the real reason is, but a bootstrap sample is typically the same size as your original sample, so this behavior seems perfectly in line with what I'd expect from something claiming to take bootstrap samples.
Answer: This does not answer why, but to get around this, one can duplicate the data for the rare class in the training data, and take a stratified sample of the result.
Two drawbacks to this approach, compared with a "natural" oversampling:

the out of bag estimates are no longer meaningful
more resources are required to store the object and take random samples

but it will allow one to build the forest with the desired class ratios.
Answer: I have the exact same question and found this in the changelog for randomForest:
Changes in 4.1-0:

In randomForest(), if sampsize is given, the sampling is now done
without replacement, in addition to stratified by class.  Therefore
sampsize can not be larger than the class frequencies.

Setting replace=TRUE manually also does not seem to override this.
Comment: It may be the case that the replace parameter is simply being ignored, but later in that changelog:

Changes in 4.5-12:

* Added the 'strata' argument to randomForest, which, in conjunction with 'sampsize', allow sampling (with or without replacement) according to a strata variable (which can be something other than the class variable).  Currently only works in classification.
Comment: I ended up just oversampling prior to running the randomForest.  There's probably something wrong with this methodology, but it seem s to work when I test the results.
Comment: No, that's the workaround that I use and it does exactly what one wants.  Especially for the use case of one relatively rare class, duplicating the data for that class on the training set and before taking a stratified sample works well and the "cost" in terms of additional memory/CPU is not too high.  I guess that's worth writing up an a "answer" even though it really isn't one...
Comment: For example, the same error is generate via `rf <- randomForest(Species ~ ., iris, sampsize=c(51, 1, 1), strata=iris$Species, replace=TRUE)`
Comment: Moreover, some test cases with the current version (4.6-7) indicate that samples are taken with replacement, so this isn't the explanation.


array of objects for an html5 canvas nav bar

Question: I have a html5 Canvas animation that I am doing on Adobe Animate and tweaking with some code.
I have a portion on the animation that will be like a combobox with all the links to navigate through the different frames. The thing is, I don't want to be creating a bunch of EventListener to many buttons because from experience I know that doesn't work so well. So I am trying to think of a more creative solution. This is my idea.

Create an array that will contain all the buttons.
Assing a variable for each target frame.
Create a for loop with a function inside that assigns the listener to the selected button and then points it to the desired frame (variable)

This is what I have got so far, (not much)
    var combobox = [this.btncasco , this.btnbanyera , this.btnLumbrera , this.btnproapopa, this.btnestriborbabor ];

for (var i=0; i<combobox.length; i++) {
var clipcasco = gotoAndStop(0);
var clipbanyera = gotoAndStop(2);
var cliplumbera = gotoAndStop(4);
var clipproapoa = gotoAndStop(6);
var clipestriborbabor = gotoAndStop(8);

    }

Would that be feasible ?
Answer: In your example, you are just assigning the result of gotoAndStop (with no scope, so likely you're getting an error in the console)
I think you are looking for something like this:
for (var i=0; i<combobox.length; i++) {

  // This is kind of complex, but if you just reference "i" in your callback
  // It will always be combobox.length, since it references the value of i
  // after the for loop completes variable.
  // So just store a new reference on your button to make it easy
  combobox[i].index = i*2; // x2 lines up with your code 0,2,4,etc.

  // Add a listener to the button
  combobox[i].on("click", function(event) {
    // Use event.target instead of combobox[i] for the same reason as above.
    event.target.gotoAndStop(event.target.index);
  }

}

You might have the same problem as your other StackOverflow post where the button is undefined (check the console). There is actually a bug in Animate export right now where children of a clip are not immediately available. To get around this, you can call this.gotoAndStop(0); at the start to force it to update the children.


Choosing the right size of an out of sample data

Question: I am beginner in forecasting, especially forecasting with R and I am really willing to improve my knowledge.
Recently, I started practicing electricity consumption time series forecasting.
The first barrier I faced is the choice of out of sample data for assessing the forecast accuracy of the forecast model i will be using (regression with ARIMA errors).
I have data for 147 months and I want to forecast the next 24 months, for the period June 2013 to January 2015. Furthermore, I have read in @RobHyndman's online text book
Hyndman, R.J. and Athanasopoulos, G. (2013),
Forecasting: principles and practice,
(accessed 28 May 2013),  section 2.5
under 'Training and test sets', that:

size of the test set is typically about 20% of the total sample, although this value depends on how long the sample is and how far ahead you want to forecast

If I divide the dataset with 20% of it being the out-of-sample data, the forecast model applied to the in-sample data is not quite accurate, since I guess it fails to capture the recent trend, (which began in the middle of the last year), of decreased electricity consumption due to a significantly raised electricity tariff.
What do I do about this?
Can you possibly give me instruction on what would be considered appropriate size of the out of sample data. I also tried with 7 months of out-of-sample data, but I am afraid that there might be an overfitting issue. Is that right?
Comment: Can you give the link to the chapter of the book you mean, and state roughly where it is to be found?
Comment: http://otexts.com/fpp/2/5/...there it is:):)
Comment: Your link is mangled, sorry, but it was enough information to quickly find it. I have included a full reference and link in your question so people can find the context in which the statement was made.
Answer: Not really my area of expertise but I think one answer should be "Nothing!" You could of course try to improve the model or try other techniques (but if you begin tuning the model on the basis of its performance in the test set, you still run the risk of "overfitting") but changing the size of the test set does not seem to directly address this problem.
If today was still 2011 and we were trying to predict electricity consumption until 2013, this model would give us some seriously misleading predictions. This is precisely the type of things out-of-sample evaluation is supposed to pick up. You can look at it retrospectively today and interpret it as a trend that started last year because of some change to the electricity market but the conclusion remains the same: This model did not allow you to see it coming.
Also, if you read the sentence carefully you will notice that Rob Hyndman also stresses that size of the test set should depend on how far ahead you want to forecast. Intuitively, if you want to predict 24 months, a test set of 7 months is too short, no matter whether you have 100 or 10000 months of past data. For example, a good model of seasonal changes in your data could look very good even if it is unable to predict any year-on-year trend.
Comment: So basicly, whichever forecasting method i choose, with the same predictors, respecting the general "out of sample data size" rule, looking retrospectively today will not capture the effect of change in consumption due to tariff modifications?
Comment: I have no idea. What I am saying is that if this particular forecasting method did not predict it, putting this fact under the rug by redefining the test after you looked at the results will not make your model better next time around and leaves you with no idea of how good it will really be in the next 24 months.
Answer: 20% of 147 months is 30 months, which means that at you have over 2 years of data. If the trend began in the middle of last year, then it exists within that 2 year time frame.
If you feel that your forecast is not capturing your trend, then it is probably because you smoothed too much. If you used the average instead of the drift or seasonal method, then it unlikely went uncaptured. The problem isn't with your sample size but with your method of forecasting - and specifically how much smoothing you are doing.


If $b \cdot a = c\cdot a$ for equal-sized non-zero vectors $a, b, c$, does it follow that $c = b$?

Question: I assumed $c = a$ due to transitivity. However, I read somewhere that this is only the case iff the vectors are collinear.
I hope someone can clear this up for me.
Thanks for your attention.
Comment: What is going on? Why are you completely changing your question?
Comment: He thought this is a chat room :-)
Comment: @u9237an I rolled back the edits and restored the orginal question, What you did is not fair to the users who took the time and effort to post nice answers. You can ask the new one separately.
Comment: Sorry. New to mse, didn't realise this was not permissible. Thank you for retrieving the original post.
Answer: I assume you mean dot products?
If so, then consider $a = (1, 0, 0)$, $b = (0, 1, 0)$ and $c = (0, 0, 1)$.  All three different and of length 1, yet the dot products are the same (and 0).
(There are 2-d examples as well, but that's harder to construct.)
Answer: No, it is not necessarily true. Think of your dot product as the projection of one of the vectors on the other multiplied by the latter.
Then for $a \cdot b$ let's say we have a projection of $b$ on $a$ multiplied by $a$, and for $a \cdot c$ we have a projection of $c$ on $a$. Note however, that we have a "free variable" - the angle between the vectors, which can be different in these two cases and thus it is not necessarily $b = c$.


Merging array values into main array

Question: In PHP how do I add the values of [2] into the main body of the array as opposed to having it as a sub array? I've tried array_push, the + concatenator and array_merge but none work.
Array
(
    [0] => 42299.37181713
    [1] => Yes
    [name] => Bob Smith
    [country] => United Kingdom
    [2] => Array
    (
        [0] => Name 1
        [1] => Name 2
        [2] => Name 3
        [3] =>
    )

What I am looking for / need is a way to get to the following (and I'm sure there's a simply/correct PHP way of doing it!):
Array
(
    [0] => 42299.37181713
    [1] => Yes
    [name] => Bob Smith
    [country] => United Kingdom
    [2] => Name 1
    [3] => Name 2
    [4] => Name 3
    [5] =>

Thanks for your answers - I have now posted my solution as one of the answers :)
Comment: how did you get that array in the first place ?
Comment: They are two separate arrays so the first part is what I'm currently getting if I use say array_merge.
Comment: array_merge() should do exactly what you want, my guess is you used it wrong somehow to end up with #1 instead of #2.
Comment: The reason was because I was in a foreach and I was merging an array with values from another array. The solution was to use array_merge but on the parent[$k] rather than on $vs. Does that warrant an answer below?
Comment: @Ukuser32 can you please upload your code ?
Comment: I have posted an answer @KanishkaPanamaldeniya thanks :)
Answer: <?php
$myArray = array(
    0 => 42299.371,
    1 => "Yes",
    "name" => "Bob Smith",
    "country" => "United Kingdom",
    2 => array(
        0 => "Name 1",
        1 => "Name 2",
        2 => "Name 3"
        )
    );

$tmp = $myArray[2];
unset($myArray[2]);

$myArray = array_merge($myArray, $tmp);

echo '
';
print_r($myArray);
echo '
';

Comment: Any chance of the source data then?
Comment: Sorry $myArray is the output not what I have to work from.
Answer: The issue here was that I was doing
foreach ($data as $row){

I was then trying to do array_merge on $row or use + on $row but these are values not an array in themselves even though print_r says its an Array.
So the solution is to do the following:
foreach ($data as $k=>$row){
     $new_row = array_merge($data[$k],$sub_array);

That way you are actually merging an array not a value set from an array.
Answer: if you get arrays separately you can use array_merge :
$a = ['whashington', 'NewYork', 98];
$b = ['fruits', 'clothes', 4];
$a = array_merge($a, $b);

array (size=6)
  0 => string 'whashington' (length=11)
  1 => string 'NewYork' (length=7)
  2 => int 98
  3 => string 'fruits' (length=6)
  4 => string 'clothes' (length=7)
  5 => int 4

Answer: You can do something like this to get the desired result,
<?php

    $multi_array = array
    (
        0 => 42299.37181713,
        1 => "Yes",
        "name" => "Bob Smith",
        "country" => "United Kingdom",
        2 => array
        (
            0 => "Name 1",
            1 => "Name 2",
            2 => "Name 3",
        )
    );

    $tmp = $multi_array[2];
    unset($multi_array[2]);
    $i = 2;
    foreach($tmp as $value){
        $multi_array[$i] = $value;
        ++$i;
    }

    print_r($multi_array);

?>

Answer: I understand that you are interested in merging a sub-array as elements of the parent array.
You might achieve it doing:
$tmp_arr = array();
foreach ($data as $k=>$v) {
  if (is_array($v)) {
    $tmp_arr = array_merge($tmp_arr, $v);
  } else {
    $tmp_arr[] = $v;
  }
}

Merging array values into main array


Sum of real numbers with random index

Question:
Let $\left\{x_{n}\,,\ n\geq 1\right\}$ be a sequence of real numbers.
$N$ be a nonnegative integer valued random variable with finite expectation.
Assume that $\,\mathrm{E}\left(S_{N}\right) = a\ \left(~\mbox{const}~\right)$ where $S_{N} = x_{1} + x_{2} + \cdots + x_{N}$.

How can we make conclusion about $N$ or $\,\mathrm{E}\left(N\right)$.
Thank you !.
Comment: Do you know anything about the distribution of the $x_i$s?
Answer: You cannot infer anything, for if
(1) all $x_i = 0$, and $N$ is always 1, you get $a = 0$.
(2) The $x_i$ alternate between $-1$ and $1$, and $N$ is always 2, you get $a = 0$ as well
In these two cases which give you identical data ($a$) you get different expectations for $N$ and $E(N)$.
Even if you know the $x_i$, you can't infer anything. For if all $x_i$ are $0$, for instance, you can't tell whether $N = 1$ constantly, $N = 2$ constantly, or $N$ is just some rv with finite expectation, all three of which will produce the same value of $a$.
Comment: I got it. Thanks !

Sum of real numbers with random index


Intuition behind defining convergence of functions

Question: What is the intuition behind defining convergence of sequence of functions? I didn't get a satisfying answer.
Answer: There are two kinds of convergence you should definitely understand: pointwise and uniform convergence. Call the sequence of functions we are looking at $\{f_n\}$, and we'll assume the functions are $\mathbb{R} \rightarrow \mathbb{R}$ for convenience.
For pointwise, pick a point $x$ in $\mathbb{R}$, and define the sequence $a_n = f_n(x)$. If the sequence converges pointwise to a function $f$, then this sequence will converge to $f(x)$. There is no condition about how fast it converges, but given some $\varepsilon > 0$, we have to be able to pick $N \in \mathbb{N}$ such that for all $n > N$, $\lvert f(x) - f_n(x) \rvert < \varepsilon.$
On the other hand, if we want uniform convergence, we are given $\varepsilon > 0$, and we then have to be able to pick an $N \in \mathbb{N}$ such that given a point $x$, the values of $f_n(x)$ for $n > N$ are all within $\varepsilon$ of $f(x)$ (i.e. $\lvert f(x) - f_n(x) \rvert < \varepsilon$). This should look very similar to the other condition! I got them mixed up a lot in real analysis. The distinction is that for uniform, you pick $\varepsilon$ and $N$ first, and for pointwise, you pick the point first. This is an important distinction: if you pick $\varepsilon$ first and need to find an $N$ that works for all points $x$, it is possible that you cannot -- even if the functions converge pointwise, some points may require larger $N$s than others, and the size of these $N$s might go to $\infty$.
Uniform convergence is stronger than pointwise, and therefore it is more powerful. For example, if $\{f_n\}$ converges uniformly to $f$, then $\int f_n$ converges to $\int f$. This is used very often when we want to approximate a function with functions that are somehow easier to work with. For example, if every function $f_n$ is a simple function, one which is made of discrete steps, it is very easy to integrate (you just add up the area under each step). Every continuous function can be defined as the uniform limit of a sequence of simple functions, so we can find the integral by taking the limit of the integrals of these. For example, if we are approximating the integral of the parabola $x^2$, $\int f_1$ might look like the shaded area in this image, $\int f_2$ like this, etc. The simple functions will converge uniformly to $x^2$, which means that $\int f_n$
will converge to $\int x^2$.
Comment: I wish to know, for what, we introduce the concept convergence of sequence of functions? is it only for finding the properties of limit function which the sequence already have?
Comment: My reply would not fit in the comment box, so I have added it as a paragraph in my answer.
Answer: The biggest leap is that between pointwise and uniform convergence. Pointwise convergence tells you basically nothing, just that for each $x$, the sequence $f_n(x)$ converges. Since in this sense, all the $x$'s are totally separate from one another, there's no reason to think this mode of convergence tels you anything at all.
Uniform convergence on the other hand, has a nice interpretation once you understand a little bit about topology. You may consider the space of continuous functions on a compact topological space $X$ with values in $\mathbb{R}$ and denote this space by $C(X)$. We can topologize this space by in fact giving it a metric, a standard metric being $\rho (f,g) = \sup_{x \in X} |f(x) - g(x)|$. This lets us regard the functions as points in a topological space. Since $f$ and $g$ are continuous on a compact set, they are bounded and so this quantity is finite. Alternatively you could drop the condition that $X$ be compact and restrict yourself to bounded functions, or compactly supported functions.... you get the point.
Anyway, it's worth noting that if you have a sequence of functions $f_n \in C(X)$, this being a perfectly good metric space, we can talk about convergence of functions $f_n \to f$. This will depend on the topology of the space in general, but for our particular metric, it merely says that if $\epsilon$ is given, there is $N$ such that $\sup_{x \in X} |f_n(x) - f(x)| < \epsilon$ when $n \geq N$. But this is exactly what it means for convergence of the $f_n$ to be uniform.
Whenever a notion of convergence is defined, it will be of this form. There is always some appropriate underlying topological space of functions with a choice of metric that makes this concept of convergence equivalent to the concept of convergence of a sequence of points in this topological space.
Many theorems of analysis are made more enlightening (by my view) with this idea in mind. The Bolzano-Weierstrass theorem asserts that bounded sequences contain convergent subsequences. Thinking of a sequence of points as a sequence of constant functions, we can see this is a special case of the Arzela-Ascoli theorem, which says that a sequence of uniformly bounded and equicontinuous functions has a uniformly convergent subsequence. This follows since a bounded sequence of constant functions is uniformly bounded, equicontinuity for constants is trivial, and convergence is uniform because the functions are again, constants.
Answer: There are several definitions of the convergence of sequences of functions. And in some sense every definition relies on a different intuitive idea of convergence.
Given a sequence of functions $f_1,f_2,\ldots$, for instance functions
$$f_n\colon [0 , 1] \to \mathbb{R}$$
one intuition that could work for many definitions is that of thinking of the sequence of graphs of the $f_n$ and "see" if they tend to some other graph that could be thought of as being the graph of a certain function $f$. In that case, you would like to be able to say that $f_n \to f$ as $n \to \infty$.
But of course, there's no obvious definition of what it is for a "sequence of graphs" to tend to another graph. For instance, if you think of the graphs (in $[0,1]$ of the functions $f_1(x)=\tfrac 1 2 x$, $f_2(x)=\tfrac 2 3 x$ and, in the general case, $f_n(x)=\tfrac n {n+1} x$, you would find it more and more "close to" the graph of $f(x)=x$.
This "closeness" happens, for many reasons:

for a fact, if you think of $x$ as fixed number in the domain and take the limit as $n$ tends to $\infty$, you will find the answer is $x$ in every case;
if you think of the functions $g(x)=x+\epsilon$ and $h(x)=x-\epsilon$, you will also find that for every $\epsilon>0$, there exists a natural number $N$ such that $f_n(x)$ "lies between" $g(x)$ and $h(X)$ (that is, $h(x)\leq f_n(x) \leq g(x)$ for all $x\in [0.1]$) given that $n$ be greater than $N$. Graphically, you would see that the graphs get inside completely between two copies of the graph of $f(x)$: one displaced $\epsilon$ units up, and another moved down; even for very small epsilons, there is a certain $N$ such that the graphs of $f_{N+1}, f_{N+2},\ldots$ all lay completely between the two copies of that of $f$.

The first notion leads to point-wise convergence while the second one leads to uniform convergence (AKA, convergence in infinity norm). Many others related to the "graph intuition" can be defined and perhaps others that do not relate to it but for sure are based on some other intuition.
Comment: (+1) your second point explaining uniform convergence graphically was extremely enlightening.


Given f is analytic in D and satisfy |f(z)|->1 as |z|->1 then prove that f is rational

Question: Let $f$ be analytic in $D$ and satisfy $|f(z)|\rightarrow 1$ as $|z|\rightarrow 1$. Prove $f$ is rational. I don't know how to go about this. I don't need Blachke products to verify this. Is there a simpler way? I do know that if we have $\phi$ is one-to-one analytic map of $D$ onto $D$, where $\phi (z)=\frac{z-a}{1-wz}$, then would that serve as a rational function that satisfies the conditions?
I am not sure how to proceed. Anyone know how to solve it?
Comment: I don't quite understand your last sentence. What do you know about $\phi$? And what is your question about $\phi$?
Comment: I meant can $f=\phi$ serve as a rational function in $D$ since it satisfies $|f(z)|\rightarrow 1$ as $|z|\rightarrow 1$?
Comment: I don't understand your question. It looks like you're trying to prove the wrong implication – the question is asked for a general $f: D \rightarrow D$, whose form you do not (a priori) know...
Comment: Maybe $\phi$ is not the right rational function. But how to prove $f$ is a rational function over $D$ if it satisfies $|f(z)|\rightarrow 1$ as $|z|\rightarrow 1$?
Answer: The standard proof of this involves noticing that the hypothesis implies that $f$ has only finitely many zeroes in the unit disc (as $|f| > 1/2$ for $|z|$ close enough to $1$), so one cn take the corresponding Blaschke product $B$ with the same zeroes and notice that $f/B, B/f$ do not vanish and $|f/B| \to 1, |B/f| \to 1, |z| \to 1$ hence by maximum modulus $|f/B| \le 1, |B/f| \le 1$ in the unit disc, hence $|f/B|=1$ there, $f=\alpha B, |\alpha|=1$
Edit later - as per comments, I thought of a different way of doing it as I realized that the hypothesis implies that $u=\log |f|$ is harmonic in a neighborhood $r <|z| <1$ (as before $f$ has only finitely many zeroes in the closed disc) and $u(z) \to 0, |z| \to 1$ which means by reflection that $u$ is extendable to a harmonic function on some annulus containing the circle $r <|z| <R, R>1$, but now $u=\Re F + c\log z$ for some analytic $F$ and some $c$ on the larger annulus and by analytic continuation $F=f$ on the original part inside the unit disc and $c=0$ hence $f$ extends to an analytic function on the larger annulus so is continuous on the closed unit disc; but now clearly we can extend $f$ to the whole plane as a meromorphic function with finitely many poles, while $\infty$ is a pole or removable depending whether $f(0)=0, \ne 0$ by the usual $f(w)=\frac{1}{\bar f(1/\bar w)}, |w| >1$ and then since $\infty$ is not essential singualarity it immediately follows that $f$ is rational so done!
Comment: Thanks Conrad. I haven't studied Blaschke products yet and this was a question from the section before Blaschke products are introduced so there must be another solution. But thanks for the input.
Comment: thought of a different way of doing it


Are there alternatives to using URL to Image Formatter?

Question: We had a need to set an image as a background element for a
 tag (see example below). When we tried to the following (with Image as formatter) it only returned the original image url, not the image URL based on the image style.
Without having to use preprocess hooks to modify the URL, we have set the display formatter to be "URL to Image" on the default View Mode and we get the desired results. If I want to use Image formatter, I had to write a preprocess hook, which I want to avoid and adding an additional module like twig_tweak seems over complicating it.
Are there any other alternatives to using the URL to Image formatter and {{ content.field_image.0['#markup] }} without having to use a preprocess hook?
Example using Image formatter
{{ content.field_image.entity.uri.value }}

Results

Example using "URL to Image" formatter
{{ content.field_image.0['#markup] }}

Results (desired results)

Alternative solution
This looks like it will get the url to image with image style.

Set formatter as URL to Image
in twig template use {{ content.field_image.0 }}
Comment: IMO better to pass the image path in as a variable.
Comment: That is, from the mytheme.theme file in a preprocess variable.
Comment: @Kevin In general the `mytheme_preprocess_image` hook works as you mentioned in mytheme.theme file, but wanted to see of alternatives.
Comment: @Kevin any thoughts on the alternative solution i just tested and found.
Answer: Background Image Formatter provides a new formatter that can do this. You will probably want a unique identifier on your target div, but this module should do the trick otherwise. There's a responsive_bg_image_formatter submodule for using responsive image styles for your bg image.
Comment: @sonfg the mere fact that this also works with Responsive Image module, it resolves multiples scenarios.


What to use in place of to_date in order to convert or cast

Question: What to use in place of to_date in order to convert it into a correct format I have tried using cast but its giving me error. the encounter_attr.attr_value is originally storing the varchar(100) but its not getting formated to YYYY-MM-DD format. Below is the code:
INSERT INTO ccsm.trn_encounter_converted_attr (person_id, encounter_id, attr_name, attr_desc, attr_type, attr_value,
                                               date_value, dt_create)
  (SELECT
     encounter_attr.person_id                         AS person_id,
     encounter_attr.encounter_id                      AS encounter_id,
     encounter_attr.attr_name                         AS attr_name,
     encounter_attr.attr_desc                         AS attr_desc,
     encounter_attr.attr_type                         AS attr_type,
     encounter_attr.attr_value                        AS attr_value,
     to_date(encounter_attr.attr_value, 'YYYY-MM-DD') AS date_value,
     cast(getdate() as date)                                     AS dt_create
   FROM ccsm.trn_encounter_attr encounter_attr
   WHERE encounter_attr.attr_type = 'timestamp');

Answer: You can used a combination of FORMAT and CAST to achieve the functionality. Simplifying your query, it would be something like this:
SELECT
    FORMAT( encounter_attr.attr_value, 'yyyy-MM-dd' ) AS 'date_value'

Comment: `FORMAT` is not supported on Azure SQL Data Warehouse as far as I'm aware?
Comment: Thanks for the update @MattUsher, I was wondering if it was a gen2 thing or something.
Answer: You can use CONVERT in Azure SQL Data Warehouse to convert strings to DATE, eg this worked for me with a VARCHAR value in the format yyyy-MM-dd or yyyyMMdd:
SELECT
    encounter_attr.person_id                         AS person_id,
    encounter_attr.encounter_id                      AS encounter_id,
    encounter_attr.attr_name                         AS attr_name,
    encounter_attr.attr_desc                         AS attr_desc,
    encounter_attr.attr_type                         AS attr_type,
    encounter_attr.attr_value                        AS attr_value,
    CONVERT( DATE, encounter_attr.attr_value )       AS date_value,
    --to_date(encounter_attr.attr_value, 'YYYY-MM-DD') AS date_value,
    cast(getdate() as date)                                     AS dt_create
FROM ccsm.trn_encounter_attr encounter_attr
WHERE encounter_attr.attr_type = 'timestamp';

CAST also worked for me so not sure why you are getting an error.  Can you post some sample data?


How to cache HTMLElement.focus in a variable?

Question: What is the correct context to store the focus function of an HTMLElement in a variable?
I tried,
var elem = document.getElementById('elem');
var focus = elem.focus.bind(document); // focus() Illegal Invocation
var focus2 = elem.focus.bind(elem); // focus2() Illegal Invocation

Answer: Wrap it into your own function:
var elem = document.getElementById('elem');
var focusElem = function(){ elem.focus(); };
focusElem();


What scale is this

Question: Hi guys I found this scale whilst playing and I really like it

st t t t t st t

st: semitone
t:  tone (whole step)

Not sure if this is an altered mode or a scale.
Any clues ?
Answer: That is a Dorian ♭2 scale, or the second mode of the melodic minor scale. It may also be called the Phrygian ♮6 scale, or sometimes the Javanese scale. @Tim points out that this scale may also go by the name Phrygidorian. Here is a link to the question about names for melodic minor modes mentioned by @Tim.
This scale can be played with ♭9sus4 chords. It is often played in modal jazz tunes.
Answer: Or Phrygian ♮6 mode maybe? If you would like to accentuate the major degree in a predominantly minor scale.
Comment: Phrygian *natural* 6 is another name for Dorian b2 (or b9).
Comment: I was trying to find the`natural` symbol and then gave up and wrote #6 (hoping that the context would be understood). Apologies. Also, although they are equivalent scales, their purposes would vary. This is why modes exist.  In one case the second degree of the Dorian scale is flattened. This could be regarded as a movement into darker territories. A composer could accentuate this. In the second case, the minor sixth degree of the Phrygian scale is raised to form a natural sixth degree. This is an opposite viewpoint than the first. Again this is all just semantic arguments from my side.
Comment: Nothing wrong with this nomenclature (natural 6th, that is). You can enter unicode codepoints on many systems with **Ctrl-Shift-U**, followed by the codepoint. ♯ is U+266F, ♭ is U+266D, ♮ is U+266E.

What scale is this


Sensitive permission issue while publishing my new app

Question: I have created an Android app after months of hard work and when it came to publishing, Google straight away rejected it.
Google says i am using a sensitive permission PROCESS_OUTGOING_CALLS. To use this permission either my app shall be a default call handler or my core feature shall fall under the exceptions they have provided. If my core feature doesn't fall under those exceptions which it actually doesn't, then i must report a new use case. I reported new use case properly and waited for two weeks NO RESPONSE. I tried publishing my app again as exception "device automation". It got rejected again saying my app doesn't fall under this exception.
Basically what my app does is, base on phone number to which call is being made, it shows some personalize data on an overlay screen over dialer. ( Cannot tell you the complete details, i am really sorry for that). No it is not a caller id or spam detection either.
I went through Google document over and over to see if i missed something.
https://support.google.com/googleplay/android-developer/answer/9214102?hl=en
I couldn't find any.
My time and money has been invested in this and i can't start showing it to people.
If someone came across same issue and able to resolve it please help.
And if more details required please comment i will provide.
Comment: i dont think you'll find answers here, see this : https://meta.stackoverflow.com/questions/255745/why-cant-i-ask-customer-service-related-questions/255746#255746
Answer: I've encountered the similar problem with Google a while ago but with this sensitive permission.
From my experience - the chances that the use case you submitted will be approved is near zero.
There are two things you can do in this case:

either extend your app to fall under one the exception cases.
or go the path I went - change your app main purpose to be the default dialer and your current main feature would be just a minor perk. (make it extendable to add more minor features in  future)

This is the easiest way to publish your app. Well frankly I see it as the only solution possible - Google is known for its strict "You are banned and I'm not gonna change my decision" policy. Youtube and Play Store have tens of thousands ban stories non of which is ended in a user beneficial way.
Hope it helps.
Comment: Thank you @Paul Ost for considering my question and answering it. I awarded the bounty.


Question about inner product and Cauchy Schwarz inequality

Question: I'm wondering where the following equality came from: $$ \langle x , y \rangle = \|x \| \| y \| \cos \theta$$
where the thing on the LHS is the inner product and $\|\cdot\|$ is the norm induced by $\langle \cdot, \cdot \rangle$. Do we need the Cauchy Schwarz inequality to prove this? I'm asking because I'm reading my notes and there is a proof of the C. S. - inequality. It's fairly short but longer than the following:
Claim: $|\langle x,y \rangle | \leq \|x \| \|y \|$
Proof: Since $\langle x , y \rangle = \|x \| \| y \| \cos \theta$ we have $-\|x \| \| y \| \leq \langle x , y \rangle \leq \|x \| \| y \|$.
Thanks.
Comment: This seems a little backwards to me. Typically the Cauchy-Schwarz inequality is used to show that the angle formula is well-defined, i.e. $\frac{\langle x,y\rangle}{\|x\|\|y\|} \le 1$ and then the angle $\theta$ is defined using the given formula.
Comment: @MattN. Not necessarily. You can also define the inner product by means of the given formula. If you are working in standard euclidean spaces, the concept of angle spanned by two vectors is elementary. In a general inner product space, the angle is *defined* by your formula.
Comment: @EuYu So it's like I suspected: We need the C.S.-inequality to prove $\|x \| \| y \| \cos \theta$.
Answer: My favorite interpretation of the identity
$$
\langle x,y \rangle = \|x\| \|y\| \cos \theta \tag{1}
$$
is that (1) defines the angle $\theta \in [-\pi/2,\pi/2]$ between the vectors $x$ and $y$. Since
$$
\langle x,y \rangle =\sum_{j=1}^n x_j y_j
$$
is the standard inner product in $\mathbb{R}^n$, the elementary Cauchy-Schwarz inequality implies that
$$
-1 \leq \frac{\langle x,y \rangle}{\|x\| \|y\|} \leq 1,
$$
and therefore there exists a unique angle $\theta \in \left[ -\frac{\pi}{2},\frac{\pi}{2} \right]$ such that (1) holds.
However, once you have fixed $x$ and $y$, the question becomes two-dimensional in the plane spanned by $x$ and $y$. There you can apply stadard elementary geometry to show that the cosine of the angle between the two vectors is given by (1).
Answer: I have seen that proof given before, so it's not out of the ordinary.
If you want to learn a proof that is independent of the cosine, there is another nice one that even for complex inner products.
It begins this way: $0\leq \langle x-\lambda y,x-\lambda y\rangle$. After expanding this into $0\leq \|x\|^2+|\lambda|^2\|y\|^2-\lambda\langle y,x\rangle-\overline{\lambda}\langle x,y\rangle$ you can use a judicious choice of $\lambda$ to get the result. (If you are satisfied with learning this for real symmetric forms then you can start with
$0\leq \|x\|^2+|\lambda|^2\|y\|^2-2\lambda\langle x,y\rangle$ instead.)
If you need some help finding the judicious choice of $\lambda$, see this.
Answer: This is generalization of $.$(dot product) in 2-D or 3-D vector space. Given two vectors $x,y$, their inner product is the product of first vector with the projection of the second vector along the direction of first vector which is equal to $||x||.||y||.\cos\theta$ where $\theta $ represents the angle between vectors in n-D vector space.


How to create borderless popup windows?

Question: So a normal popup but without the original borders and styles what comes from the Operating system.
Is there a way to style these popups?
EDIT:
Simply HTML elements are not good like
 because they cannot be on front of the windows in the OS.
Comment: Modern browsers don't let you hijack the screen this way, because the only uses for it are annoying at best and huge security risks at at worst. Why can you possibly want to do this?
Answer: 'Chromeless' pop-up windows used to be allowed in IE via showModalDialog, showModelessDialog and createPopup, but were a disaster for usability and security reasons. They allowed any web page to fake UI on any part of the screen (effectively 'click-jacking' the entire desktop, circumventing all security-related UI), and were typically used for the most obnoxious advertising.
IE introduced restrictions on them (dialog unadorned is not available to web pages, and createPopup popups can no longer obscure other windows) which are not going to go away, and other browsers never implemented them at all.
Answer: You can just display an HTML element in front of the web-page. Take a look at w3viewer.com. Click on the "About" link in the bottom left corner.
Comment: The problem with HTML elements are that they cannot be in front of other windows including the browser.
Comment: @CIRK Consider reformulating your question with "popup window" instead of just "popup".
Comment: Updated. :) But hey w3viewer is awesome!!
Answer: The answer to this is basically no. You generally cannot style windowed content in a browser...it is possible to style scrollbars and a few other elements in some browsers but nothing can be consistently done to change the browsers 'chrome'.

How to create borderless popup windows?


Gideros game engine box2d bodies

Question: I am going to make a simple Game. my code have many bodies in on timer function (every second for example):
local function onTimer()
    local sx = 20
    local sy = 20

    body = world:createBody{type = b2.DYNAMIC_BODY, position = {x = i*48, y = 50}}

    local shape = b2.PolygonShape.new()
    -- box images are 70x70 pixels. we create bodies 1 pixel smaller than that.
    shape:setAsBox(20, 20)
    body:createFixture{shape = shape, density = 1, restitution = 0.1, friction = 0.3}

    rand = math.random(1,32)
    sprite = createBoxSprite(0.6,0.6,rand)
    stage:addChild(sprite)

    actors[body] = sprite
    actors_r[sprite] = body

    table.insert(sp, sprite)
     --print (sprite)
     --print (sp[#sp])

    sprite:addEventListener(Event.TOUCHES_BEGIN, onTouchBegin,sprite)
    sprite:addEventListener(Event.TOUCHES_END, onTouchEnd,sprite)

    i=i+1
    all=all+1
    --print(all)
    if i>8 then
        i=1
    end
    if all>88 then
        print("game over")
    end

end

I want remove any body on click. but with this listeners when clicked all of sprites removed only.
function onTouchBegin(e)
    e:removeFromParent()
end

function onTouchEnd(e)

end

how to do this?
Answer: It actually works like this:
-- receive sprite as first parameter and event as second
function onTouchBegin(sprite, e)
    -- check if event hit this exact sprite
    if sprite:hitTestPoint(e.touch.x, e.touch.y) then
        -- remove it from the stage
        sprite:removeFromParent()
        -- also lets not forget about references in actors tables
        local body = actors_r[sprite]
        actors[body] = nil
        actors_r[sprite] = nil
        -- and we could either destroy the body here
        world:destroyBody(body)
        -- or reuse it to attach to the next sprite
    end
end

Gideros game engine box2d bodies


Has a pitcher ever struck out nine consecutive batters in MLB?

Question: Has any pitcher in a competitive Major League Baseball game ever struck out nine consecutive batters (in other words, the whole side)? Has anyone ever done this from first pitch, striking out the whole side in three innings?
Comment: Ryan Rupe struck out 9 straight for AAA PawSox in 2003.
Answer: Five pitchers have done it.  This ESPN article from April 14, 2012 lists the following three occurrences:

10 -- Tom Seaver, N.Y. Mets vs. San Diego, April 22, 1970
9 -- Ricky Nolasco, Florida at Atlanta, Sept. 30, 2009
9 -- Aaron Harang, L.A. Dodgers vs. San Diego, April 13, 2012

Then on September 27, 2012, Doug Fister of the Detroit Tigers struck out 9 straight Kansas City Royals batters. (link)
Then on October 3, 2015, Max Scherzer of the Washington Nationals struck out 9 straight New York Mets while throwing a no-hitter. (link)
Aaron Harang's nine straight strikeouts on April 13, 2012 came in the first 3 innings, after he gave up a single to the leadoff batter in the first inning. (link)
Comment: Great answer! Just a heads up, if you want play-by-play for those dates, you can snag them from BR. For instance here's Fister's game: http://www.baseball-reference.com/boxes/DET/DET201209270.shtml
Comment: Didn't Kent Bottenfield have some record too?


Confusion about BPM and time signature

Question: First of all, is the beat in BPM based on the quarter note or the fundamental beat of each time signature?
For example, if it's 3/2 time and it's 80 BPM, does the half note go in 80 times in a minute?
The reason I'm confused about this is because I thought quarter notes were the standard in BPM.
In other words, I thought that a half note on the BPM would take two beats to sound.
But No matter how many examples of playing I looked for, they all played half notes in sync with the one-beat time shown on the BPM.
Maybe I'm misunderstanding, but if everything is decided by the BPM... what does time signature mean? That's what I don't understand.
Comment: @Todd Wilcox  No, I mean, if the tempo is the same, 3/2 time and 3/4 time would be exactly the same. In other words, the length of a note can change relative to the tempo and can remain the same at different beats, so what's the point of determining the length of a note?
Comment: What is it... If i select that, all the comments disappear. Anyway, The question in the text has the same part as the one some guy linked to, but it has already been resolved and the remaining questions are left in the comments above.
Answer: BPM is based on the fundamental beat given in the time signature, unless otherwise indicated. So 3/2 time at 80 BPM means there are 80 half-notes per minute. In some cases, the tempo will be given in terms of a specific note value. For example, in 3/2 time, one might see <quarter note> = 160.
Comment: So, if the BPM of 2/2 and 4/4 is the same, then 2/2 is shorter than 4/4, right? that's really weird
Comment: If the 2/2 time has the same length as the 4/4 time,

2/2 time is
It should be half of the BPM of 4/4 time. That is, 2/2 time should be 30 BPM, 4/4 time should be 60 BPM.
Comment: @guss2222 It's more accurate to say that if there are 30 half-notes per minute, then there are 60 quarter-notes per minute.
Comment: OK. Anyway, it was awkward to me that note length is just relative to tempo. But maybe i get used to it. thank you.
Answer:
First of all, is the beat in BPM based on the quarter note or the fundamental beat of each time signature?

In the classical music world, and any place where music notation and music theory are taken seriously, the metronome marking (AKA "BPM") refers to the beat indicated by the time signature.
However, some DAWs another music-related software will not always conform to this real-world standard. This is most often true for compound time signatures such as 6/8. A 6/8 time signature (for example - all of this is true for 9/8 and 12/8 also) indicates that a dotted quarter note is one beat, but many DAWs or electronic metronomes will consider either an eighth note or quarter note to be one beat in 6/8 time.

For example, if it's 3/2 time and it's 80 BPM, does the half note go in 80 times in a minute?

Yes, exactly. Again, some software will not follow this convention, but it is most correct to have the half note come at 80 BPM in this example.
Comment: Metronome marking is not necessarily bpm. Beethoven for example liked to indicate a timing for whole measures, much closer to mpm in dancing.

Confusion about BPM and time signature


Checkbox - como verificar se ao menos 1 cbx foi selecionada

Question: Olá,
Tenho um conjunto de 8 checkBoxs. Alguém sabe como eu verifico se pelo menos 1 deles foi selecionado?
Obrigada
Answer: Se quiser testar um-a-um:
boolean algumSelecionado = jcbx1.isSelected() || jcbx2.isSelected() || jcbx3.isSelected() || jcbx4.isSelected()
                        || jcbx5.isSelected() || jcbx6.isSelected() || jcbx7.isSelected() || jcbx8.isSelected();

Ou um solução mais dinâmica se os JCheckBox estiverem dentro de um JPanel:
boolean algumSelecionado = false;

for (Component c : jpnl.getComponents()) {
  if (c instanceof JCheckBox && ((JCheckBox) c).isSelected()) {
    algumSelecionado = true;
    break;
  }
}

Comment: Simples e Genial! Valeu! Só troquei o .isSelected por .isChecked.
Comment: @ElaineBredaSchwaner não é `swing`? Tem que ver se a segunda opção que eu coloquei funciona então
Comment: Não sei o que é swing. Mas está funcionando, maravilha!
Answer: CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
checkBox1.isChecked();

Comment: Obrigada. Juntei sua resposta com o do colega e deu tudo maravilha.


Creating a dimension in SQL Server

Question: I have a table witch doesn't have its dimension table, for example, in the table below I have only descriptive items (Function), but not the key of the dimension table:
Id  Employee  Function
1   Chris     Bartender
2   Millena   Waiter
3   Jessica   Firefighter
4   Paul      Waiter

I don't have my DIM_Function, in other words, I wanted to create a dimension table having those values, and as the table grows up and new records are populated in my table, the another DIM_Function must have these values. I already heard about surrogate key, but don't know how to use it.
In the end, creating a fact table, the column 'Function' must store the ID that I created to the DIM_Funcion.
Thanks.
Comment: I do not at all understand what are trying to accomplish here.
Comment: I don't have a dimension table, so I'd like to create one
Comment: So what is preventing you?
Comment: Note that while it's common practice to use a surrogate key for your dimensions, it's not inherent in the dimensional model.  You can use the existing Function name as the key of the dimension.  The main role of the dimension table is to have a single place to store all the other attributes of the Function.
Answer: The basic idea of this is that you would create a dimension table of unique values with IDs (the ID column would be a primary key and an identity column), and then update your fact table with that ID. Then whenever you load more data into the fact table, you first try to retrieve the ID for each record from the dimension table. If it isn't found, you would insert a new record for it, and then retrieve the new ID. One way to do this is via a stored procedure - with the raw data having been written to a staging table - and would look something like this (using your example of 'Function'):
UPDATE Staging
SET S.FunctionID = D.FunctionID
FROM
    Staging S
    JOIN Dim_Function D ON S.[Function] = D.[Function]

IF EXISTS (SELECT * FROM Staging WHERE FunctionID IS NULL)
BEGIN

    INSERT INTO Dim_Function ([Function])

    SELECT DISTINCT [Function]
    FROM Staging
    WHERE FunctionID IS NULL
    ;

    UPDATE Staging
    SET S.FunctionID = D.FunctionID
    FROM
        Staging S
        JOIN Dim_Function D ON S.[Function]= D.[Function]
    WHERE S.FunctionID IS NULL

END

You can then insert the 'FunctionID' rather than the actual 'Function' value into the fact table (from the staging table).

Creating a dimension in SQL Server


how to find $A^{-1}$ in a matrix

Question: I have been given this matrix
$$A=\begin{pmatrix} 3 & 9 & 4 \\ 5 & 6 & 8 \\ 1 & 0 & 2 \end{pmatrix}$$
and I have to find $A^{-1}$, how would I go about doing this?
Comment: 30 days a member, 8 questions asked. Common, learn how to properly write mathematics in this site.
Comment: @eyeballfrog the edit wasn't done by the OP and the original way the question was asked does not make it clear which of the two was intended (*if even one of those two is the intended, it could still be something else entirely*).  It should be the OP who should clarify what the problem is meant to ask, not us making assumptions.
Comment: Take a look at [this page](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to learn how to type mathematics correctly on this site using $\LaTeX$ and MathJax.  As for the content of your question, "$1$" is not usually interpreted as a $3\times 3$ matrix and subtractions involving $A$ would only make sense between two $3\times 3$ matrices.  Do you mean for $1$ to be the $3\times 3$ identity matrix perhaps instead?  Or are you wanting to find the multiplicative inverse of the matrix?
Comment: is there a tutorial or something to learn how to do it?
Comment: @JMoravitz given the edit it appears he's asking for the inverse.
Comment: yes, the edit is correct. thank you projectilemotion for fixing it.
Comment: @anon420 Anyways, this should give you everything you need https://en.wikipedia.org/wiki/Gaussian_elimination#Finding_the_inverse_of_a_matrix
Comment: @anon420 You're welcome. Which way have you learnt to find the inverse of $3\times 3$ matrices?
Comment: @anon420 apparently the question is in the title and you have nothing else to say...
Answer: One of the first methods commonly taught is to row reduce $\left[\begin{array}{ccc|ccc}3&9&4&1&0&0\\5&6&8&0&1&0\\1&0&2&0&0&1\end{array}\right]$ and put this into reduced row echelon form
Assuming the inverse actually exists where initially we begin with $[A\mid I]$ the result of the row reduction will be $[I\mid A^{-1}]$.  If it is impossible to row reduce in such a way that the left-half of the augmented matrix reduces to the identity then the matrix is not invertible.
Other methods exist as well and can be found on the wiki page.
Answer: As pointed out by @JMoravitz, one strategy is to use elementary operations to reduce the  augmented matrix
$$
\left[ \begin{array}{c|c} \mathbf{A} & \mathbf{I} \end{array} \right] \to \left[ \begin{array}{c|c} \mathbf{I} & \mathbf{A}^{-1} \end{array} \right].
$$

Swap the first and third rows, this makes the top row look more like the target identity matrix.
2  Row 2: subtract 5 $\times$ row 1. Row 3: subtract 3 $\times$ row 1.
Normalize rows 2 and 3.
Subtract row 2 from row 3.
Normalize row 3.
Row 1: subtract 2 $\times$ row  3. Row 2: add one third of row  3.

$$
\left[
\begin{array}{rrr|rrr}
 3 & 9 & 4 & 1 & 0 & 0 \\
 5 & 6 & 8 & 0 & 1 & 0 \\
 1 & 0 & 2 & 0 & 0 & 1 \\
\end{array}
\right]
%
\overset{1}{\longrightarrow}
%
\left[
\begin{array}{rrr|rrr}
 1 & 0 & 2 & 0 & 0 & 1 \\
 5 & 6 & 8 & 0 & 1 & 0 \\
 3 & 9 & 4 & 1 & 0 & 0 \\
\end{array}
\right]
%
\overset{2}{\longrightarrow}
%
\left[
\begin{array}{rrr|rrr}
 1 & 0 & 2 & 0 & 0 & 1 \\
 0 & 6 & -2 & 0 & 1 & -5 \\
 0 & 9 & -2 & 1 & 0 & -3 \\
\end{array}
\right]
%
\overset{3}{\longrightarrow}
%
\left[
\begin{array}{rrr|rrr}
 1 & 0 & 2 & 0 & 0 & 1 \\
 0 & 1 & -\frac{1}{3} & 0 & \frac{1}{6} & -\frac{5}{6} \\
 0 & 1 & -\frac{2}{9} & \frac{1}{9} & 0 & -\frac{1}{3} \\
\end{array}
\right]
%
\overset{4}{\longrightarrow}
%
\left[
\begin{array}{rrr|rrr}
 1 & 0 & 2 & 0 & 0 & 1 \\
 0 & 1 & -\frac{1}{3} & 0 & \frac{1}{6} & -\frac{5}{6} \\
 0 & 0 & \frac{1}{9} & \frac{1}{9} & -\frac{1}{6} &
   \frac{1}{2} \\
\end{array}
\right]
%
\overset{5}{\longrightarrow}
%
\left[
\begin{array}{rrr|rrr}
 1 & 0 & 2 & 0 & 0 & 1 \\
 0 & 1 & -\frac{1}{3} & 0 & \frac{1}{6} & -\frac{5}{6} \\
 0 & 0 & 1 & 1 & -\frac{3}{2} & \frac{9}{2} \\
\end{array}
\right]
%
\overset{6}{\longrightarrow}
%
\left[
\begin{array}{rrr|rrr}
 1 & 0 & 0 & -2 & 3 & -8 \\
 0 & 1 & 0 & \frac{1}{3} & -\frac{1}{3} & \frac{2}{3} \\
 0 & 0 & 1 & 1 & -\frac{3}{2} & \frac{9}{2} \\
\end{array}
\right]
$$
Harvest the matrix inverse
$$
  \mathbf{A}^{-1} =
\frac{1}{6}
\left[
\begin{array}{rrr}
 -12 & 18 & -48 \\
 2 & -2 & 4 \\
 6 & -9 & 27 \\
\end{array}
\right]
$$
You should verify that $\mathbf{A} \, \mathbf{A}^{-1}= \mathbf{A}^{-1}\, \mathbf{A}=\mathbf{I}_{3}.$

how to find $A^{-1}$ in a matrix


I want to control the peak volume of guitar feedback and echo/delay feedback

Question: So, I have just set up a rig which, along with other things, allows me to create theremin like feedback from my guitar, controlling pitch through various means.
It gets pretty crazy at times, which is how I want it, but sometimes the echo will start doing its oscillatey thing or some feedback pitch will come in and it will be of a higher volume than the general sound. I don't necessarily want to stop these oscillations or the pitch, I just want them to be more a part of the overall sound rather than overpowering it. So what I was thinking is that I need to put a compressor somewhere in the chain. I would set the threshold pretty high so that the normal signal and the standard 'theremin' feedback would not be effected, only this higher volume stuff which happens would hit that roof and be limited.
My questions are: is there a particular place that I should put the compressor? It would seem logical to put it after the delay so that the oscillations would be effected by it, but that is almost last in a long pedal chain, which does not seem to be the recommended place for a compressor. Is there any quiet pedal compressors that would serve this purpose without adding or emphasizing the noise floor too much? Any other solutions?
This is my rig:

Boss TU-2 Tuner ->
Electro-Harmonix POG2 ->
Electro-Harmonix Freeze ->
ZVEX Fuzz Factory ->
ZVEX Box of Rock ->
CBC Superfuzz ->
Fulltone OCD ->
Fulltone Deja-Vibe 2 ->
Empress Tremolo ->
Empress Superdelay Vintage Modified ->
Boss FRV-1 Reverb
Comment: Boy, I'd love to see the control-loop diagram for that setup in some tool like LabView :-) .    Meanwhile - what do you mean by "theremin-like"? A theremin has no feedback. It operates directly on the spatial position of the controller (typically one's hands/arms).
Comment: Addendum:
Current options:
Boss CS-2,
Keeley,
Pigtronix Philosophers Tone

(I only have space on my board for a pedal for something that is around the size of a standard boss, fyi)
Comment: @CarlWitthoft - I think the poster is saying that he is getting feedback through his rig that sounds theremin-like in tone quality.
Comment: Yeah, I mean't tonally it is like a theremin, I also have alot of control of it by moving the guitar in relation to the amp, which although not the same technically has at least a similar feel to a theremin ;)
Comment: You say the oscillations are too heavy, but you have the tremolo and delay at the end of the chain. Try moving them back so that they have a more muted effect.
Comment: How did everything work out? I have the same issue, I love messing with feedback/delay oscillation but it gets EXTREMELY loud coming out of my Death By Audio Echo Dream, of course. I'm looking at pedal limiter or compressors to tame those volume spikes. What did you end up using? What worked best?
Answer: While I can't provide the answer, I can tell you that a compressor won't do quite what you're describing.  When the compressor is triggered it will decrease the gain of everything going through the chain.  So, if your feedback is overwhelming the mix and triggers the compressor, then everything will get compressed, making everything you want emphasized quieter.  If everything is set just right you could use the compressor to reduce the amount of feedback you can get but again, you can't get the same amount of feedback and just have it be quieter.  For example, at a specific volume (actual volume in the room) and at a specific distance from the amp, with a compressor at or toward the end of the chain, with the threshold set a little below the point of feedback and a high ratio (more than 5:1), when the feedback got too loud it would decrease the overall volume just enough to keep the feedback from going too crazy while keeping the rest of the sound close to its normal volume (volume without feedback).
The real problem you have is that feedback is generated by the loop of your guitar receiving what's coming out of the speaker then getting amplified again.  If you put a compressor in the line, the undesired feedback will decrease everything running through the chain and therefore stop feeding itself.  If you're willing to lose that feedback altogether, then a compressor might just be your answer.  You could even toggle it off to allow for feedback at times.
I don't know of any multiband compressor pedals but you could get a rack mount one.  That would allow you to compress different frequency ranges independently, so, if your undesired feedback is in a different frequency range and your desired tone isn't dependent on that freq rang, then you're in the money.  You might be able to accomplish this with a de-esser, which is basically a single band compressor.
I would also look into using the effects loop on the amp and whether to have all of the pedals in the loop or keep some out of it.  I don't know quite as much about that so I won't elaborate.
Answer: A compressor will not fix your issue. I would suggest either (in order of awesome)...

a delay pedal with either (or both) an expression input (to allow you to dial down the repeats via an expression pedal when they start to get out of control)  like the very expessive Chase Bliss Tonal Recal. Different delay pedals allow expression to be linked to different parameters (ie delay time, mix level etc.)
a delay pedal with a self oscillation mode, again the Chase Bliss Tonal Recall will do this
Specialist feedback pedals such as the Digitech FreqOut but i fear your chain is already so complex it might just add to the problem rather than offer a solution.

Other pedals are available.
Answer: If you have a delay pedal where you can insert an additional pedal just for the wet signal as send return, you could insert the compressor there - this would only compress the wet signal then.
The empress echo system can do this (it is mono then, as the second in/out is serving as send/return).
As others have mentioned, an expression pedal controlling the feedback could be another option (this is available on your Empress Superdelay Vintage Modified).


Automatically group the sub menu items in drupal 7

Question: My website contains project for following categories-

C language
Java language
Shell script

I have a custom content type "project", which has these fields as radio button. I have a menu item in main menu called project, which has above three categories as sub menu item. I want whenever I add any "C language" project, it should automatically attach as a sub menu item of "C language".
How to achieve it?
Comment: Automatically adding items to menu could be done in hook_entity_presave with menu_link_save function. In that case you just need to update the links in case category changes. Is there any reason you not to just inject them from views in theme functions (http://drupal.stackexchange.com/questions/9154/customizing-menu-link-output)?
Comment: @user20301: Can you please explain me little more? Also I didn't get that what do you mean by "just inject them from views in theme functions". Is there any other way to achieve my requirement?
Answer: You could make links list attachment with views for each taxonomy term and then add them in theme_menu_link function if the link in variables matches. Note that requires customization in template.php