How to enharmonically change the bottom note of the interval A# to E#

Question: A# to E# is a perfect fifth, and an exercise book I am working through says to enharmonically change the bottom note and identify the resulting interval.
I cannot see any possibility except rewriting it as Bb to E#, which would be a double augmented 4th.  The book has not introduced doubly augmented or double diminished intervals, and I can't even find those terms in the glossary.
Is there another possibility?  It specifically says to enharmonically change the bottom note.
Answer: Sure there are other possible enharmonic equivalents you can convert the interval to C♭♭ to E♯, but it makes the interval uglier (a tripy augmented 3rd). Even if the book misprinted this and did not intend for you to have any doubly augmented or doubly diminished it's still an acceptable exercise for you.
Intervals of a 4th and 5th are the most likely place you'll ever see a doubly diminished or doubly augmented interval due to the nature of these intervals. In fact, there may be chords you play that have these intervals.
Let's look at a C7b5#9 and a C7#5b9

C7b5#9 - C  E  Gb  Bb  D#

C7#5b9 - C  E  G#  Bb  Db

In the case of a C7b5#9, the interval between Gb and D# is a doubly augmented 5th and the Gb wants to go to an F(tonic) and the D# wants to go to an E(tonic's 7th aka leading tone). In the case of a C7#5b9, the interval between G# and Db is a doubly diminished 5th and the G# wants to go to an A(the 3rd of tonic) and the Db wants to go to a C(the 5th of tonic).
The point of these excesses is more to just drill and tax your knowledge of the topic and taking it to extremes to think most likely is the goal of that specific example. In fact in collage in my Music Theory 101 course my professor gave us interval worksheets that were very rigorous with the last interval being a triply augmented 5th (G♭♭ to D♯!) which was meant to stretch our understanding of the concept of intervals and is something that you'll almost certainty never see. It also wasn't in the book we were using and he even said as a joke "

If you ever see a G♭♭ to D♯ in the wild, drop what you are doing and contact me.

I have yet to contact him due to this.
Comment: I've been using **aug 4** to mean augmented 4th.  Is there a standard way to adapt this notation to a doubly augmented 4th?
Comment: @KyleSchlitt typically you write the augmented part twice. For example and Augmented 4th I would typically write A4 and for a doubly augmented 4th I would write AA4.
Answer: Yes, if the requirement is to change only the lower note, the only sensible alternative is Bb.  Which results in a not-very-sensible double-augmented 4th.  If this interval did occur in a piece of music, calling it a double-augmented 4th is most unlikely to be useful.  It will actually be a perfect 5th coinciding with an enharmonic shift.  Something rather different to the dual-function nature of e.g. the tritone B (Cb) - F as part of alternatively G7 or Db7.
The author of this book may be throwing in an extreme case just to test your logic!  Or he may not have thought the question through carefully enough.  What's the book?


Is there a name for this scale?

Question: I'm writing a song and I am not sure if I'm writing in an obscure scale, or just using a standard scale with added sharps and flats. All I know is I really like the sounds I'm creating on piano, and that is the most important part. I would like to start writing it out on paper (for collaboration purposes), but first I need to figure out this scale thing.
Please be gentle with me. My main education is in singing, not piano and composing... but I do OK. I'm advanced in some areas and mediocre in others. Help would be greatly appreciated.
The scale is:
D E F G G# A A# B C C# D
or of course
D E F G Ab A Bb B C Db D
The closest thing I could find was D minor blues, but that's not quite right.
Comment: Note, there are other ways of composing that don't require being in a key, or being based on a scale.
Comment: Are you writing just a lead tune, or are you writing out full chords?  If the latter,  you'll need to decide which chords are "in the key" and which have blue notes.
Answer: Just because a piece has certain notes doesn't necessarily put it into a particular key. True, if it contains C,D,E,F,G,A and B, there is a very good chance it'll be in C major (or poss. A minor) (or maybe D Dorian - the list goes on!).
But there are things called passing notes, which blend between other notes and don't always belong to the parent key. They will be your red herrings.
It will be easier to determine the key when the 'odd' notes are identified as being used on the weaker parts of the bars, so they will be more of a colouration or a way to chromatically move between other 'main' notes.
For now, it may be best to write it out with no key sig., and when it's finished, look at which accidentals occur only a few times. These will probably end up AS accidentals, with the ones occurring lots of times becoming the key sig. It does sound like it's a bluesy set of notes, and don't forget that in blues, when the tune is on the sub/dominant chord, another couple of blues notes pop up to be used, which don't feature in the key sig. anyway. But in blues writing, the m3, d5 and m7 notes don't get a mention in the key sig. in any case.
Another deciding factor will be the tonal centre, which will give a clue to the letter name of the key.
Comment: The notes with accidentals are a key part of the song, not just occasional. I started out in Dorian/D minor but then it took on a life of its own!
Comment: @musiclover238 - is there a specific reason you wrote out the notes starting on D? If the piece FINISHES on a D, then that's a good clue to the key.
Comment: If you reveal the chords you've put to it, it's another clue. If you think it's Dm, then the key sig. will be just one flat - Bb. The other notes will be accidentalised.
Answer: You're right, the key is D minor, but there is not one single scale containing all these notes. Since a piece in minor can use all notes of the natural, the harmonic, and the melodic minor scales, you already get D E F G A Bb B C C#, which are all the notes in your question except for the Ab/G#. Depending on the way it is used, the latter could be a blue note giving some bluesy feeling to the melody, or it could be an ascending approach/leading tone to the note A.
Also take a look at this answer to a related question.
Answer: We can't hear the music, so we can't tell you what the key "really" is, or even if it makes sense to talk about it being in a key.
But from a pragmatic point of view, the purpose of a key signature is to reduce the number of accidentals in the notation. So assuming all the notes occur roughly the same number of times in the piece:

No signature - 3 notes with accidentals
F# - 4 notes with accidentals (you need F natural)
F# C# - 4 (you also need C natural)
F# C# G# - 4 (... and G natural)

So sharp signatures don't gain you anything ...

Bb - still 3 notes with accidentals (you need B natural)
Bb Eb - 4 (E natural)
Bb Eb Ab - 4 (A natural)

... and neither do flats, though 1 flat (D minor) is no worse than no signature at all.
If the key note really is D, I would use one flat; otherwise, no key signature.
Bb, B, C, C#, belong to the D melodic minor scale. In "common practice notation" (the basis for classical music notation from about 1700 to 1900) you would write G# not Ab, since G# is part of the "dominant of the dominant" chord, i.e. E major.
But to repeat, if the piece doesn't sound like it's in D minor, ignore all this advice!
Answer: I noticed that with 10 notes, this scale is almost the entire chromatic scale.  It is 1 of exactly 6 scales with 10 notes.  None of these scales have widely used names, however William Zeitler, who gave names to 1490 different scales, has named yours the "Gothyllian" scale.
From inspection, you will have the easiest time writing this out if you put the key signature in C Major or F Major because either of these key signatures will let you write the music with only three accidentals.

Is there a name for this scale?


Moving WP blog to Tumblr but still use old WP server's images?

Question: I've successfully moved my old WP blog that I hosted on my server to a Tumblr blog by using the CNAME to point to it.
However, all of the Tumblr blog's photos are still hosted on my old WP blog, so they are not showing up anymore.
How can I maintain the redirect to Tumblr except for photos (png/jpg or really any file, because the only accesses for a file would be an image)?
Could I use a RewriteCond in my htaccess, or will that be overridden by the CNAME record from my blog subdomain to Tumblr's?
Answer: You can't. CNAMEing the domain delegates it to Tumblr's servers, you have no control over what it serves. You'd have to rehost your images via Tumblr, or host your old blog subdomain on a new subdomain and update all your posts' images to that new subdomain.
Comment: I'll take option 2. Genius. Thanks!


Writing into c-string

Question: my code segfaults and I don't know why.
 1  #include <stdio.h>
 2
 3  void overwrite(char str[], char x) {
 4    int i;
 5    for (i = 0; str[i] != '\0'; i++)
 6      str[i] = x;
 7  }
 8
 9  int main(void) {
10    char *s = "abcde";
11    char x = 'X';
12    overwrite(s, x);
13    printf("%s\n", s);
14    return 0;
15  }

The gdb debugger tells me, that problem is on the line 6, where I want to store a char, into c-string (if I use lvalue pointer dereferencing, it's the same problem.) This is what he says:
(gdb) run
Starting program: /tmp/x/x

Breakpoint 1, overwrite (str=0x8048500 "abcde", x=88 'X') at x.c:5
5         for (i = 0; str[i] != '\0'; i++)
(gdb) s
6           str[i] = x;
(gdb)

Program received signal SIGSEGV, Segmentation fault.
0x080483e3 in overwrite (str=0x8048500 "abcde", x=88 'X') at x.c:6
6           str[i] = x;
(gdb) q

I am learning from K&R-C book and this is simplified example from chapter 2.8 (the remove function). I have no idea where is the problem.
Answer: because char*s = "abcde"; creates string in readonly memory. try
char s[] = "abcde";

EDIT: explanation: char* is pointer, and "abcde" is created in readonly memory -> immutable.
char[] is array, which is wholly stored on stack and initialized from the memory, so is mutable
Answer: When you define a pointer to a string literal, declare it as const char *.
const char *s = "abcde";

That way, your compiler complains when you try to send that string to the overwrite() function.
const char *s = "abcde";
char t[] = "fghij";
char x = 'X';

overwrite(s, x); /* oops */
overwrite(t, x); /* ok */

Answer: Not disagreeing, but just to elaborate: Consider what would happen if the compiler allowed this. You could write:
char *s1="abcde";
char *s2="abcde";
s1[0]='x';
puts(s1);
puts(s2);

If the compiler recognizes that the two literals are the same and re-uses them, but then also allows line 3, your output would be:
xbcde
xbcde

Which is probably not what you would want. This would be particularly mysterious if the two literals were in widely-separated parts of the program.
Comment: This is why in .Net strings are immutable.  It *does* reuse the strings through something called "string interning".
Comment: @Tom Ritter - Yep, that's why .Net is a completely different platform with completely different goals than C.
Answer: Try out:
#include <iostream>
#include <cstring>

using namespace std;

void overwrite(char[], char);

int main(void)
{
        char *s = strdup("abcde");
        char X = 'X';
        overwrite(s, X);
        cout << s << endl;

        if(s!=NULL)
                delete [] s;

        return 0;
}

void overwrite(char str[], char x)
{
        for(int i=0; str[i]!='\0'; i++)
                str[i] = x;
}

Comment: Question is tagged as C ... and if you're going to check for s being NULL you could check immediately after the strdup() call, rather than using an invalid pointer.
Comment: also strdup does a malloc() ... calling delete[] on it is wrong.
Answer: my guess is the parameter definition where you define the type as an array of chars. While you are passing a pointer to a char
You could try changing the first line to this:
 void overwrite(char *str, char x) {

A char array and a char pointer are not semantically the same.
Comment: `char str[]` and `char *str` are equivalent as function arguments.
Comment: You're wrong, `char str[]` decays to `char *` when used in a parameter list.
Comment: ok.... But I'm right that they are different in some cases right? Could you elaborate in which case it is different?
Comment: @reinier, no they are the same as function parameters. Both have type char*, none of them is an array (although the first is declared as an array - the compiler won't make it an array).
Comment: i meant cases other than as a function parameter. I understand now that they are the same as used as a parameter ;^)
Comment: In other cases they surely are different. The difference shows up less in C than in C++, though. In C, an array `E[N]` is implicitly converted to a `E*` anywhere it appears, except as argument of `sizeof` or `address-of &`. So, sizeof will give you `N * sizeof(E)`, and address-of will give you `E(*)[N]`. Conceptionally, the array is different to - in some kind it's the inverse: A pointer points to an array of elements, while an array stores those elements. So in the situation that conversion occurs, it's not because of their similarity, but because of the necessity to address an element :)

Writing into c-string


Convergence of Difference of Sequences

Question: Suppose $\{x_n\}$ and $\{y_n\}$ are sequences in $\mathbb{R}$ such that $$\lim_{n \to \infty} x_n = \lim_{n \to \infty} y_n = \infty$$ and $$\lim_{n \to \infty} \frac{x_n}{y_n} = q.$$ What can we say about $$\lim_{n \to \infty} x_n-y_nq?$$
What conditions can we put on $\{x_n\}$ and $\{y_n\}$ to get the limit of $0$?
Answer: Anything can happen - you might get lucky and have the second limit be 0, but not always. For example, consider $x_n=n^2+n$ and $y=n^2$. We have that $\lim\limits_{n\to\infty} \frac{x_n}{y_n}=1$ but $\lim\limits_{n\to\infty}x_n-y_n=\infty$.
Comment: What extra conditions can we put on the sequences to have the limit be 0?

Convergence of Difference of Sequences


Eclipse-Kepler, Java 8 compilation issue "syntax errors on tokens"

Question: I am using Eclipse Kepler with jdk1.8.0.
I do not face any compilation problems in import statements related to java8 or collect construct. However I get the compilation issue in:- Dish::getName...it says.. Syntax errors on tokens, delete the tokens.
Just trying to run the following code:
<code>List<String> dishNames = menu.stream()
                              .map(Dish::getName)
                              .collect(toList());

System.out.println(dishNames);
</code>
Dish is a java object with String property name.
I have installed JDK8, added the latest JRE in eclipse Java Build Path.
Java compiler compliance.
Any hints what something silly I am missing?
Comment: I'm pretty sure if I run that code, I'll get all sorts of errors.  Could you give a [MCVE](http://stackoverflow.com/help/mcve)?  And most importantly, what is `Dish`?
Comment: Sorry, if that confused you. I was actually facing problem with "::" in Dish::getName , so I missed mentioning the POJO.
Answer: I think you missed installing support of java8 in eclipse kepler.
You can follow this link for detailed instructions.
https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler
Comment: Can you check which Kepler version are you using from Help? For Kepler you need SR2(4.3.2).
Comment: How silly of me.Thanks for the quick response. When I try to install the update, I get the following error:-Cannot perform operation, will not be installed JDT patch with Java8 support.Any help?


Open set as a finite union of closed sets

Question: I was studying a text (http://arxiv.org/abs/math/0510331) when in a proof the author stated:
!proof][1 http://www.ime.unicamp.br/~ra151530/mann.png
If I got it right, the author says that $\widetilde{U}$ (a nonempty open connected set in $\mathbb{C}^n$) is a finite union of closed sets, so one of these closed sets must have nonempty interior.
I tried to prove it but I could not. I think it is a very simple topological detail I am missing.
Comment: Do you know the Baire category theorem? https://en.wikipedia.org/wiki/Baire_category_theorem
Answer: Suppose for contradiction there are closed sets $F_1, \ldots, F_n$ with empty interior and a nonempty open set $G$ such that $G = F_1 \cup \ldots \cup F_n$.
Then $G_1 = G \setminus F_1 = G \cap (\mathbb{C}^n \setminus F_1)$ is nonempty (because $F_1$ has empty interior) and open, because it is an intersection of two open sets.
Again, the set $G_2 = G_1 \setminus F_2$ is also nonempty open. Continue this to deduce $G_n = G_{n-1} \setminus F_n$ is nonempty, which contradicts the assumption $G = F_1 \cup \ldots \cup F_n$.


Como verificar as versões dos módulos instalados no Python?

Question: Instalei dois módulos no Python via anaconda (conda install):

zipfile36;
MySQLdb.

Utilizando o prompt do anaconda consigo obter a versão de ambos e de todos os meus outros módulos utilizando o comando:
conda list

Porém gostaria de saber, como diretamente no código consigo obter a versão desses módulos? Possuo uma aplicação que irei necessitar disso.
Comment: Geralmente os pacotes possuem em `__init__.py` uma variável com a versão. Você pode acessar o código fonte de cada pacote e verificar qual variável deve avaliar.
Answer: Não existe uma forma 100% determinística de um módulo informar a sua versão. O que existem são convenções e sugestões.
O PEP 8 sugere aqui que se use uma variável de módulo chamada __version__ para armazenar a versão, porém, isso é apenas uma sugestão - não é obrigatório que os módulos tenham essa variável.
Alguns módulos seguem essa sugestão e disponibilizam a versão em __version__, porém outros usam variáveis alternativas como VERSION ou VER ou simplesmente version. Existem também módulos que usam uma função get_version() capaz de gerar o número dinamicamente baseado em tags do sistema de controle de versão utilizado.
Por sorte, tanto o MySQLdb quanto o zipfile36 que você quer usam o método sugerido pelo PEP 8. Então você pode usar:
import zipfile36
print(zipfile36.__version__)

import MySQLdb
print(MySQLdb.__version__)

Comment: Excelente, muito obrigado! Por sorte vou poder utilizar assim então rs
Answer: A título de curiosidade, vi nesta resposta do SOen uma alternativa à resposta do @nosklo, onde se usa o módulo pkg_resources do setuptools.
import pkg_resources
pkg_resources.get_distribution("requests").version  # nome do pacote no PyPI
# '2.20.0'

Comment: ótima observação Fernando! Realmente testei aqui e também obtive o mesmo resultado que utilizando ( __version__ ) uma boa alternativa também obrigado!
Comment: Vale lembrar que o `pkg_resources` tenta uma variedade de formas para buscar a versão do módulo e se ele não conseguir encontrar, é lançado um `ValueError`. Na documentação que eu linkei explica isso.
Comment: Verifiquei isso, fiz alguns testes e o erro quando não encontra é esse:

`DistributionNotFound: The 'urllib' distribution was not found and is required by the application`
Comment: Mas o módulo `urllib` é nativo, porque você quer saber a versão dele? Bastaria ver a versão do python então.
Comment: não queria, só fiz um teste para verificar como viria o erro
Comment: Teria que ser alguma lib instalada pelo  `pip` para testar
Comment: Entendi, realmente não havia me atentado a isso vlw!


Same collection of digits between two integers Javascript

Question: I'm trying to check if two integers contain the same collection of digits.
equivalent(123, 321) // -> true
equivalent(413, 1453) // -> false
equivalent(2002, 2200) // -> true
equivalent(542, 545) // -> false

I've started off the function with:
function equivalent(a,b) {
    let stringA = a.toString().match(/[1-9]/g);
    let stringB = b.toString().match(/[1-9]/g);
}

I didn't know whether to use a hash map to map each occurrence of a digit and increment along, however I couldn't check if two objects are equal to each other.

Which method is most optimal(in terms of space/time complexity) and which method is most easily readable or both? Thanks.

Edit: Apologies for not elaborating a bit more on my question. I want to check if two integers contain the same digits and the same amount of those digits.
Comment: Would `.toString().length` be easier?
Comment: If I understand correct, apart from having the same length, the digits in them also should be the same, right?
Comment: If it is always going to be positive integers (i.e., just digits, no commas, decimal points, or negative signs), @j08691 's suggestion is the way to go.
Comment: Ooooh . . . I see what you're saying, @KapilKashyap . . . so "123" and "124" would be `false`, because the digits aren't the same.  Wow . . . confusing question.
Answer: Use a simple loop and remove each character from the second string using String#replace and later check second string is empty(empty means both contains same amount of digits).

console.log(
  equivalent(123, 321), // -> true
  equivalent(413, 1453), // -> false
  equivalent(2002, 2200) // -> true
);

function equivalent(a, b) {
  // convert into string
  a = a.toString();
  b = b.toString();
  // iterate over each character
  for (var i = 0; i < a.length; i++)
  // replace each character from second string
    b = b.replace(a[i], '');
  // finally check second string is empty
  return b == '';
}
Answer: You could sort the figures and compare the joined strings.

function equivalent(a, b) {
    return [...a.toString()].sort().join('') === [...b.toString()].sort().join('');
}

console.log(equivalent(123, 321));
console.log(equivalent(413, 1453));
console.log(equivalent(2002, 2200));

Approach with a hash table

function equivalent(a, b) {
    var hash = Object.create(null);
    [...a.toString()].forEach(a => hash[a] = (hash[a] || 0) + 1);
    [...b.toString()].forEach(b => hash[b] = (hash[b] || 0) - 1);
    return Object.keys(hash).every(k => !hash[k]);
}

console.log(equivalent(123, 321));
console.log(equivalent(413, 1453));
console.log(equivalent(2002, 2200));
Comment: @kdizzle, it spreads a string into an array of single characters.
Comment: @PranavCBalan, why do you think so?
Comment: the question contains `let`, so it's an ES6 question.
Comment: What is the `...` spread operator accounting for in your method? Thanks.
Answer: Convert to string, split it, sort it, combine it and compare.

function equivalent(a, b) {
  return a.toString().split("").sort().join("") === b.toString().split("").sort().join("");
}

console.log(equivalent(123, 321));
console.log(equivalent(413, 1453));
console.log(equivalent(2002, 2200));

Could add length check so the other processing does not need to take place.


Which clustering technique to use for 1D data with 2 Gaussian distributions without training data?

Question: I have 1D data which is likely to be 2 Gaussian distributions overlapped. I do not have training data but I know one should be slightly high contributed from few points and another is very broad with almost of data. Are there some clustering techniques possible to use for this purpose?
Answer: Gaussian mixture modeling optimizes the fit of Gaudeians to your data.


Why do I have a contradiction when using "Leibniz criterion" and " Integral test"

Question: $$\sum \frac{(-1)^{n}}{n\cdot \ln n}$$
leibniz criterion: The series $\frac{1}{n\cdot \ln n}$ is monotonically decreasing. Also $\lim_{n \to \infty}\frac{1}{n\cdot \ln n}=0$
Thus, the the series is convergent.
however, these criteria also met with "integral test".
Using Integral test: $\int \frac{1}{x\cdot \ln x}dx$ using the formula $\int \frac{f'(x)}{f(x)}dx=\ln (f(x))$
I get: $\ln (\ln x)$
solving the latter with "infinity" as an upper bound gets me a result of "Divergent" which for some reason contradicts Leibniz criterion that gets me an answer of "Convergent"
why is that?
Comment: You have proved that $\sum\frac{(-1)^n}{n\ln n}$ is convergent and that $\sum\frac1{n\ln n}$ is divergent. No contradiction so far.
Comment: Note, you have proved that the series is conditionally convergent
Answer: The integral test relates $\sum f(n)$ and $\int f(x)$ where $f$ is a non-negative function.
In your case, you've selected $f(x)=\frac{1}{x\ln x}$, but the terms of your series are not given by $f(n)$. They're given by $(-1)^nf(n)$.
Answer: The series of interest is $\sum_{n\ge 2}^\infty \frac{(-1)^n}{n\log(n)}$, not $\sum_{n\ge 2}^\infty \frac{1}{n\log(n)}$.
By applying Leibniz's test, you showed correctly that the alternating series, $\sum_{n\ge 2}^\infty \frac{(-1)^n}{n\log(n)}$, converges.
And by using the integral test on the series $\sum_{n\ge 2}^\infty \frac{1}{n\log(n)}=\sum_{n\ge 2}^\infty \left|\frac{(-1)^n}{n\log(n)}\right|$, you showed correctly that the series, $\sum_{n\ge 2}^\infty \frac{(-1)^n}{n\log(n)}$, does not converge absolutely .
There is no contradiction here.
Comment: Please let me know how I can improve my answer.  I really want to give you the best answer I can.


How do i send multi dimentional array from browser url and recieve in php API

Question: I want to access the indexed multi dimensional array sent from my app.for the test purpose i am sending request by url.
xyz/?array1[0][id]=2&array1[0][value]=400
this is how i am receiving and echoing.
  ?php
  $price[][]=$_REQUEST['array1'];
  echo $price[0]['id'];
  echo $price[0]['value'];

but i am getting array1 as $price[0]['id'] and $price[0]['value'] empty.
also in error log its showing id and value not defined. Any help would be great.
Comment: did you try `echo $_REQUEST['array1[0][id]'];`?
Comment: ya it didnt display anything
Answer: You just don't need the [][] after your $price.
$price=$_REQUEST['array1'];

echo $price[0]['id'];
echo $price[0]['value'];

Answer: Your code is the equivalent of
$price = array(
    0 => array(
        0 => $_REQUEST
    )
)

which means you need $price[0][0]['id']['value'] instead
Comment: no its like `$price[0]['id']` and `$price[0]['value']`


Foreach Array incrementando outro array

Question: to com uma duvida em realizar um foreach e incrementar um outro auxiliar para realizar um insert no banco, vejam só:
Quando realizo um envio do meu form via post tenho o seguinte array como resultado:
array (size=2)
  'quantidade' =>
    array (size=8)
      0 => string '10' (length=2)
      1 => string '11' (length=2)
      2 => string '15' (length=0)
      3 => string '22' (length=0)
      4 => string '10' (length=0)
      5 => string '9' (length=0)
      6 => string '0' (length=0)
      7 => string '35' (length=0)
  'produto' =>
    array (size=8)
      0 => string '11' (length=1)
      1 => string '18' (length=1)
      2 => string '19' (length=1)
      3 => string '21' (length=1)
      4 => string '22' (length=2)
      5 => string '25' (length=2)
      6 => string '29' (length=2)
      7 => string '22' (length=2)

Como estou usando o CodeIgniter pra pegar os dados do Form, to usando a seguinte estrutura:
foreach ($this->input->post() as $chave => $valor) {
  //o array aux aqui
}

Alguma ideia de como gerar este resultado, pegando o primeiro valor de cada elemento e inserindo em um array auxiliar:
Tipo assim:
$array_aux[0] = array('quantidade' => 10, 'produto' => 11)
...
$array_aux[7] = array('quantidade' => 35, 'produto' => 22)

Comment: Não seria melhor fazer um for normal e 'controlar' os dois indices por `$i` ?
Comment: Ola @rray, então to usando o codeigniter e pegando essas variaveis atraves do $this->input->post(), por isso pensei no foreach. Saberia me auxiliar a usar o for pra isso?
Comment: Esse array auxiliar vc vai mandar para o banco? qual a estrutura dele?
Comment: sim, vou enviar ao banco. A estrutura do BD é id, quantidade. Que no exemplo que passei o id é igual a chave produto
Answer: Provavelmente o que você quer é isso:
array_combine( array $keys , array $values );

No seu caso:
$array_aux = array_combine( $array['quantidade'], $array ['produto'] );

Veja funcionando no IDEONE
Manual:

http://php.net/manual/pt_BR/function.array-combine.php
Comment: Opa @Bacco valeu pela ajuda com apenas uma linha. No caso to usando o CodeIgniter, e recebo os dados atraves do $this->input->post(), por isso usei o foreach, saberia me auxiliar neste caso?
Comment: Se o $this->input->post() retornar array, só fazer $array = $this->input->post() antes da linha acima, e se retorna objeto, só trocar o $array['quantidade'] por ->quantidade no objeto, e o mesmo no produto. Poste um print_r do seu $this->input->post() no pastebin e o link aqui nos comentários pra eu ver. De qq jeito, dá pra usar a mesma lógica.
Comment: Ok meu caro, vou realizar o post la no pastebin, de qualquer forma ja coloquei na descricao da pergunta o que voce pediu. No mais valeu pela ajuda novamente
Comment: De qq forma, não precisa de loop. A linha acima resolve. Mas mande o link do pastebin aqui que eu vejo se adapto.
Comment: Mas não se esqueça, ponha um print_r mesmo, pq ai dá pra ver toda estrutura.
Comment: Então, analisando o print estamos no caminho correto, so nao consegui montar as chaves como no exemplo $array_aux[0] = array('quantidade' => 10, 'produto' => 11), visto que isto será inserido no banco. Vou dar uma olhada aqui atraves do que vc me mandou
Comment: @tkmattos `$array = $this->input->post();` `$array_aux = array_combine( $array['quantidade'], $array ['produto'] );`
Comment: SIm @Bacco entendi esta logica, to tentando é montar aqui a ideia de criar os arrays pra inserir no banco, visto que cada par de produto e quantidade será um insert no banco, por isso vou precisar colocar nome nas chaves
Comment: @tkmattos eu tou indo pelo que vc colocou na pergunta, fica dificil imaginar como vc tá fazendo a inserção. Conforme for, abra uma pergunta com o código da inserção propriamente dito.
Comment: Tranquilo meu caro, daqui ja ajudou muito, vou tentar modificar com base no que me mandou, e coloco a resposta da pergunta pra ajudar a todos tbm. Mais uma vez obrigado pela ajuda de sempre!!!
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/48473/discussion-between-tkmattos-and-bacco).
Answer: $arrayForm = array();

foreach($array['quantidade'] as $key => $val){
    $arrayForm[] = array(
                   'quantidade' => $val,
                   'produto'    => $array['produtos'][$key]
    );
}

echo '
';
print_r($arrayForm);
echo '
';

Comment: Exatamente, pega a mesma chave dos dois arrays.
Comment: perfeito sua logica @Gumball saiu exatamente como precisava, e ainda posso adicionar novas chaves. O esquema é usar a variavel $key pra pegar as posicoes das minhas chaves correto?
Answer: Se vai montar um array e fazer um insert via querybuilder do CI, normalmente os nomes das chaves devem ser os nomes das colunas no banco de dados, nesse caso pode usar a função array_map() para combinar os valores.
A função anônima retorna um array que terá como valor o primeiro (e demais) item de  $a1['quantidade'] e $a2['produto'].
$a1 = array('quantidade' => array(10,11,15,22,10,9,0,35));
$a2 =  array('produto' => array(11,18,19,21,22,25,29,22));

$r = array_map(function($q, $p){ return ['quantidade' => $q, 'produto' => $p] ;}, $a1['quantidade'], $a2['produto']);

echo "
";
print_r($r);

Saída:
Array
(
    [0] => Array
        (
            [quantidade] => 10
            [produto] => 11
        )

    [1] => Array
        (
            [quantidade] => 11
            [produto] => 18
        )

    [2] => Array
        (
            [quantidade] => 15
            [produto] => 19
        )

    [3] => Array
        (
            [quantidade] => 22
            [produto] => 21
        )

    [4] => Array
        (
            [quantidade] => 10
            [produto] => 22
        )

    [5] => Array
        (
            [quantidade] => 9
            [produto] => 25
        )

    [6] => Array
        (
            [quantidade] => 0
            [produto] => 29
        )

    [7] => Array
        (
            [quantidade] => 35
            [produto] => 22
        )

)

Foreach Array incrementando outro array


A functional equation while attempting to integrate a function differently: $ f(x)-f(y) = z \bigl( f(xz) - f(yz) \bigr) $

Question: Here is a functional equation :

For $f : \mathbb (0,\infty) \to \mathbb R$ continuous non-constant, $f$ has the property that for every $b,x,y>0$, $f(1) = -1$  and
$$
f(x) - f(y) = b \bigl( f(bx) - f(by) \bigr) \text .
$$

I want to show that the only possible solutions are $f(x) = a-\frac {a+1}x$ for some constant $a$, without using any form of calculus(with the exception of limits, if required).
For an approach, there are too many free variables, so I tried to set $b$ to a certain value, say $b=2$. Then I get:
$$
f(x)-f(y) =  2 \bigl( f(2x) - f(2y) \bigr) \text .
$$
but I don't know how to proceed : I can't use this to find a particular value of any single $x$, because the value of $x$ depends on the value of $2x$, and so on, so there's no way of proceeding I can think of. This also makes me feel that there is missing information, but that doesn't seem likely because in the presence of three constraining variables and domain, some kind of uniqueness must hold, right?
Setting $g(x) = xf(x)$ and trying to prove that it is constant has also proved futile, for the same reason as before.

Context : This post contains the question I am trying to answer.
Let $f : (0,\infty) \to \mathbb R$ be a function satisfying $f(x)-f(y) = \int_y^x \frac{\mathrm dt}{t^2}$ for all $y,x>0$. Under the fix $f(1) = -1$, we know that there is a unique function $f$ satisfying these conditions, given by $f(x) = -1 + \int_1^x \frac{1}{t^2}\,\mathrm dt = -\frac 1x$. I attempted to locate such an $f$ without using calculus, but rather using functional equations.
The logic was as follows : let $b>0$ be arbitrary, and in the expression $\int_x^y \frac{\mathrm dt}{t^2}$, make the change of variables $bt =u$, so that $b\,\mathrm dt = \mathrm du$. Accordingly, we get:
$$
f(x)-f(y) = \int_x^y \frac{\mathrm dt}{t^2} = \int_{bx}^{by} \frac{b^2 \,\mathrm du}{u^2} = b \int_{bx}^{by} \frac{\mathrm du}{u^2} = b \bigl( f(bx)-f(by) \bigr) \text .
$$
and thus the functional equation comes out. Now if I can use non-calculus techniques to prove that this functional equation is satisfied only by $-\frac 1x$ then I will have obtained the antiderivative of $\frac 1{x^2}$.
Comment: I'm afraid that won't work: $\displaystyle f(x)=a-\frac{a+1}x$ (for any constant $a$) satisfies your functional equation, and $f(1)=-1$.
Comment: @ProfessorVector Thank you very much! There's something missing now : according to the second part of the question, I derived a functional relation that I thought was enough to decide the nature of $f$. The function that you mention is the specific case of my function for $a=0$, which gives $f(x) = -\frac 1x$. Can you prove that this is the list of all possible functions i.e. that if a function $f$ satisfies the constraints then there exists a constant $a$ such that $f(x) = a-\frac{a+1}{x}$? I will edit the question to reflect this.
Comment: Yes, my goal was definitely to get a functional equation and I tried to reduce part of the problem to algebraic techniques. You got me completely right. I [love](https://math.stackexchange.com/q/3556795/460967) solving functional equations too much. Thanks to you, I have refreshed my math backround. I learned new things and realized my mistakes. Thanks a lot.
Comment: @lonestudent Yes, good to see you visited here. I struggled for some time to solve this functional equation, Professor's answer is brilliant.
Comment: By the way, I want you to know that I upvoted your question (and given answers) before. It doesn't mean anything, but I wanted to say.  Functional equations are my favorite math problems.
Comment: @lonestudent Thank you for the confirmation. I just thought you should know, but functional equations go way beyond just recreational mathematics : I discussed some of this in a conversation with Professor below. If you don't understand some of the things I mention, you can read them up, or be informed that they are super important concepts, especially iteration theory.
Answer: In this case, more free variables is better: let's assume $$f(x)-f(y) = z(f(xz)-f(yz))$$ for $x,y,z>0$. Then,
$$f(x)-z\,f(xz)=f(y)-z\,f(yz),$$ meaning that expression depends only on $z$:
$$f(x)-z\,f(xz)=g(z).$$ Letting $x=1$, we see that $g(z)=-1-z\,f(z)$, i.e. we have
$$f(x)-z\,f(xz)=-1-z\,f(z).$$ Exchanging $x$ and $z$, we get
$$f(z)-x\,f(xz)=-1-x\,f(x),$$ multiplying the first equation by $x$ and the second one by $z$ and subtracting, we arrive at
$$x\,f(x)-z\,f(z)=-x+z+xz(f(x)-f(z)).$$ This equation has to hold for any $x,z>0$, substituting any constant value $z_0\neq1$ for $z$, we see that $x\,f(x)=ax+b$. Since $f(1)=-1$, this means $b=-a-1$, i.e. $x\,f(x)=ax-a-1$.
Comment: For functional equations, that's a rather standard technique, but then, that's a somewhat exotic subject. Essentially, you need it only in mathematical contests. :-)
Comment: Excellent, the exchange followed by the subtraction was what I was missing. Thank you so much, may you be granted myriad wishes, Professor.
Comment: True, I believe functional equations as a rigorous mathematical subject go into iteration theory (which I though of because $\frac 1x$ is an involution of order $2$ so a switch of $x \to \frac 1x$ could produce something, did not happen though), Schroder's equation, then of course functional equations involve the derivative and integral so there's PDE and integro-differential equations. But yes, for contests I read up a few books, none of which had this because they were into Cauchy's equation and standard forms which I knew did not apply.
Comment: I used PARI/GP and Mathematica to check if $\,f(x):=ax-a-1\,$ is a solution of the equation  $\,f(x)-f(y) = z(f(xz)-f(yz))\,$ and it failed to check. the left side is $\,a(x-y)\,$ while right side is $\,z^2a(x-y).$
Comment: @Somos Hi, you seem to have used $f(x) = ax-a-1$ for the PARI/GP and Mathematica check, which I see from the results you obtain. Professor had $f(x) = \frac{ax-a-1}{x} = 1-\frac{a-1}{x}$, which works for any $a$ , because here $f(x) = a - \frac{a-1}{x}$, so $f(x) - f(y) = (a-1)(\frac{1}{x} - \frac 1y)$,then replacing $x,y$ by $bx,by$ just puts a $\frac 1b$ on the RHS, so this satisfies the equation.
Comment: @Teresa Lisbon In my contest time, iteration theory didn't exist, yet, and there was essentially one book about functional equations (by Aczel). Of course, there are (or might be) serious applications (e.g. http://math.fau.edu/yiu/PSRM2015/yiu/Backup031229/Journals/functionaleqt.pdf), but it's not a very popular subject.
Comment: @ProfessorVector Thank you for the additional information. I just wanted to say that function iteration theory is now more of a global phenomena outside contest math, because plenty of approximation algorithms involve application of an operator or function to an initial input, and the result is proved to be a solution to some equation. (For example, the Picard-Lindelof iteration for DEs) Then we use structure preservation of that operator to assert things like monotonicity of the solution and so on : I've seen this in queue theory. The subject, including the contest part is fascinating.
Comment: @TeresaLisbon Okay, it was my misreading. The equation is $x\,f(x)=ax-a-1$ and I just neglected the initial $x$ because it was unexpected. It should have been $f(x)=\frac{ax-a-1}x$ which is mathematically equivalent, but that is **not** what was written.
Comment: @Somos true , I agree with you.
Answer: Suppose we have a functional equation
$$ x(f(x)-f(x\,y)) = z(f(z)-f(z\,y)) \tag{1}$$
which holds for all $\,x,y,z>0.\,$
We want solutions for $\,f(x)>0.$ Since this
equation holds for all $\,x,z>0\,$ both sides depend only on $\,y.\,$ call it $\,g(y).\,$
Thus if $\,z=1\,$ we define
$$ g(x) := f(1)-f(x). \tag{2} $$
Equations $(1)$ and $(2)$ imply that
$$ f(x) - f(x\,y) = g(y)/x. \tag{3} $$
Add equations $(2)$ and $(3)$ to get
$$ f(1) - f(x\,y) = g(x) + g(y)/x. \tag{4} $$
Rewrote the left side of equation $(4)$ using equation $(2)$ to get
$$ g(x\,y) = g(x) + g(y)/x. \tag{5} $$
Eliminate the denominator in equation $(5)$ by defining
$$ h(x) := x\,g(x). \tag{6} $$
Rewrite equation $(5)$ using equation $(6)$ to get
$$ h(x y) = h(x)y + h(y). \tag{7} $$
Define the limit
$$ c := \lim_{x\to 0} h(x). \tag{8} $$
The limit as $\,x\to 0\,$ of equation $(7)$ is
$$ c = c\,y + h(y). \tag{8} $$
Solve equation $(8)$ for $\,h\,$ to get
$$ h(y) = c - c\,y. \tag{9} $$
Using equations $(9)$, $(6)$, and $(2)$ to get
$$ f(x) = f(1) + c - c/x. \tag{10} $$
The original equation in the question was
$$ f(x)-f(y)=b(f(b\,x)-f(b\,y)). \tag{11} $$
Replacing $\,y\,$ by $\,x\,y\,$ and
$\,b\,$ with $\,z/x\,$ in this equation
is equivalent to our equation $(1)$.
EDIT: This version is simpler than my previous one
from Jan 22, 2021.
Comment: I understood your method, +1, it is ciertamente correct. Having said that, the other answer was quicker to the same conclusion and also was slightly simpler, which I require since I am using this to answer a question for a beginner user. Thank you very much, also note the comment I made at the end of Professor's answer.


Graph 3-colors coloring with the use of the given function

Question: I have the function three_colorability(n,E) which gives output true(when the graph with those edges and vertices can be coloured with 3 colors) or false(if not). (!there is no parameter to know what has been coloured already)
We assume that this function works in linear time complexity.
I have to make 3-coloring algorithm of the given undirected graph G with the use of the given function which will work in polynomial time.
I can't come to the solution to this.
Answer: Add 3 new nodes, named C1, C2 and C3 by colour they represent. Add edges between new nodes (C1,C2), (C2,C3) and (C1,C3). If three_colorability(V,E) is true than three_colorability(V+{C1,C2,C3},E+{(C1,C2),(C2,C3),(C1,C3)}) is also true.
For each (original) vertex v, three_colorability() returns true for at least one of graphs with added two edge of {(v,C1), (v,C2), (v,C3)}. E.g. if three_colorability() returns true for graph with added edges {(v,C2), (v,C3)}, it means that v can be coloured with colour 1.
To find colour for all vertices, incrementally find vertex colour and add these 2 edges in a graph.


elasticsearch nest support of filters in functionscore function

Question: I am currently trying to implement a "function_score" query in NEST, with functions that are only applied when a filter matches.
It doesn't look like FunctionScoreFunctionsDescriptor supports adding a filter yet.   Is this functionality going to be added any time soon?

Here's a super basic example of what I'd like to be able to implement:

Runs an ES query, with basic scores
Goes through a list of functions, and adds to it the first score where the filter matches

"function_score": {
    "query": {...},  // base ES query
    "functions": [
        {
            "filter": {...},
            "script_score": {"script": "25"}
        },
        {
            "filter": {...},
            "script_score": {"script": "15"}
        }
    ],
    "score_mode": "first",  // take the first script_score where the filter matches
    "boost_mode": "sum"  // and add this to the base ES query score
}

I am currently using Elasticsearch v1.1.0, and NEST v1.0.0-beta1 prerelease.
Thanks!
Answer: It's already implemented:
_client.Search<ElasticsearchProject>(s =>
            s.Query(q=>q
                .FunctionScore(fs=>fs.Functions(
                    f=>f
                        .ScriptScore(ss=>ss.Script("25"))
                        .Filter(ff=>ff.Term(t=>t.Country, "A")),
                    f=> f
                        .ScriptScore(ss=>ss.Script("15"))
                        .Filter(ff=>ff.Term("a","b")))
                .ScoreMode(FunctionScoreMode.first)
                .BoostMode(FunctionBoostMode.sum))));

Comment: Gah, wonder how I missed that.  I've tried it and it works.  That's awesome, thanks!
Answer: The Udi's answer didn't work for me. It seems that in new version (v 2.3, C#) there's no Filter() method on ScoreFunctionsDescriptor class.
But I found a solution. You can provide an array of IScoreFunction. To do that you can use new FunctionScoreFunction() or use my helper class:
class CustomFunctionScore<T> : FunctionScoreFunction
    where T: class
{
    public CustomFunctionScore(Func<QueryContainerDescriptor<T>, QueryContainer> selector, double? weight = null)
    {
        this.Filter = selector.Invoke(new QueryContainerDescriptor<T>());
        this.Weight = weight;
    }
}

With this class, filter can be applied this way (this is just an example):
        SearchDescriptor<BlobPost> searchDescriptor = new SearchDescriptor<BlobPost>()
            .Query(qr => qr
                .FunctionScore(fs => fs
                    .Query(q => q.Bool(b => b.Should(s => s.Match(a => a.Field(f => f.FirstName).Query("john")))))
                    .ScoreMode(FunctionScoreMode.Max)
                    .BoostMode(FunctionBoostMode.Sum)
                    .Functions(
                        new[]
                        {
                            new CustomFunctionScore<BlobPost>(q => q.Match(a => a.Field(f => f.Id).Query("my_id")), 10),
                            new CustomFunctionScore<BlobPost>(q => q.Match(a => a.Field(f => f.FirstName).Query("john")), 10),
                        }
                    )
                )
            );

Comment: This is the only solution i've found with the latest version of Nest (2.x and up). But we used to be able to make multiple functions delimited with a comma. The solution you have provided is good, but doesn't make it easy to add conditional logic which is important in my case.


Why is "jump" between two primes (almost) always prime or 1 up to 1000?

Question: While looking at prime numbers between 1 to 1000 I noticed that the number of non-primes between prime numbers are almost always also prime or 1. In other words, if we take the prime gap,
$$
g_n=p_{n+1}-p_n,
$$
for prime numbers larger than 2, and subtract 1 from it, we almost always get a prime number or 1. In the cases (between 1 to 1000) where $g_n-1$ is not equal to a prime number or 1 it is instead equal to 9. Below is a figure I made to better explain:

What is the reason that the "jump length" (i.e. numbers in red or blue above) between primes are either 1, 9 or also prime when looking at 1 to 1000?
Comment: General note:  it's tempting, but risky, to read too much into numerical computations for such small numbers.  In this case, there are many small primes, so any random-y list of small odd numbers is going to contain lots of primes.  To study anything like this, I'd want to look at much larger primes.
Comment: You can assume [Cramer's conjecture](https://en.wikipedia.org/wiki/Cram%C3%A9r%27s_conjecture): $g_n \approx O\left((\log{p_n})^2\right)$ and draw one or two conclusions, like $\left((\log(1000))^2\right)\approx 48$, consider only even gaps, that's $24$ and there are $14$ primes (or "jumps") between $1$ and $48$ (excluding $2$), thus the chance is $\frac{14}{24}=\frac{7}{12}>\frac{1}{2}$.
Comment: Because the gap between consecutive primes is always an even number, except for $3-2=1$
Comment: It does,  $p_{282}=1831, p_{283}=1847$ and then again almost immediately, $p_{295}=1933,p_{296}=1949$.
Comment: Absolutely agree with @lulu on this one. "Law of small numbers." A cursory look at http://oeis.org/A046933 seems to confirm your hypothesis. But look at the "b-file": it's still mostly primes, but 9, 15, 25 make more appearances the further along you go.
Comment: Is it just a coincidence that 15 never appears as a "jump length"?
Comment: these are super insightful comments! So if I understand correctly; because primes > 2 are always uneven, their prime gap is always even and prime gap - 1 is thus always uneven, and when looking at *small* numbers almost all (except 9 and 15) uneven numbers are (incidentally) primes or 1 because the prime gap is still too small?
Answer: This phenomenon was studied by Odlyzko, Rubinstein and Wolf (with whom I have written a paper on primes).

Definition: An integer $d$ is called a jumping champion for a given $x$ if d is the most common gap between consecutive primes up to $x$.

They postulated that most common gap between primes or the jumping champions are the product of prime numbers i.e. the first jumping champion is $2$. The after some time, $2*3 = 6$ takes over as the next jumping champion. At around $1.74*10^{35}$, the number $2*3*5 = 30$ takes over as the next jumping champion. At around $10^{425}$, the number $2*3*5*7 = 210$ takes over as the next jumping champion and so on.
This means that per your definitions, if we subtract $1$ from the gap between primes then the most common results would be $1$ initially. This would be overtaken by $5$ which would in turn be overtaken by $29$ and this would be overtaken by $209$ as you go higher up the number line.
So it is a co-incidence that $5, 29$ are prime but $209 = 11*19$ is not. This means if you looked large enough to reach the range of $209$, you would actually have the opposite conclusion based on experimental evidence that gap between prime minus $1$ is often a non prime.
Equivalent question: With the above arguments, your question is equivalent to

How often is the primorial number $22.214.171.124\cdots p - 1$ a prime?

Reference:

Odlyzko, A.; Rubinstein, M.; and Wolf, M. "Jumping Champions."
Experiment. Math. 8, 107-118, 1999.
Comment: Nice answer! Do you know whether any result of this form (classifying jumping champions) has been proven, or if it's all just conjecture so far?
Comment: As with most problems with primes, we have way more conjectures on jumping champions than theorems. However you can find a few theorems on them by Goldston in this paper. https://arxiv.org/pdf/1102.4879.pdf


Moving from min pent to aeolian? How does tension resolve work

Question: I want to apologize if my question itself is an error.
Thats due to everything you can find about music theory being very abstract, with little info about practical application
If my question itself is an error then dont answer it directly,  but put me on the right track for understanding things
You have the minor pentatonic scale
In which a lot of licks on guitar sound ok as long as you use proper rythm and techniques like bending, because it is hard to hit a wrong note
Now i want to extend from the minor pentatonic scale to the aoelian mode, which has the same notes plus 2 extra.
Now there is some concept about slightly dissonant sounding notes(tension), which need to be resolved. Which notes need to be resolved and to what(like half step above /under, to pentatonic scale notes or to chordtones)?
And how does this apply to moving from the min pentatonic to the aeolean mode? Or are there other things i need to know when moving to aeolean mode
Thx in advance for you answers
Answer: ti->do and fa->mi
Minor pentatonic: La do re mi so la
Aeolian: adding ti and fa -> la ti do re mi fa so la
ti and fa are leading tones: ti resolving up to do, fa resolving down to mi.
But both are used as passing tones in both directions, up and down.
Answer: Looking at the chord changes you are playing over and picking out which notes are affecting those changes, then accentuating those notes along with those changes, is a place to start.
Here's an example that focuses on accentuating the notes in Aeolian mode that are not part of the Pentatonic scale.
You're playing over a simple i-v vamp, let's make it Em-Bm. (Bolded are non-Pentatonic scale notes.)

E Aeolian mode notes are E, F#, G, A, B, C, D. (I, II, bIII, IV, V, VI, bVII)
Em chord tones are E, G, B. (I, bIII, V)
Bm chord tones are B, D, F#. (V, bVII, II)

Depending on what you're trying to say, as the vamp moves between chords you can accentuate that 1/2-step between F# (II) and G (bIII), or you can accentuate the whole-step between D (bVII) and E (I). The former uses the non-Pentatonic note F# (II), so will add a bit of flavor not found in the Pentatonic scale.
If you expand that vamp to include a iv, in this case Am (A, C, E,) you now also have the non-pentatonic C (VI) note, a 1/2-step from B (V) in either Em or Bm, and a whole-step from D (bVII) in Bm, and can focus on those note changes when moving between those chords.
As far as resolution from tension goes, generally aim to resolve on a chord tone, the I, (b)III or V note, and you'll be pretty safe. The extent of that tension and how you build it is up to you. In the i-v vamp above, you might try to utilize that C (VI) note as a tension builder, as theoretically it will suggest the missing Am (iv) chord and then resolve nicely as you move back to a chord tone on the change. Another way might be to preempt the chord change with a chord tone in the resolution chord that is not part of the leading chord.
If you have a loop station, loop a simple vamp like the one above (or if you don't, find a simple backing track online,) and then spend some time just playing with the notes that make the chord changes (II - bIII, bVII - I, II - I) and the tension resolution from the VI (VI - V, VI - bVII) and you'll get a feel for what those movements can actually say from a musical standpoint.
As a final note, the above movements between notes are all linear, in that they move from one note to the next without skipping over any other notes in the key. Naturally there are non-linear movements to explore, as well (ie: VI - I, II - V.)
Answer: Firstly bending notes has absolutely nothing to do with playing notes from pentatonic. make no mistake about that. There are two notes missing from Aeolian compared with pentatonic (minor). They are the two notes which are hardest to play in the right place.
You need to isolate those two notes, and work out - by listening very carefully - how they fit into the bigger plan of playing. We cannot say exactly where you should put those two notes - there isn't a simple route to take. Use ypur ears, and work out what you hear as good places to use those two extra notes, which are the key, probably, to being a great player rather than one who relies on purely using the minor pentatonic, which is, after all, is the panacea for so many players.
Comment: They are also (perhaps not coincidentally!) the harmonically "tastiest" notes - to my ear at least.

I should add it would be of great benefit not only to listen to how it sounds when you use those notes but also to listen to how great players use those notes (Miles is surely the canonical choice but feel free to pick someone to your personal taste!)


How do you access variables stored in a Direct Editor table from an Installshield vbscript or javascript custom action?

Question: I need to read or change the value of "Enable32bitAppOnWin64" in the IsIISProperty table from within a custom action. Now while I can access properties from the Property Manager by Session.Properties("PropertyName")
I can't see how to do the same for the property tables.
I have tried {ISIISProperty1}, [ISIISProperty1] and Session.Properties("ISIISProperty1") all with no success.
How do I achieve this?
Any help will be appreciated.
Thanks
Answer: I haven't been able to find any information on accessing properties from installer tables in a custom action. What I did find out was that you can write some installer SQL syntax to update the tables from custom actions, but this was overkill and I couldn't get it to work.
What I have been able to do is use property substitutions with the ISIISProperty table.

I created two new properties in the Property table called ASPBITNESS and ALLOWTHIRTYTWOBIT which are set to x86 and true respectively by default.
Then I edited the ISIISProperty table in the direct editor and replaced the values for Enable32bitAppOnWin64 and AspNetVerBitness with [ALLOWTHIRTYTWOBIT] and [ASPBITNESS] respectively. Interestingly, the Enable 32-Bit Applications setting shows "No" in the InstallShield designer, even though the [ALLOWTHIRTYTWOBIT] property is set to true by default.
Finally, I have a custom action that conditionally (NOT REMOVE and VersionNT64 and IIS_VERSION > "#6") fires at the very start of the install to change those values accordingly.

The custom action code code is:
On Error Resume Next

' change the properties for x64 systems
if SYSINFO.bIsWow64 <> 0 then
    Session.Property("ASPBITNESS") = "x64"
    Session.Property("ALLOWTHIRTYTWOBIT") = "false"
end if

Before the MSI logs showed:

InstallShield 12:09:19: SetVRootProperties for virtual directory
  'MyWebApp', app ''
  InstallShield 12:09:19: IIS7 check for ASP.NET version bitness on application pool
  'MyAPPPool', install is requesting 'x86'
  ...
  InstallShield 12:09:19: SetAspversion: machine is 64-bit and
  IIS running in a bit mode other than the currently selected mode
  ...
  InstallShield 12:09:19: Error with IISRT: -2172
  ...
  CustomAction ISIISInstall returned actual error code 1603 (note this may not be 100% accurate if translation happened inside sandbox)

After these changes the applications install and the logs now show:

MSI (s) (D4:1C) [10:53:18:662]: Doing action: Set64Bit
  Action 10:53:18: Set64Bit.
  Action start 10:53:18: Set64Bit.
  MSI (s) (D4:0C) [10:53:18:678]: Created Custom Action Server with PID 912 (0x390).
  MSI (s) (D4:D0) [10:53:18:709]: Running as a service.
  MSI (s) (D4:D0) [10:53:18:709]: Hello, I'm your 32bit Impersonated custom action server.
  MSI (s) (D4!1C) [10:53:18:725]: PROPERTY CHANGE: Modifying ASPBITNESS property.
  Its current value is 'x86'. Its new value: 'x64'.
  MSI (s) (D4!1C) [10:53:18:725]: PROPERTY CHANGE: Modifying ALLOWTHIRTYTWOBIT
   property. Its current value is 'true'. Its new value: 'false'.

And then:

InstallShield 10:53:20: SetVRootProperties for virtual directory
  'MyWebApp', app ''
  InstallShield 10:53:20: IIS7 check for ASP.NET version bitness on application pool
  'MyAppPool', install is requesting 'x64'
  InstallShield 10:53:20: Application pool Enable32bitAppOnWin64 value is 'false'
  InstallShield 10:53:20: ASP.NET version can be set for 64-bit.
  InstallShield 10:53:20: Configuring ASP .NET version:
  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir


Converte uma consulta SQL em Consulta no Entity

Question: Fiz esse pergunta em um outro fórum, mas o conteúdo da discussão seguiu outro caminho por isso resolvi abri esse tópico. Sem fugir do assunto, como faço para realizar essa consulta SQL:
select p.RA, p.Nome, p.Modulo, a.Descricao
from inscricao as i, participante as p, Atividade as a
where i.ParticipanteId = p.ParticipanteId and
   i.AtividadeId = a.AtividadeId order by p.Modulo

em uma consulta usando o Entity?
Comment: Coloque as entidades na pergunta!
Answer: Tente fazer da seguinte forma.
var query = (from i in dbContext.inscricao
                     join p in dbContext.participante on i.ParticipanteId equals p.ParticipanteId
                     join a in dbContext.Atividade on p.AtividadeId equals a.AtividadeId
                     where i.periodo == ViewModel.periodo && i.data == ViewModel.data.
                     select new {
                         RA = p.RA,
                         Nome = p.Nome,
                         Modulo = p.Modulo,
                         Descricao = a.Descricao
                     })
                     .OrderBy(x => x.Modulo);

Comment: Obrigado Marconcilio, e agora estou a apanhando da sintaxe para incluir nessa mesma consulta mais duas condições: Na tabela de inscrições preciso verificar se os campo periodo == ViewModel.periodo e data == ViewModel.data.
Comment: alterei a query


How to automate setting up Services or RESTws?

Question: It looks like xmlrpc.php is of almost no use. I want to use XML-RPC to control my sites but I don't want to set up Services or RESTws manually on dozens of sites. It doesn't look like Services has support for Features.
Is there a way to automate setting up Services or RESTws on many sites at once?
Answer: The Services module doesn't have any Drush integration (Drush being the standard way of running code against multiple sites at once). So I would assume that nothing currently exists that does what you're looking for.
However, Services does use the ctools plugin API, so you can probably piggy-back off that to some degree. It will mean you need to code a Drush plugin yourself to manage the export/import, but you can probably get most of the boilerplate code from somewhere like the Drush CTools Export Bonus module.
Bottom line, I think it's unlikely you'll find a pre-existing solution for this, you'll probably have to get stuck in and make your own.
Comment: Darn. Fortunately [it looks like](https://www.drupal.org/project/restws) this will be better in d8.
Comment: Yeah REST is in core in D8, and I'd wager resources/servers will be config entities, so you'll be able to import/export them easily.


Can you use 2.5mm mono jack cables as a quick plug system in a guitar control panel?

Question: I've picked up a guitar kit that has a simple solderless system for connecting the pickups to the control panel. You can see it here:

I was wondering if it's possible to use a 2.5 mm mono jacks to do the same job.
GuitarFetish do a Kwikplug system to swap pickups:
https://www.guitarfetish.com/GFS-Guitar-Pickups_c_7.html
But I thought using 2.5mm mono jacks would be even simpler. Is this possible?
Comment: IMO a crimpable quick plug is far simpler to install than wiring up male & female mono jacks
Answer: Providing the pups have only two wires emanating from them, yes, any male/female connectors will do the same job. Seen plenty of 2.5mm mono jacks, but not so many sockets which would go on the end of a sheathed wire, but don't see why they're not available. Or mount them onto the pcb.
Comment: idk outside the UK, maybe Radio Shack still have a high street presence somewhere… It's the kind of thing in the UK you could just walk into Tandy/Maplins to buy - but in the UK those type of retailers are all gone. RS is your go-to for anything like that these days - https://uk.rs-online.com/web/c/connectors/av-connectors/jack-plugs-sockets/?applied-dimensions=4294876964,4294432000
Comment: @Tetsujin - haven't used RS for several years, but I reckon it's the only retail outlet for this sort of electrical goods in UK left, sadly. But it's all good quality.


Link to a text file

Question: In Drupal 8, how do we make a link to a text file? The file is not managed by Drupal, but hosted within the same domain.
For example, I'm building a Drupal 8 module and on its help page I'd like to link to its README.txt file. I thought this would work:
$readmePath = drupal_get_path('module', 'my_module') . '/README.txt';
$readmeLink = \Drupal\Core\Link::fromTextAndUrl(
  t('README'),
  \Drupal\Core\Url::fromUri($readmePath)
)->toString();

This unfortunately does not work, and instead throws a 500.
Answer: The API documentation for Url::fromUri() states the following regarding the $uri parameter:

string $uri: The URI of the resource including the scheme. For user
  input that may correspond to a Drupal route, use internal: for the
  scheme. For paths that are known not to be handled by the Drupal
  routing system (such as static files), use base: for the scheme to get
  a link relative to the Drupal base path (like the  HTML
  element). For a link to an entity you may use
  entity:{entity_type}/{entity_id} URIs.

So I think that you would need to do,
$readmePath = drupal_get_path('module', 'my_module') . '/README.txt';
$readmeLink = \Drupal\Core\Link::fromTextAndUrl(
  t('README'),
  \Drupal\Core\Url::fromUri('base:' . $readmePath)
)->toString();

Link to a text file


Relationship between Binomial and Beta distributions

Question: I'm more of a programmer than a statistician, so I hope this question isn't too naive.
It happens in sampling program executions at random times. If I take N=10 random-time samples of the program's state, I could see function Foo being executed on, for example, I=3 of those samples. I'm interested in what that tells me about the actual fraction of time F that Foo is in execution.
I understand that I is binomially distributed with mean F*N. I also know that, given I and N, F follows a beta distribution. In fact I've verified by program the relationship between those two distributions, which is
cdfBeta(I, N-I+1, F) + cdfBinomial(N, F, I-1) = 1

The problem is I don't have an intuitive feel for the relationship. I can't "picture" why it works.
EDIT: All the answers were challenging, especially @whuber's, which I still need to grok, but bringing in order statistics was very helpful. Nevertheless I've realized I should have asked a more basic question: Given I and N, what is the distribution for F? Everyone has pointed out that it's Beta, which I knew. I finally figured out from Wikipedia (Conjugate prior) that it appears to be Beta(I+1, N-I+1). After exploring it with a program, it appears to be the right answer. So, I would like to know if I'm wrong. And, I'm still confused about the relationship between the two cdfs shown above, why they sum to 1, and if they even have anything to do with what I really wanted to know.
Comment: Nice idea.  The statistical assumption is that the interruption is independent of the execution state, which is a reasonable hypothesis.  A **binomial confidence interval** is a good tool to use to represent the uncertainty.  (It can be an eye-opener, too: in your 3/10 situation, a symmetric two-sided 95% CI for the true probability is [6.7%, 65.2%].  In a 2/10 situation the interval is [2.5%, 55.6%].  These are wide ranges! Even with 2/3, the lower limit is still less than 10%.  The lesson here is that something fairly rare can happen twice.)
Comment: If "what you actually wanted to know" is "the actual fraction of time that Foo is in execution," then you are asking about a Binomial confidence interval or a (Bayesian) Binomial credible interval.
Comment: @whuber: Well I've used the random-pause method of performance tuning for over 3 decades, and some other people have discovered it too. I've told people that if some condition is true on 2 or more random-time samples, then removing it would save a good fraction of time. HOW good a fraction is what I've tried to be explicit about, assuming we don't know a Bayesian prior. Here's the general flame: http://stackoverflow.com/questions/375913/what-can-i-use-to-profile-c-code-in-linux/378024#378024 and http://stackoverflow.com/questions/1777556/alternatives-to-gprof/1779343#1779343
Comment: @whuber: Thanks. You're right. Something more useful is the expected value. As far as priors go, I point out that if you only see something once, it doesn't tell you much *unless* you happen to know the program is in an infinite (or exceedingly long) loop.
Comment: I think all of the answers and comments have certainly been enlightening and correct, but no one really touched on the interesting equality that @MikeDunlavey put in his original post. This equality can be found on the Beta wikipedia https://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function but there is no description given of why that is the case, its just stated as a property.
Answer: Consider the order statistics $x_{[0]} \le x_{[1]} \le \cdots \le x_{[n]}$ of $n+1$ independent draws from a uniform distribution.  Because order statistics have Beta distributions, the chance that $x_{[k]}$ does not exceed $p$ is given by the Beta integral
$$\Pr[x_{[k]} \le p] = \frac{1}{B(k+1, n-k+1)} \int_0^p{x^k(1-x)^{n-k}dx}.$$
(Why is this?  Here is a non-rigorous but memorable demonstration.  The chance that $x_{[k]}$ lies between $p$ and $p + dp$ is the chance that out of $n+1$ uniform values, $k$ of them lie between $0$ and $p$, at least one of them lies between $p$ and $p + dp$, and the remainder lie between $p + dp$ and $1$.  To first order in the infinitesimal $dp$ we only need to consider the case where exactly one value (namely, $x_{[k]}$ itself) lies between $p$ and $p + dp$ and therefore $n - k$ values exceed $p + dp$.  Because all values are independent and uniform, this probability is proportional to $p^k (dp) (1 - p - dp)^{n-k}$.  To first order in $dp$ this equals $p^k(1-p)^{n-k}dp$, precisely the integrand of the Beta distribution.  The term $\frac{1}{B(k+1, n-k+1)}$ can be computed directly from this argument as the multinomial coefficient ${n+1}\choose{k,1, n-k}$ or derived indirectly as the normalizing constant of the integral.)
By definition, the event $x_{[k]} \le p$ is that the $k+1^\text{st}$ value does not exceed $p$.  Equivalently, at least $k+1$ of the values do not exceed $p$: this simple (and I hope obvious) assertion provides the intuition you seek. The probability of the equivalent statement is given by the Binomial distribution,
$$\Pr[\text{at least }k+1\text{ of the }x_i \le p] = \sum_{j=k+1}^{n+1}{{n+1}\choose{j}} p^j (1-p)^{n+1-j}.$$
In summary, the Beta integral breaks the calculation of an event into a series of calculations: finding at least $k+1$ values in the range $[0, p]$, whose probability we normally would compute with a Binomial cdf, is broken down into mutually exclusive cases where exactly $k$ values are in the range $[0, x]$ and 1 value is in the range $[x, x+dx]$ for all possible $x$, $0 \le x \lt p$, and $dx$ is an infinitesimal length.  Summing over all such "windows" $[x, x+dx]$--that is, integrating--must give the same probability as the Binomial cdf.
Comment: It's a little late, but I finally got time to sit down and re-create your argument. The key was "multinomial coefficient". I had tried figuring it out using plain old binomial coefficients and I was getting all balled up. Thanks again for a nice answer.
Comment: @Mike See http://meta.stats.stackexchange.com/q/218/919 .
Comment: I appreciate the effort. I'm going to have to really study this because it's not my "native tongue". Also, I'm seeing a lot of dollar signs and formatting stuff. Is there something I don't know about that makes it look like real math?
Comment: I'm a little slow, but you're getting through to me.
The denominator of the Beta integral is exactly what I came up with.
Answer: Look at the pdf of Binomial as a function of $x$:  $$f(x) = {n\choose{x}}p^{x}(1-p)^{n-x}$$ and the pdf of Beta as a function of $p$: $$g(p)=\frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)}p^{a-1}(1-p)^{b-1}$$
You probably can see that with an appropriate (integer) choice for $a$ and $b$ these are the same. As far as I can tell, that's all there is to this relationship: the way $p$ enters into the binomial pdf just happens to be called a Beta distribution.
Comment: Maybe somebody will chime in with a full response, but in an "intuitive" explanation we can always hand-wave away constants (like $n+1$) that do not depend on the variables of interest ($x$ and $p$), but are required to make the pdf add/integrate to 1. Feel free to replace the "equality" signs with "proportional to" signs.
Comment: I know those look almost the same, but if I substitute y for n-x, and if I take the Beta pdf and substitute x for a-1 and y for b-1 I get an extra factor of (x+y+1), or n+1. i.e. (x+y+1)!/x!/y!*p^x*q^y. That seems to be enough to throw me off.
Comment: I take a different view of "intuitive" explanations.  In some cases we don't care too much about constants, but in this case the *crux* of the matter is to see why an n+1 appears and not an n.  If you don't understand that then your "intuition" is incorrect.
Comment: Good point. I think I'm getting closer to an understanding. I'm still trying to be able to say what x tells you about the p distribution, and why those two cdfs sum to 1.
Answer: As you noted, the Beta distribution describes the distribution of the trial probability parameter $F$, while the binomial distribution describes the distribution of the outcome parameter $I$. Rewriting your question, what you asked about was why
$$P(F \le \frac {i+1} n)+P(I \le fn-1)=1$$
$$P(Fn \le i+1)+P(I+1 \le fn)=1$$
$$P(Fn \le i+1)=P(fn<I+1)$$
That is, the likelihood that the observation plus one is greater than the expectation of the observation is the same as the likelihood that the observation plus one is greater than the expectation of the observation.
I admit that this may not help intuit the original formulation of the problem, but maybe it helps to at least see how the two distributions use the same underlying model of repeated Bernoulli trials to describe the behavior of different parameters.
Comment: Regarding your revision: Yes, $F\sim Beta(I+1,N-I+1)$, as long as your sampling intervals are long enough that each observation is independent and identically distributed.

Note that if you want to be Bayesian about it and specify a nonuniform prior distribution for what you expect the actual proportion to be, you can add something else to both parameters.
Comment: I appreciate your take on it. All the answers are helping me to think about the question and possibly understand better what I'm asking.
Comment: I revised the question, if you care to take a look. Thanks.
Comment: @sesqu, could your answer be somehow related to my question here: http://stats.stackexchange.com/questions/147978/probability-distribution-for-a-proportion-based-on-continuous-quantities? I would appreciate your thoughts on it.
Answer: Summary: It is often said that Beta distribution is a distribution on distributions! But what is means?
It essentially means that you may fix $n,k$ and think of $\mathbb P[Bin(n,p)\geqslant k]$ as a function of $p$. What the calculation below says is that the value of $\mathbb P[Bin(n,p)\geqslant k]$ increases from $0$ to $1$ when you tune $p$ from $0$ to $1$. The increasing rate at each $p$ is exactly $\beta(k,n-k+1)$ at that $p$.

Let $Bin(n,p)$ denote a Binomial random variable with $n$ samples and the probability of success $p$. Using basic algebra we have
$$\frac d{dp}\mathbb P[Bin(n,p)=i]=n\Big(\mathbb P[Bin(n-1,p)=i-1]-\mathbb P[Bin(n-1,p)=i]\Big).$$
It has also some nice combinatorial proof, think of it as an exercise!
So, we have:
$$\frac d{dp}\mathbb P[Bin(n,p)\geqslant k]=\frac d{dp}\sum_{i=k}^{n}\mathbb P[Bin(n,p)=i]=n\Big(\sum_{i=k}^{n}\mathbb P[Bin(n-1,p)=i-1]-\mathbb P[Bin(n-1,p)=i]\Big)$$
which is a telescoping series and can be simplified as
$$\frac d{dp}\mathbb P[Bin(n,p)\geqslant k]=n\mathbb P[Bin(n-1,p)=k-1]=\frac{n!}{(k-1)!(n-k)!}p^{k-1}(1-p)^{n-k}=\beta(k,n-k+1).$$

Remark To see an interactive version of the plot look at this. You may download the notebook or just use the Binder link.
Comment: This probably most directly addresses the aspect of the question regarding CDF's, +1, binder notebook definitely helpful too. It is not clear to me personally though how a differential identity might have a combinatorial interpretation / proof, although maybe it is related to an identity involving conditional probabilities? I don't know  / understand, tbh, in any case the ideas and results in this answer are definitely interesting.
Answer: In Bayesian land, the Beta distribution is the conjugate prior for the p parameter of the Binomial distribution.
Comment: Yes, but why is this the case?
Comment: It's quite mathy but here's an exhaustive answer https://towardsdatascience.com/beta-distribution-intuition-examples-and-derivation-cf00f4db57af
Answer: Can't comment on other answers, so i have to create my own answer.
Posterior = C * Likelihood * Prior (C is a constant that makes Posterior integrated to 1)
Given a model that uses Binomial distribution for likelihood, and Beta distribution for Prior. The product of the two which generates the Posterior is also a Beta distribution. Since the Prior and Posterior are both Beta, and thus they are conjugate distributions. the Prior (a Beta) is called conjugate prior for the likelihood (a Binomial). For example, if you multiply a Beta with a Normal, the Posterior is no longer a Beta. In summary, Beta and Binomial are two distributions that are frequently used in Bayesian inference. Beta is Conjugate Prior of Binomial, but the two distributions are not a subset or superset of the other.
The key idea of Bayesian inference is we are treating the parameter p as a random variable that ranges from [0,1] which is contrary to frequentist inference approach where we are treating parameter p as fixed. If you look closely to the properties of Beta distribution, you will see its Mean and Mode are solely determined by $\alpha$ and $\beta$ irrelevant to the parameter p . This, coupled with its flexibility, is why Beta is usually used as a Prior.
Answer: Here is an intuitive explanation that works for me:
$Binomial(n, p)$:
When repeating a Bernoulli trial with $p$ probability $n$ times. The chance of exactly $k$ successes is:
$$Binomial_\mathit{pmf}(\pmb{k}, n, p) = {n\choose \pmb{k}} p^{\pmb{k}} (1-p)^{n-\pmb{k}}$$
$Beta(n, k)^*$:
For a fixed $n$ and $k$, given probability $p$, calculate the probability, $p'$, of getting $k$ in the former experiment. Then multiply this $p'$ by $n+1$ to get $k'$, the most probable (interpolated) outcome if we have done the experiment with $p'$ (conceptually this is like the mode of $Binomial(n, p')$, only it allowes for non-integer values):
$$Beta_\mathit{pdf}(\pmb{p}, n, k) = \underbrace{(n+1) \overbrace{{n \choose k} \pmb{p}^k (1-\pmb{p})^{n-k}}^{p'=Binomial_\mathit{pmf}(k, n, \pmb{p})}}_{k' \approx mode(Binomial(n, p'))}$$
$\small{*}$ I'm using ${n \choose k}$ to emphasize the similarity with the $Binomial$. To get the actual $Beta$ function we need to replace $\cdot!$ with $\Gamma(\cdot+1)$, which interpolates the factorial for non-integer values.
Note 1: If $p$ is close to $k/n$, k′ is larger.
Note 2: If the parameter $n$ is larger we are more certain of the result (the concentration is higher).
Note 3: The get the common formulation for the $Beta(\alpha,\beta)$ function:
$$k \to \alpha - 1$$
$$n \to \alpha + \beta- 2$$
Note 4: When replacing $\cdot!$ by $\Gamma(\cdot+1)$, $Beta(n, k)$ is actually defined for real-valued $n$ and $k$, with ranges $n > k - 1$ and $k > -1$. We can think of things like -0.3 successes out of -1.1 Bernoulli trials as interpolations from the integer $0 \le k \le n$ cases.
Note 5: $Beta(n=0, k=0) \equiv Uniform(0,1)$
Note 6: $\int_0^1(n+1){n\choose k} p^k (1-p)^{n-k} \,dp = 1$
Comment: $$(n+1){n\choose k} \pmb{p}^k (1-\pmb{p})^{n-k}$$how did you derive this?
Comment: So it is a likelihood and can be above 1. But still where does the multiplication with a factor n+1 come from. Why is it not something like $$1-\left(1- {n\choose k} \pmb{p}^k (1-\pmb{p})^{n-k}\right)^{n+1}$$ according to $$p(\text{at least one event in k trials}) = 1 -(1 - p(\text{one event in one trial}))^k$$
Comment: @SextusEmpiricus I think Thomas Bayes derived it :).
See https://youtu.be/UZjlBQbV1KU?t=1074 (though his story is different)
Comment: This is supposed to be an intuitive explanation. Nothing more.
(I did replace 1 / BetaFunc with the (N+1) * binomial coefficient, is this the issue?)
Comment: *"The chance of at least one of the experiments having exactly k successes is"* I have difficulties to imagine how that equals $n+1$ time the probability of having exactly k success in a single run of the experiment. For instance when p=0.5, n=2 and k=1 then the probability equals 1.5 which makes no sense.
Comment: Yes, it's a PDF not a PMF. I'll rephrase.
Comment: You're right. I edited my answer.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/107931/discussion-between-amit-portnoy-and-sextus-empiricus).
Comment: I see now. The first version made me confused. What you seem to be saying now is that the beta distribution is actually similar as the likelihood for $p$ with the binomial distribution. But why is that intuitive? It is not clear *why* it is like that. We can not do the same trick with other distributions so why does it work here while it doesn't for other cases? Is there some special property that makes it work, or is it just a coincidence? And why did you choose $n+1$? It is a parameter that normalizes the likelihood function, but is that the reason, or is there some more/other logic behind.
Comment: I am saying that it doesn't work for other cases, but I would actually have to check that out. Maybe there is some symmetry principle.
Comment: I don't know, but I think it may have something to do with the support size of the Binomial. In any case, I'm interested to know if there is any known symmetry principle. $1/(n+1)$ comes up analytically from integrating the likelihood of p.
Comment: Regarding "beta distribution is actually similar to the likelihood for p". I think this is how beta was viewed by Bayes. Start with the binomial likelihood for p, and find the constant that makes the integration works.
Comment: I believe that the beta distribution is foremost the conjugate prior distribution of the binomial distribution. The connection here is the relation $$cdfBeta(I, N-I+1, F) + cdfBinomial(N, F, I-1) = 1$$ which is a different thing then the relationship as conjugate prior.
Comment: I don't know the actual historical progress, but I've seen it presented as starting from the likelihood and finding a constant that makes it into a PDF. The fact that it happens to be the conjugate prior may have been just a nice coincidence (or intuition on Bayes part).
Comment: What I mean is that conjugate prior relates to this relationship between the pdf <-> likelihood (and related to that you refer to Bayes, which is not very clear and a bit handwaving). ---- The issue that is in this question is the relationship between **cumulative distribution functions**. You mention a relationship between the beta distribution and the binomial distribution, but that seems to me to be a *different* relationship. It is not clear what this has to do with the relationship between the CDF's.


How to perform partial correlation analysis among multiple columns and controlling by multiple covariates?

Question: I want to perform partial correlation analysis among multiple columns controlling by multiple covariates, and then extract r and p-value. My real data have some missing values.
I found that this answer (Pairwise partial correlation of a matrix, controlling by one variable) might be useful, so I adjusted this method into my code. Because I have missing values, so I cannot use ppcor::pcor.test(), which is described as 'Missing values are not allowed', to achieve my goal.
Here I use the built-in dataset mtcars to display the problem I met.
# load "ggm" packages to perform partial correlation analysis
library(ggm)

# subset mtcars dataset and make some datapoints as missing values
mydata <- cbind(mtcars[1:8])
mydata[4:10,3] <- rep(NA,7)
mydata[1:5,4] <- NA

# perform partial correlation analysis among the first 6 columns with the last two columns as covariates
sapply(1:(ncol(mydata)-2), function(x) sapply(1:(ncol(mydata)-2), function(y) {
  if (x == y) 1
  else ggm::pcor(c(mydata[,x], mydata[,y], mydata[,7], mydata[,8]),var(mydata))
}))

# error:
Error in S[u, u] : subscript out of bounds

I got error at this step and could neither perform partial correlation nor extract r and p-values.
Many thanks to you to help me!
Ella
Comment: It seems that `ggm::pcor` function just drop the column containing missing values. Does anyone know which function that can perform partial correlation analysis would delete the rows with missing values rather than dropping the columns?
Answer: You don't need to pass the column values in pcor function. You can pass column number or column names. Try :
sapply(1:(ncol(mydata)-2), function(x) sapply(1:(ncol(mydata)-2), function(y) {
   if (x == y) 1
   else ggm::pcor(c(x, y,7,8),var(mydata))
}))

#           [,1]       [,2] [,3] [,4]       [,5]       [,6]
#[1,]  1.0000000 -0.7208025   NA   NA  0.5717984 -0.8260219
#[2,] -0.7208025  1.0000000   NA   NA -0.6969510  0.7414846
#[3,]         NA         NA    1   NA         NA         NA
#[4,]         NA         NA   NA    1         NA         NA
#[5,]  0.5717984 -0.6969510   NA   NA  1.0000000 -0.5510354
#[6,] -0.8260219  0.7414846   NA   NA -0.5510354  1.0000000

Comment: Awesome, it works. Thank you, @Ronak Shah. It seem that `pcor` function just drop the column containing missing values, rather than deleting the row containing missing values.
Comment: Thank you for this answer! Would you direct me how to get p-value? Thank you!


Alterar tabela com javascript jquery

Question: Possuo uma tabela de pedido criada dinamicamente, o usuário seleciona o item, a quantidade, e se é para empréstimo ou não, e adiciona o item na tabela.
Eu precisava que, ao adicionar novamente um item que já está inserido na tabela (por exemplo o mouse, cujo ID é 8) e que a coluna empréstimo também possua o mesmo valor, ao invés de adicionar uma nova linha para o mouse, aumentar a quantidade da linha já existente na tabela, e eu não sei como fazer.
Então eu preciso, ao adicionar um novo produto, verificar todas as linhas da tabela na coluna de ID's se já existe o ID desse produto que está sendo inserido e se a coluna EMPRESTIMO dessa linha também possui o mesmo valor da que está sendo inserida, se as 2 condições forem verdadeiras, ao invés de adicionar uma nova linha, apenas aumentar a quantidade da linha já existente.

   Item
   Quantidade
   Empréstimo
   Ações

 8
 Mouse
 2
 Sim
 <button class="btn btn-large btn-danger" onclick="RemoveTableRow(this)" type="button">Remover</button>

Onde: a primeira coluna que está escondida é o ID do item, a segunda o nome, a terceira a quantidade que está sendo pedida, a terceira se é um item para empréstimo ou não, e a quarta uma ação para remover a linha
Comment: Que tipo de dados você está trabalhando? Digo, os dados do produto
Comment: é um produto que possui ID, nome, quantidade em estoque. e no pedido é inserido o ID do produto e a quantidade solicitada
Comment: OK, mas como você faz o controle dos produtos selecionados? Com array? Ou só adiciona na tabela?
Comment: só adicionei na tabela
Comment: Você poderia tentar usar o DataTables para isso e ainda pode incrementar sua tabela com as funcionalidades de busca, ordenação, etc. https://datatables.net/manual/data/
Answer: No seu caso seria melhor controlar os produtos selecionados com um array de objetos, por exemplo:
var produtos = [
    { id: 0, nome: "lorem", valor: 0 },
    { id: 1, nome: "lorem 1", valor: 0 },
    { id: 2, nome: "lorem 2", valor: 0 }
];

E os produtos selecionados:
var selecionados = [
    { id: 1, quantidade: 2, emprestimo: true },
    { id: 2, quantidade: 1, emprestimo: false },
];

Quando fosse adicionar um novo produto na lista, verificaria pelo id se já está na lista, nesse caso somente adiciona em 1 o valor da propriedade 'quantidade' do elemento. Ex.
var id = 1; // id do produto selecionado
var encontrado = selecionados.find(function(el) {
                     return el.id === id;
                 }); // busca o produto
if (encontrado)
    encontrado.quantidade++;

Depois apenas exiba na tabela os valores percorrendo o array.
Comment: oi, eu acabei fazendo várias coisas desde a hora que fiz a pergunta, agora estou obtendo um array com todas as linhas da tabela, estou tentando fazer algo para percorrer este array e somar as quantidades dos produtos repetidos, deletando-os após isso.

    $item[0]['id']
    $item[0]['quantidade']

estou obtendo um array assim ...

Alterar tabela com javascript jquery


Get device location in latitude-longitude in xamarin forms

Question: I have a scanner in my application, and as I am scanning any QR code I need to get a current location of device in latitude-longitude. I don't have any idea how to get location so I don't have any piece of code right now. Suggest me some ways to get location on scanning completion of QR code.
Answer: Geolocator Plugin example:
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync (timeoutMilliseconds: 10000);
Console.WriteLine ("Position Status: {0}", position.Timestamp);
Console.WriteLine ("Position Latitude: {0}", position.Latitude);
Console.WriteLine ("Position Longitude: {0}", position.Longitude);

Ref: https://github.com/jamesmontemagno/GeolocatorPlugin
Nuget: https://www.nuget.org/packages/Xam.Plugin.Geolocator
Comment: I'm using this method in my OnAppearing method, however the App crashes after GetPositionAsync, do you know what it can be?
Comment: Make sure that `ACCESS_COARSE_LOCATION` and `ACCESS_FINE_LOCATION` are checked in the Android Solution Properties
Comment: Hi, I am using this plugin in my xamarin android project but  I am getting task cancellation exception. I  have tested in both simulator and real device both getting same result.
Comment: Hi @MichaelYuwono , i am trying to get the position of current location on app sleep mode. but i can't get it using this code, var position = await locator.GetPositionAsync(); please help me to achieve this.
Answer: For everyone that is confused about this location stuff I recommend using Xamarin Essentials and not the plug-in mentioned above.
            var location = await Geolocation.GetLastKnownLocationAsync();
            if (location != null)
            {
                MyLocation = location;
                if (!ShowUserLocation)
                    ShowUserLocation = true;
            }

Comment: But is it crossplatform? I want everything at xamarin forms level, not android or ios.
Comment: yes @MYil its crossplatform
https://learn.microsoft.com/en-us/xamarin/essentials/geolocation?tabs=android
Answer: I recommend Xamarin Essentials.
Look this post and check your permissions.
https://learn.microsoft.com/en-us/xamarin/essentials/geolocation?tabs=android
var Latitude;
var Longitude;
var request = new GeolocationRequest(GeolocationAccuracy.Best);
                    var location = await Geolocation.GetLocationAsync(request);

                    if (location != null)
                    {
                        if (location.IsFromMockProvider)
                        {
                            //Put a message if detect a mock location.
                        }else
                        {
                            Latitude=location.Latitude;
                            Longitude=location.Longitude;
                        }
                    }


Space remove from String

Question: #include<stdio.h>
#include<string.h>

int main(){
    char array[]="Arijit Saha Student";
    spaceremover(array);
    getch();
    return 1;
}

int spaceremover(char a[]){
    int i;
   // printf("L=%d",strlen(a));
    char final[strlen(a)+1];
    int count=0;
    for(i=0;i<strlen(a);i++)
    {
        if(a[i]!=' ')
            final[count]=a[i];
        count++;
    }
    final[count]='\0';
    int j=0;
    for(j=0;j<strlen(final);j++)
    printf("%c",final[j]);
    // printf("\n%s",final);
    return 1;
}

With this example code the output is Arijit.Saha, but my desired output is ArijitSahaStudent.
Why am I getting the wrong output?
Where the . is coming from?
Comment: The '.' is probably just junk data leftover from something else. Your biggest problem is that `count` is being incremented no matter what. You should put curly braces around `final[count]=a[i];` and `count++` so `count` only increments when a letter is added to the array. Currently, when it gets to a space, nothing is added to the `final` array at that position
Comment: @anishsane It is with C99 compliant compilers I believe.
Comment: This probably belongs on [CodeReview](http://codereview.stackexchange.com)
Comment: `char final[strlen(a)+1];` : is this legal in C?
Comment: @VladLazarenko Really? I thought SO is for programming issues and CR is for reviewing code. Then what kind of questions belong here?
Comment: @anishsane: This is called VLA (for Variable Length Array). Basically, compiler allocates such arrays on stack as in `alloca()`.
Answer: The error is here:
if(a[i]!=' ')
    final[count]=a[i];
count++;

The count++ should be included in the if, so:
if(a[i]!=' ') {
    final[count]=a[i];
    count++;
}

Note: It is considered good programming practice to always use curly braces after if statements.
Comment: +1 nice spotted. It just shows how important is the proper indentation of the code.
Answer: In the for loop you increase count even if a[i] == ' ' .
So when a[i] == ' ' you only increase count but doesn't set final[count] to anything.
I assume you ment to write:
if (a[i] != ' ')
{
    final[count] = a[i];
    count++;
}

Answer: You are not incrementing count correctly.  It needs to be in the if loop. This might be easier for you to see if things are indented correctly.
#include<stdio.h>
#include<string.h>

int main(){
  char array[]="Arijit Saha Student";
  spaceremover(array);
  return 1;
}

int spaceremover(char a[]){
  int i;
  // printf("L=%d",strlen(a));
  char final[strlen(a)+1];
  int count=0;
  for(i=0;i<strlen(a);i++)
  {
    if(a[i]!=' ')
      final[count++]=a[i];
  }
  final[count++]='\0';
  int j=0;
  for(j=0;j<strlen(final);j++)
    printf("%c",final[j]);
  // printf("\n%s",final);
  return 1;
}

Answer: In the loop, the count should increase if a[i] not equal to space
if(a[i]!=' ')
      final[count]=a[i];
count++;
if(a[i]!=' ')
final[count++]=a[i];
//count++;

Space remove from String


Vue Refresh page with realtime data

Question: I'm building some app using Laravel & Vue, and so far so good, but I'm no expert with Vue.
So I have one very "begginers" problem, using live data.
So I want to make button that will check if live data is on or off, and if they turn it on, it must refresh data and set liveData state to true.
For example:
This is my "button" and it's not working as expected, It will change state but data is still no live

        Turn OFF Live data

        Turn On Live data

I have defined state like so:
    data() {
        return {
            liveData: false
        }
    },

And this is my created() function:
created() {
        if(this.liveData){
            window.Echo.channel("addOrder").listen(".order-created", (order) => {
                this.$store.commit("ADD_ORDER", order);
            });
        }

        this.$store.dispatch("GET_ORDERS");
    },

So in this case only button is not working, but if I set state to true it's working perfectly.
What do I need to do here? Do I need to make new function to work or?
Answer: Created will only be executed once in your component lifecycle. At this point the value of liveData is always false.
If you click on your "button" the value should change but your code inside of created will not be executed once more.
Instead of created you can use an immediate watcher:
watch: {
  liveData: {
    immediate: true,
    handler(val) {
      // your code from created here
    }
}

Answer: Correct the mistake

        Turn OFF Live data

        Turn On Live data

or

Vue Refresh page with realtime data