Determine Octave Number given Only Key Num

Question: I have recently been searching for a formula to determine the octave a note is in, given the number of that key on the piano. For example, given the key #77 (C7# for reference), how could I mathematically determine its octave number?
So far, I have tried dividing by 12 and 13, rounding to the nearest whole, since there are 12-13 notes in an octave (counting black and white keys), depending if you include the repeat of the first note or not.
Any ideas? Thank you!
Comment: Intriguing! There are 12 pitches in an octave; like hours in a day, "a.m." last up to but not including noon.
Comment: Thank you all for your help! I have applied the final answer of FLOOR((x+8)/12) to a computer program I was making that converts computer-code files to music. For anyone interested, I will post a link to it in a few hours.
Comment: And here is the link to the project: https://github.com/flancast90/Harpsichord. For anyone interested, I would love some feedback. You do not need to be a programmer to use it, the base of the actual program is music theory concepts I have learned, expressed mathematically.
Comment: @Finn_Lancaster 1. note that `math.floor((note_loc+8)/12)` is the same as `(note_loc + 8) // 12` or even `int((note_loc + 8) / 12)`; 2. even if the range of a piano keyboard is pretty standard, it's better to consider the 128-range of MIDI with a (possibly customizable) constant used as offset in order to get the correct pitch; 3. some time ago I developed a virtual keyboard in PyQt5, in case you're interested in studying its code: https://gist.github.com/MaurizioB/43a053575f17eae371a9d7394e66a46e
Comment: Awesome! Glad to see there are some fellow programmers/musicians here!
Comment: @Finn_Lancaster Oh, given the fact that the venn diagram of "People who know StackExchange exists" and "people who regularly use StackOverflow" and "people who write code" is roughly a set of concentric circles... I imagine most here are like me, with lives as both musician and programmer. I don't have enough Python experience to give any tips, but the project seems like a cool idea!
Comment: Thanks! Also, feel free to look at my new Python/Piano mashup: https://www.github.com/flancast90/Pythune , which is a tool that maps frequency of key on piano in order to help tune it!
Answer: Given a key number x, the octave can be calculated by FLOOR([x+8]/12).

As pointed out by @user80003, this formula cannot distinguish between enharmonically equivalent pitches. It will give wrong answers for B#s and Cbs. Given key #76, the above formula gives 7 as the octave, which is correct for C7, but incorrect for B#6.
This can only be accommodated when the pitch is known and made enharmonically equivalent. Using pitch class (PC) notation (C=0; C#/Db=1; D=2; ...; B=11), for example, eliminates the problem.
KeyNum = (12 * Octave) + (PC - 8)
Thus
Octave = FLOOR[ (KeyNum + 8 - PC)/12 ]
Since B# and C are equivalent in pitch-class terms (0) — as are B and Cb (11) — the octave is calculated unambiguously, but with the loss of the letter-name designation.
Comment: Thanks, @Aaron, this adds the corrections myself and others were suggesting to @guidot's answer. I would upvote except for my too-low reputation, and I would like to wait for any new developments on @user80003's answer before accepting as answer. EDIT: Just upvoted
Answer: Note that there is no definitive answer as stated, since for example key #76 is used for both C7 and B♯6 and key #75 is used for both C♭7 and B6, meaning that the actual octave number may depend on the tonality.
Comment: This answer seems to point out the complications of special cases without an attempt to address the basic question.
Comment: Should be a comment, but idk if new users have the rep to do that.
Comment: Interesting, @user80003, I did not even think of that. Because of the FLOOR function, I believe that the octave number returned would be correct, but nonetheless #76 and #77 would return slightly different decimal answers before being floored, I think.
Comment: @guidot It addresses the basic question by pointing out that it's unanswerable as given. There's no way to distinguish between enharmonically equivalent pitches with different octave designations. Piano keys are 1-based, so given the formula FLOOR([x+8]/12), for key #76 the return value will be 7, which is correct for C7, but incorrect for B#6.
Answer: You have to consider the offset caused by the non-existing keys of the first octave on the piano as well. Otherwise divsion by 12 should work.
So if you keyboard starts with a, then (key_number + 9)//12 should do the trick. Note, that octave numbering is a minefield of its own (whether to start with 0 or 1).
It of course depends also on the number you assign to the first key (key_number). The given 9 works for those starting with 0, to be replaced by 8 when you start with one.
Comment: Shouldn't it be key_number+8?  The lowest octave transitions from 0 to 1 on C, which is the fourth key, so you want 4+8 = 12 // 12 = 1, no?  (Note that this assumes you're numbering the first key 1, as opposed to 0, but 1 is in line with OP's example key.
Comment: @Anthanasius: your comment with adding 8 instead of 9 seems to be correct. Just verified with note 40 (Middle C), which means 48/12=4. With 9, the floor function returns the same, and should have no difference because of the low number of octaves on the piano, but as soon as the number of octaves was too high, the slightly more decimal would mean an incorrect answer.
Comment: For the sake of simplicity, assuming that C1 was the beginning of the first octave, disregarding A0, etc, how then would the formula change. Would just division by 12 work?
Comment: @Finn_Lancaster - in case it's unclear, note that "//" in this answer indicates integer division, where you truncate the answer by ignoring any decimal and taking the integer (as in a mathematical floor function).
Comment: Answered my question just before I asked! Yep, sounds just like floor - returning the nearest integer less than or equal to the given number.
Answer: A standard grand piano keyboard goes from 39 notes below Middle C to 48 notes above Middle C.  So, if you number the keys from 1 to 88 (as opposed to 0 to 87), then Middle C = #40.
Assuming you define octaves as going from C to B (ignoring the tricky numbering of B♯ and C♭), then the octave number of key n is (n - 40) // 12 + M, where // is Python's floor division operator and M is the octave number assigned to Middle C.
If M=4 (as in scientific pitch notation), then (n + 8) // 12 is an equivalent formulation.


How to access the raw content of a views field, for use with Services Views

Question: I have a user that I want to expose to services. Using Services Views. I'm using fields as the format, and adding the "photo" field to my display. My issue is that when I view the service (as JSON). I get all the HTML as well as th image URL, for instance
users_node_picture: "",

I need just the url, I've tried the following with no luck.

Strip HTML (removes everything)
Rewrite output (same result)
Row theming (does not effect the services result, only the html page)
Installed Views PHP (by returning the row, I simply get the field id)

Is there any other way to effect the output of this field before it is outputed by Services Views? I thought perhaps I could do something with template_preprocess, but I'm not really sure how I would go about doing it.
Comment: Have you found a solution to this issue?
Answer: You can do it using relationships! Under Advanced, add the relationship File Usage: File. Then go add a new field, and you'll see File: Path.
Alternatively, you could use the Image URL Formatter module. This allows you to print an image as a URL. Then in the field settings in Views select this under 'Format' for the image field. The module has some features that would be harder to achieve with the relationship, but for most cases the relationship should work.
Comment: Good call I would suggest using the Image URL Formatter module, its always a standard use on our dev team
Answer:
Create a file called field.tpl.php in your theme folder
In this new file, add the code detailed here:
Edit the code to suit how you want it show, for example if you want the raw output with no Divs etc

 $item) : ?>

type);
$item=$items[0]; //Just display the first date
$display=field_get_display($instance, 'default', $node);
$display['settings']['format_type']='short'; //Alter the display
$vars['dates'] =date_formatter_process('date_default', 'node', $node, $field, $instance, $langcode, $item, $display);
$output=theme('date_display_combination', $vars);
?>
Comment: Please see number 3, field templates do not seem to effect the output of the field to services, I'm not exactly sure how services views works, but apparently it is pre - template.


How to prove this problem about doubly periodic?

Question: We say that$ \omega_1$and $\omega_2$ generate the periods of a doubly periodic
function if the periods of the function are precisely the complex
numbers of the form $ m\omega_1+ n\omega_2 $ where m and n are integers. Show that if$ \omega_1$and$ \omega_2$ generate the periods of a doubly periodic function
$f(z)$, and if $\alpha_1$ and $ \alpha_2$are complex numbers, then$\alpha_1 $and $\alpha_2$ generate
the periods of $f (z) $if and only if there is a 2 x 2 matrix  $\mathrm A$with integer
entries and with determinant ±1 such that $A(\omega_1 ,\omega_2) = ( \alpha_1,  \alpha_2  ) $.
I think $ \omega_1 $ and  $\omega_2$ have form  $ m_1\alpha_1 +  n_1 \alpha_2 $,$ m_1$and $ n_1$  are integer .
$\Leftarrow$:
I want to prove   $ \omega_1$and $\omega_2$  have form $ m_1\alpha_1+ n_1\alpha_2 $,i suppose $A= \begin{pmatrix}
a_{11} & a_{12} \\ a_{21} & a_{22} \end {pmatrix}, \omega_1 =\begin{pmatrix} x_1\\ y_1 \\  \end {pmatrix} $and so on. But i can't find this relation.
$\Rightarrow$: i haven't clue.
Comment: If $\alpha_1$ and $\alpha_2$ generate the periods, then in particular, they generate $\omega_1$ and $\omega_2$.  That is, there is an integer matrix $A$ such that  $$\begin{pmatrix}\omega_1\\\omega_2\end{pmatrix}=A
\begin{pmatrix}\alpha_1\\\alpha_2\end{pmatrix}$$
Comment: But we should  prove $A(\omega_1 ,\omega_2) = ( \alpha_1, \alpha_2 ) $.$(\omega_1 ,\omega_2)$ and $( \alpha_1, \alpha_2 )$ either Column vector or row vector.
Answer: Suppose $\omega_1,\omega_2$ generate the periods, and $\alpha_1,\alpha_2$ do as well.
Since $\omega_1,\omega_2$ generate periods, that means any period may be written as an integer combination of them, so in particular $\alpha_1=a_{11}\omega_1+a_{12}\omega_2$ and $\alpha_2=a_{21}\omega_1+a_{22}\omega_2$ for integers $a_{ij}$. That is,
$$ \begin{pmatrix} \alpha_1 \\ \alpha_2 \end{pmatrix} = \begin{pmatrix} a_{11} & a_{12} \\ a_{21} & a_{22} \end{pmatrix} \begin{pmatrix} \omega_1 \\ \omega_2 \end{pmatrix} $$
Or $\vec{\alpha}=A\vec{\omega}$ for an integer matrix $A$.
How do we know $A$ must have determinant $\pm1$? Well, the same argument works to show $\vec{\omega}=B\vec{\alpha}$ for some integer matrix $B$ ... can you finish from there?
Comment: The reason $\det A=\pm1$ is because $B=A^{-1}$ is also an integer matrix, and taking determinants of $AB=I$ yields $(\det A)(\det B)=1$ forcing $\det A$ to be $\pm1$.
Comment: OK,thanks!use Formula $A^{-1}$=$\frac{A^*}{|A|}$  and $A^{-1}$ is also entire matrix can know $|A|$= ±1.


How to prove $\Delta DEF$ is an equilateral triangle?

Question:
$\Delta ABC$ is an equilateral triangle and $AD = BE = CF$. Prove that $\Delta DEF$ is an equilateral triangle.
Comment: Has anyone considered either of these approaches? $$1. \text{Drawing "auxiliary" lines}$$ $$2. \text{Assuming that DEF is not equilateral and reaching a contradiction}$$
Comment: approach 2 is OK , But how to draw the auxiliary lines?I have no ideas.
Comment: I have racked my brain for a solution that doesn't involve circles, with no success. Good luck to you!
Comment: OK,thanks a lot.
Answer: Draw circles centered at A, B, and C, with radius AD=BE=CF.
Triangle $\triangle$DEF must lie in the region between these 3 circles, touching each circle with a vertex.
Draw the rotationally symmetric solution as $\triangle$D'E'F'.
(Side exercise: Show it must exist.)
Now suppose $\triangle$DEF $\ne$ $\triangle$D'E'F'.
Up to here, everything I've said is very straightforward, but you might want to stop for a second and see if you can solve it from here.  If you can't, one more hint is hidden in the gray box below.

 DE is either outside $\triangle$D'E'F', or crosses it.
 Either way, can you say something similar about DF?  About EF?
Comment: Yeah, proofing by contradiction is good choice.But is there any method of direct proof ? By transforming?
Comment: It is unlikely for a transformation to help, since the key information AD=BE=CF is destroyed by most types of transformations, and those that preserve it leave the problem unchanged.
Comment: clearly explanation,Thank you.
Answer: Suppose we fix $\ell = AD=BE=CF$, and let $x=\angle{BAD}$, $y=\angle{CBE}$, $z=\angle{ACF}$.
Then we can define $f : [0,\pi/6]\to[0,\pi/6]$ such that $y = f(x)$, $z = f(y)$, and $x = f(z)$. Note that $f$ is strictly decreasing: one good way to see this is by drawing the circles centered at $A,B,C$ with radius $\ell$. But then $f^3(x) = x$ forces $f(x) = x$ (and thus $x=y=z$); otherwise, if WLOG $x<f(x)$, then $$f(x)>f^2(x)\implies f^2(x)<f^3(x)=x\implies x=f^3(x)>f(x),$$ contradicting $x<f(x)$.
Note that this solution assumes that $x,y,z<\pi/6$, but the problem still holds as long as $x,y,z<\pi/3$. In particular, I think you can show that if one of $x,y,z$ is larger than $\pi/6$ (which requires $\ell>1/2$), the other two must be as well, so $f$ is still well-defined. Anyway, all of this is equivalent to the rotation method Matt mentioned in his answer, but I thought it would be good to include this more algebraic perspective.
fedja also has a long post about this kind of problem on AoPS.


Como contar o numero de "rows" em uma tabela em python

Question: Exemplo, tenho um banco de dados chamado 123, nesse banco de dados tem a tabela jogadores, que seria onde ficam as contas dos jogadores.
Quero contar quantas contas existem no banco de dados.
Enfim, contar o numero de rows de uma tabela SQLITE3, usando PYTHON 2.7.
O que tenho até agora:
# -*- coding: cp1252 -*-
import sqlite3

# Connexion for database
try:
    print "Tentando conectar-se ao banco de dados."
    Database, Cursor = None, None
    Database = sqlite3.connect("./database/database.db", check_same_thread = False)
    Database.text_factory = str
    Database.isolation_level = None
    Database.row_factory = sqlite3.Row
    Cursor = Database.cursor()
    print "Conectado com o banco de dados.\n"
except:
    print "[ERROR] Falha na conexão do banco de dados."

Cursor.execute("?")
Comment: Ok, o que você já tem de código até agora? Já conseguiu conectar-se com o banco com Python? Deu algum erro? Você sabe SQL?
Comment: Att: Codico att
Tenho conexão, sem erros na conexão.
Sobre o codico não tenho =/
Comment: E quanto ao SQL? Você sabe como é feito uma consulta com SQL?
Comment: Sei muito pouco sobre SQL, mais sei sim Deletar, atualizar, inserir valores em tabelas. Consulta também.
Comment: Tente executar a consulta: `select count(*) from jogadores`
Answer: Criando banco de dados contendo uma tabela de jogadores com 3 registros:
import sqlite3

jogadores = [ { "id" : 1, "nome" : "Joao" }, { "id" : 2, "nome" : "Maria" }, { "id" : 3, "nome" : "Jesus" } ]

conn = sqlite3.connect('foobar.db')

c = conn.cursor()

c.execute("CREATE TABLE tb_jogador ( id integer, nome text );")

for j in jogadores:
    c.execute("INSERT INTO tb_jogador ( id, nome ) VALUES ( %d, '%s' );" % ( j["id"], j["nome"] ))

conn.commit()
conn.close()

Recuperando quantidade de registros contidos na tabela:
import sqlite3

conn = sqlite3.connect('foobar.db')

c = conn.cursor()

c.execute('SELECT count(1) FROM tb_jogador')

count = list(c)[0]

print("Quantidade de jogadores registrados: %d" % (count) )

conn.close()

Answer: Você também poderia fazer isso:
cursor.execute(f'SELECT * FROM jogadores')
count = len(cursor.fetchall())

o fetchall() pega todas as linhas de sua tabela e as coloca em uma tupla, todas elas dentro de uma lista. Então é só colocar o len para contar quantos valores tem dentro dessa lista.
:)
site: https://pynative.com/python-cursor-fetchall-fetchmany-fetchone-to-read-rows-from-table/
cursor.fetchall(): busca todas as linhas de um resultado de consulta. Ele retorna todas as linhas como uma lista de tuplas. Uma lista vazia é retornada se não houver nenhum registro para buscar.


Link to my CSS in my wordpress template, css file is in the sibling folder of the template

Question: I have temp.php in wp-content/themes/fifthteen/paytest.php, the css file is **wp-content/themes/fifthteen/paytest/paytest.css**
I want to link to the paytest.css in my paytest.php
<link rel="stylesheet" href="????/paytest/paytest.css />

How can I do this?
Answer: You should use  get_template_directory_uri() to have the template directory URI of your current theme.
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/paytest/paytest.css "/>

Answer: You'll want to link to the theme directory
<?php echo get_template_directory(); ?>

So in working example:
<link rel="stylesheet" href="<?php echo get_template_directory(); ?>/paytest/paytest.css />

Comment: Isn't that used for the absolute path ?
Comment: Yes, I always find absolute paths to be more stable with wordpress because of the way the linking and pretty urls work. Though with a correct server setup either of our answers should work.


Django - deployment on Heroku returns different HTML than local host

Question: I have a Django app that works great on localhost. When deployed the Heroku, for some reason the app returns different HTMLs. A few examples:

I have a form with button type submit. This is the template

        <button type="button" page="{{request.resolver_match.view_name}}" type="submit" id="bullets_submit"
            class="btn btn-primary px-5 py-2">
            Next Step
        </button>

In localhost everything works well. But, on Heroku, the HTML I receive is without the type="submit". Same button just without this attribute.

I have a for loop that iterates on a model and create a li

            About the role </button>

                {% for responsibility in description_responsibilities%}

{{responsibility}}

                {% endfor %}

On Heroku, even though the   is clearly outside of the for loop, it still get generated several times in the HTML I receive from the server, as if it was inside the for loop.
Any idea what might cause this weird behavior? Or how I can debug it?
Answer: Found the reason. It was stupid (missing HTML tag).
What's interesting is that the page rendered nicely on my local Windows machine, but on Heroku, the issue appeared. It made it really hard to find what's wrong.
So I cloned my app to a linux shell and then the issue reproduced locally. From there it took 2 minutes to fix. I'm not sure why Windows django rendered a different page then linux.


System of two non-linear equations

Question: I have the following system of equations:
\begin{align}
\cos(\alpha)+\cos(\beta)&=1.6, \\
\cos(3\alpha)+\cos(3\beta)&=0.
\end{align}
How can i use an iterative method to solve these equations?
Comment: Welcome to MSE. It is in your best interest that you type your questions (using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)) instead of posting links to pictures.
Comment: Do you mean $$\cos(3\alpha_1)+\cos(3\alpha_2)=0$$ and $$\cos(\alpha_1)+\cos(\alpha_2)=1.6$$
Answer: Using the triple angle formula,
$$\begin{cases}a+b&=p,\\4a^3-3a+4b^3-3b&=q.\end{cases}$$
Eliminating $b$,
$$12pa^2-12p^2a+4p^3-3p-q=0$$
is a mere quadratic equation.
With the given numerical values,
$$\cos\alpha=a=\frac{24\pm\sqrt{33}}{30}.$$
By symmetry,
$$\cos\beta=b=\frac{24\mp\sqrt{33}}{30}.$$

System of two non-linear equations


Where em um Array JSON Postgres

Question: Como posso fazer para selecionar apenas os registros que possuam o valor "18" nesse JSON?
'{"filtros":[
    {
        "tipo":"caracteristicas",
        "operador":"=",
        "valor":{"18":[12]}
    }
  ]}'

Tentei usar a comparação com o @> mas não deu certo, pois ele não me retorna o registro.
SELECT opcoes FROM pagina WHERE (opcoes->>'filtros')::jsonb @> '[18]'

Answer: O complicado aqui é que filtros é um array, então você não pode fazer a consulta diretamente, tem que percorrer para cada posição dele.
Para isso, você deve usar a função jsonb_array_elements(jsonb). Ela vai transformar a lista de resultados em uma "tabela" e você pode dar trabalhar com esses resultados.
Imagine que você tenha em vez de 1 elemento dentro de filtros, tenha 2 elementos. Exemplo:
'{"filtros":[
    {
        "tipo":"caracteristicas",
        "operador":"=",
        "valor":{"18":[12]}
    },
    {
        "tipo":"caracteristicas",
        "operador":"=",
        "valor":{"19":[12]}
    }
]}'

Com (opcoes->>'filtros')::jsonb você vai escolher todos os elementos desse array. Com jsonb_array_elements você vai transformá-lo em tuplas:
SELECT jsonb_array_elements((opcoes->>'filtros')::jsonb) FROM pagina limit 1;
                    jsonb_array_elements
---------------------------------------------------------------------
 {"tipo": "caracteristicas", "valor": {"18": [12]}, "operador": "="}
 {"tipo": "caracteristicas", "valor": {"19": [12]}, "operador": "="}
(2 rows)

Mas você ainda tem q ver se um desses caras tem o valor "18". Imagino eu que você queria olhar especificamente o campo valor e não qualquer campo. Para isso você tem que referenciar ele na consulta:
SELECT jsonb_array_elements((opcoes->>'filtros')::jsonb)->>'valor' FROM pagina limit 1;
   ?column?
--------------
{"18": [12]}
{"19": [12]}
(2 rows)

Agora basta ver se o "valor" tem a chave '18' usando o operador ? (sempre lembrando que tem q transformar o resultado em um jsonb pra permitir a consulta).
SELECT (jsonb_array_elements((opcoes->>'filtros')::jsonb)->>'valor')::jsonb ? '18' FROM pagina limit 1;
   ?column?
--------------
t
f
(2 rows)

Como esse resultado pode retornar mais de uma linha para cada tupla armazenada, você pode colocar ele numa subconsulta para fazer o filtro, algo como:
SELECT opcoes FROM pagina WHERE id in (
    SELECT DISTINCT id FROM pagina WHERE
        (jsonb_array_elements((opcoes->>'filtros')::jsonb)->>'valor')::jsonb ? '18'
    );

Comment: Em partes deu certo, mas quando tentei usar o SELECT (jsonb_array_elements((opcoes->>'filtros')::jsonb)->>'valor')::jsonb ? '18' FROM pagina limit 1; que pro meu caso seria o mais adequado ele retorna erro:

ERRO:  sintaxe de entrada é inválida para tipo json
DETAIL:  Fim da entrada esperado, encontrado ",".
CONTEXT:  dado JSON, linha 1: 1,...
Comment: O que imprime a consulta:

    SELECT (jsonb_array_elements((opcoes->>'filtros')::jsonb)->>'valor') FROM pagina limit 1;
Comment: Sim, isso deu certo, mas o problema foi quanto tentei filtrar pelo registro 18 conforme colocastes no penúltimo SQL
Comment: Eu queria ver o resultado dessa consulta, porque o que parece que ele esta falando é que o json contido em valor é invalido.
Comment: Consegui resolver de um jeito diferente, fazendo assim: SELECT opcoes FROM pagina WHERE opcoes::jsonb @> '{"filtros":[{"valor":{"18":[]}}]}'; mas o que tu me passou me ajudou a chegar na solução
Answer: Consegui resolver do seguinte modo:
SELECT opcoes FROM pagina WHERE opcoes::jsonb @> '{"filtros":[{"valor":{"18":[]}}]}';

Comment: Funcionou com mais filtros. Na base tenho vários registros e com o select acima funcionou perfeitamente
Comment: Mas isso vai funcionar apenas quando tiver só um filtro, não?

Where em um Array JSON Postgres


How do I progress without a cello teacher during COVID lockdowns?

Question: I've been playing cello for four years now and I want to get better, but I don't know how. I started playing when I was placed in the wrong course at school and I ended up in the experienced class instead of beginner. The first year was taught by a proper strings teacher, but I spent most of the time self-teaching in order to catch up with the class (having played piano for several years really helped with the transition). Then, by the start of the next year, my teacher moved schools and my class was left with a band teacher who hadn't taught strings in over 10 years.
Now, I'm in twelfth grade and worked my way up to the principle cellist in the school orchestra but I know there are some key skills missing (such as vibrato and tone). Playing at school was enough for me but now because of COVID, I'm stuck at home and want to take advantage of the copious amount of extra time I have and improve my cello skills.
Due to never having a proper cello teacher, I don't actually know how advanced I am. I have a friend who is in the RCM system who said I would be around a level 3/4, but even so, I don't know where to start or how to progress without a teacher.
Is there anything someone could recommend for me to do?
(For reference, here's an example of something we played in orchestra last year):
Comment: Somewhat off the wall comment here! It seems (to me at least) that apart from guitarists every other instrumental learner appears to need 'proper' training. As in formal education on their instrument. Whereas guitarists (apart from a few who have to rely on what they're told in tutorials) will just have a go at playing - which is what I did back in the '60s, when that was pretty well all we could do. There's a lot of mileage in just 'having a go' and trying to play by yourself. Learn to listen to something, and try to play it. Play something in a different key. Change the time sig. and play ..
Comment: .. in a new one. Look at some dots and play in a different key. The list goes on...and on! Good luck!
Answer: The only string teaching that remains, as far as I know, is online. I know quite a few violin teachers who were teaching online before and who are continuing but a lot of regular face-to-face teachers have installed Zoom are offering their former face-to-face students online tuition.
If you are keen to continue with tuition I would suggest you make enquiries for online tuition. If you had previously had a proper cello teacher then that would have been the obvious first suggestion. In any case I would start by asking teachers of related string instruments who you know and trust if they know of any cello teachers they could recommend who are now teaching online.
Answer: I'm actually also a cello student in twelfth grade! Unfamiliar with any grading systems, though, bc my teacher doesn't use them (to that end your friend is probably not that far off??).
Best I can say is, a good teacher is the only one with the expertise to guide you through not only what you can do with your instrument, but what you can do as a musician as well, like paths in life and how cello can be a part of your future even if you don't plan on studying it. They'll also be able to gauge your skill and what you might need to advance. And developing technical skills on your own could lead to bad habits as others have also said. And if you play too much with the resulting strain it could lead to injury. So yea, if you're serious then do find a teacher; it's definitely worth it.
Besides finding a teacher: if you have friends (or even if you don't) in the orchestra, you could try doing some chamber music! That's one of the things I love doing most and it definitely helps motivate you to learn. Do keep social distancing in mind, though :)
Look for some orchestra/strings/chamber music programs in your area. They might have online auditions, it's worth a try!
I don't know if this kind of stuff is allowed here but there's a program my friend is involved in, that matches music students up with mentors for free teaching sessions- if you're interested it's at https://musicarementor.org/!
Best of luck!!
Answer: I teach guitar online and take voice lessons (now online).  I can tell you that there are challenges with online lessons.  It is difficult to get some information across.  I can't help students with hand position and posture bu touching them (with permission).  Some things are hard to describe and showing or doing is the best method.  Also, with only the webcam the angles are not great and it's hard to show details of the fingers and hand.  I suspect that taking cello lessons will have similar challenges.
You stated that you never had proper instruction.  How did you get as far as you did?  Did you at least have some basic instruction at your high school?  I would think so.  For many this is enough as they just want to get through and get their credits. If you like playing and want to improve I would seriously invest (or get your parents to invest) in lessons with a classical cello player.  Perhaps a college student in a music program would be a good place to start, they usually charge a lot less and are enthusiastic to get the experience.  Other than that do you have a basic book to work from, something from the Carl Fisher series?  F. Simandl is the standard Double Bass book, they have Lazarus for clarinet, and Carcassi for classical guitar.  I googled them for cello and found a few beginner to intermediate level work books.  You  should have one or something like it from school (our school books were not very good).  If you have good technique and no bad habits you should be able to work through one of these books on your own and get better.  But this has some risk.  If you try to get into harder exercise and new techniques without the help of an instructor you could develop bad technique and that translates to poor quality of tone and performance.  It is your call if you think you can go through one of those books systematically.
Answer: I agree with the other answers: you really have two problems.  The most important is that you've gone far too long without lessons, and are at risk of falling into incorrect habits.
The second problem is that of lessons, of course.  Do some networking if you can, with fellow student cellists, local music schools... and see if there's a teacher with Zoom or iChat capability that you could sign on with.


Confusion on assessing the linearity assumption

Question: This is for assignment. But i am not asking for hold my finger and guide me. Just asking something that is confusing me.
I am reading a chapter in which we are using gg_resX(mydata) from lindia package.  The value of mydata was calculated from mydata <- with(my_centered_data, lm(y ~ x)).
The output of this is following graph

The author of the tutorial then went on to say that there is no non-linear pattern here. Even though, to me, it appears that there is kind of a sin wave ..
Now, here is another graph

Should i consider that there is no pattern here as well? Or should i call it out that there are outliers at the bottom of the graph?
I mean, I am not sure why author said in first graph that it is linear and because of that i am confuse at second one
Comment: Can you post a link to the data itself, or just post the output of `dput(data)`?  I cam see why you might observe a sinusoidal, but it's probably a bit too sparse and would be easy to "see" all kinds of things.
Comment: i am not sure if i am allowed to do so :( as i said its for assignment
Comment: What is being plotted in both of those figures ? Are they residuals from a model, or raw data ?
Answer: The plots appear to be for residuals vs fitted values, or perhaps against a predictor. This is a fairly standard approach to assessing linearity.
Basically we don't want to see any non-linear pattern in the plots.
The problem we have here is that the sample size is quite small. It looks like around 30. With this sample size it would be easy for a nonlinearity to be masked, or indeed to see a spurious nonlinear association.
I think you are justified in considering both plots to not show any clear evidence of nonlinearity.
Also, I would not pay too worry too much about apparent "outliers". Extreme data points occur naturally, it is only when something is clearly an error, such as a hieght of a human being 10cm, or 10m, that it should be removed.
Comment: Thanks a lot. you cleared my confusion. yeah, the sample size is 26 in first chart and 30 in second one. appreciate the time and comment.


Send Prometheus query from telegraf to VictoriaMetrics DB

Question: Did anyone know if it is possible to collect metric directly by sending a prometheus query in telegraf to VictoriaMetrics ?
I have tried this but it is not working :/
[inputs]
[[inputs.prometheus]]
urls = ["http://my_db_address:8428"]
query = "ifHCOutOctets_counter{target="device"}"

Any ideas ?
Thanks !
Answer: Make sure Prometheus query is valid data in system.if issue persists victoria metrics logs connection problem.Adusjust query with single quotes.Not use double quotes.
Comment: AFAIK It looks like [[inputs.prometheus]] is using only for polling metrics and not to query them from telegraf, see https://github.com/search?q=repo%3Ainfluxdata%2Ftelegraf%20inputs.prometheus&type=code , see also https://stackoverflow.com/questions/54636124/sending-metrics-from-telegraf-to-prometheus
Comment: The one quote didn't change anything. in telegraf logs i am getting this error : configuration specified the fields ["query"], but they weren't use
Answer: Try the following config for Telegraf:
[[inputs.prometheus]]
urls = ["http://my_db_address:8428/federate?match[]=ifHCOutOctets_counter{target='device'}"]

It uses /federate endpoint for obtaining the last values for metrics matching the given filters. The /federate endpoint returns metrics in the same format as usual Prometheus exporters do at /metrics page.


unit-test for c - how to test a 'unit' without recompiling/relinking?

Question: I'm new to unit-testing, but not C (in an embedded environment) - I have a conceptual problem that I'm sure has a simple answer... I'm just having trouble getting that answer.
I've started to experiment with unit-testing, after reading a couple of books on the subject - the examples in the book always seem clear, but trivial, but neither really touched on the piece I'm missing (or if it did, it went over my head).
I've started to experiment with unit testing on one of our protocol stacks that has four layers (app, presentation, session, transport). Keeping the example simple for clarity, each layer might have one to several functions. If I want to unit test the App layer, I think I'm to understand that I'd 'stub' out the interface to the presentation layer (or create a mock for the presentation layer?), in order to isolate the application layer. I've tried this out, and all seems good.
However, my question is then, how do you unit test the presentation layer without recompiling or relinking the target and thereby generating a bunch of executables?
Thanks for insight.
Comment: What are the public interfaces to your layers? Can you exercise the API from a separate executable>
Comment: Some unit test library required you to build with some custom flags in order to mock out global functions. Why you want to avoid rebuild? It should be fast anyway.
Answer: Im not sure of C++ but in case of C,
a suggested method is to have conditional compilation. So that you can compile either as real project or for unit testing. So in unit testing the stubs are executed.
But since you want not to recompile it, there is very rude method and that is to have 2 parts for your function which depends on a flag. So on run time if you change the flag value, the second part is executed so your real functions can act as a stub in this case.
Answer: Disclaimer, I work at Typemock.
You can use Typemock Isolator++ to mock out anything you need in c\c++.
Isolator works in runtime, so you will not need to recompile nor change your production code, see example:
production.cpp in production.dll
class MyPureClass
{
public:
   virtual int GetResult() = 0;
}

test.cpp in test.dll
TEST_METHOD(Method1)
{
    //mock the class = its methods will return fake objects (recursively) or default values
    MyPureClass* fakeMyClass = FAKE<MyPureClass>();

    //assign specific return value to a method
    WHEN_CALLED(fakeMyClass->GetResult()).Return(10);
}

You can also mock concrete classes, static and global functions... in the same manner.


Efficient way to make thousands of curl requests

Question: I am using CURL to make thousands of requests. In my code I set the cookie to a specific value and then read in the value on the page. Here is my Perl code:
#!/usr/bin/perl
my $site = "http://SITENAME/?id=";
my $cookie_name = "cookienum123";
print $fh "#\t\tValue\n";
for my $i ('1'..'10000') {
    my $output = `curl -s -H "Cookie: $cookie_name=$i" -L $site$i | grep -Eo "[0-9]+"`;
    print "$i\t\t$output\n";
}

So from 1 to 10000, I am setting cookienum123 to that value and reading in the whole response from the page. Then I use grep to just extract the #. The code I have now works fine but I am wondering if there is a faster or more efficient way I can do this.
Please note this does not have to be done as a Perl script (I can also use Windows batch file, Unix shell script, etc).
Edit Jan 18: Added bounty with the note "The desired answer should include a way in Perl to run through several thousand curl requests simultaneously but it needs to be run faster than the rate it is currently running at. It has to write the output to a single file in the end but the order does not matter." Some of the below comments mention fork but I am not sure how to apply it to my code. I am very new to Perl as this is my first program in it.
Comment: Net::Curl::Multi allows you to make parallel requests to the curl library. Of course,  there's also Parallel::ForkManager to ruin multiple `curl` processes
Comment: @ikegami you have some interesting typo there? `:)`
Comment: @Bijan, No, not using `curl`, since you would make sure that only one `curl` runs at a time. If you used Net::Curl::Multi, you would only have to the lock the file when you're writing to it, so that could work, but the output would be in random order. As such, you want to keep the output in memory, in a database or in separate files, then reassemble the output at the end.
Comment: What about forking to multiple children, say maybe 20 at a time to start, so you can run multiples at once?
Comment: @TheJester1977 how would I fork to multiple children?
Comment: @ikegami would that work if these are all writing to the same file?
Comment: @Bijan, check this out for a whimsically produced, yet spot-on accurate description of fork: [link]http://users.telenet.be/bartl/classicperl/fork/all.html
Comment: Would you be able to create an example of this using my example? I still have not found anything of how to create multiple curl forks.
Comment: Random output is fine because it goes into excel and I sort the values
Answer: What you have here is an embarrassingly parallel problem. These are great for parallelising, because there's no inter-thread dependency or communication needed.
There's two key ways of doing this in perl - threading or forking. I would generally suggest thread based parallel processing for the kind of thing you're doing. This is a matter of choice, but I think it's better suited for collating information.
#!/usr/bin/perl

use strict;
use warnings;

use threads;
use Thread::Queue;

my $numthreads = 20;

my $site        = "http://SITENAME/?id=";
my $cookie_name = "cookienum123";

my $fetch_q   = Thread::Queue->new();
my $collate_q = Thread::Queue->new();

#fetch sub sits in a loop, takes items off 'fetch_q' and runs curl.
sub fetch {
    while ( my $target = $fetch_q->dequeue() ) {
        my $output =
            `curl -s -H "Cookie: $cookie_name=$target" -L $site$target | grep -Eo "[0-9]+"`;
        $collate_q->enqueue($output);
    }
}

#one instance of collate, which exists to serialise the output from fetch.
#writing files concurrently can get very messy and build in race conditions.
sub collate {
    open( my $output_fh, ">", "results.txt" ) or die $!;
    print {$output_fh} "#\t\tValue\n";

    while ( my $result = $collate_q->dequeue() ) {
        print {$output_fh} $result;
    }
    close($output_fh);
}

## main bit:

#start worker threads
my @workers = map { threads->create( \&fetch ) } 1 .. $numthreads;

#collates results.
my $collater = threads->create( \&collate );

$fetch_q->enqueue( '1' .. '10000' );
$fetch_q->end();

foreach my $thr (@workers) {
    $thr->join();
}

#end collate_q here, because we know all the fetchers are
#joined - so no more results will be generated.
#queue will then generate 'undef' when it's empty, and the thread will exit.
$collate_q->end;

#join will block until thread has exited, e.g. all results in the queue
#have been 'processed'.
$collater->join;

This will spawn 20 worker threads, that'll run in parallel, and collect results as they exit to a file. As an alternative, you could do something similar with Parallel::ForkManager, but for data-oriented tasks, I personally prefer threading.
You can use the 'collate' sub to postprocess any data, such as sorting it, counting it, whatever.
I would also point out - using curl and grep as system calls isn't ideal - I've left them as is, but would suggest looking at LWP and allowing perl to handle the text processing, because it's pretty good at it.
Comment: enqueue whatever you'd like printed from the source thread. `$collate_queue -> enqueue ( "Target: $target Output $output\n" );` for example.
Comment: `$fetch_q->pending()` will give you a count of items that haven't yet been processed.  You can probably use that, either in a separate thread or the collater thread.
Comment: General experience that 20 is usually a good number. Each thread will increase the memory usage. Too many will also start to contend with each other. For a CPU oriented task, I would say one thread per core. For network IO oriented, it very much depends on your infrastructure and request size. It isn't too hard to saturate network pipes this way.
Comment: One small thing, you only output $result to the file. How would you output $target to be on the same line?
Comment: One more thing, is it possible to use `Term::ProgressBar` to keep track of how much of the progress has been completed? I have done this before with my previous example but i imagine its different since I am using threads
Comment: Perfect, got that working. What would you suggest for # of threads? I found that too little threads is slow but too many (~100) is also a little slow. Is there a reason you chose 20?
Answer: I'm pretty sure the following will do what you want however slamming a server with 10000 simultaneous requests is not very polite.  In fact, harvesting a site's data by walking the id's of a given url doesn't sound very friendly either.  I have NOT tested the following but it should get you 99% of the way there (might be a syntax/usage error somewhere).
See for more info:

https://metacpan.org/pod/distribution/Mojolicious/lib/Mojolicious/Guides/Cookbook.pod#Non-blocking
https://metacpan.org/pod/Mojo::UserAgent#build_tx
https://metacpan.org/pod/Mojo::DOM

Good luck!
#!/usr/bin/perl

use warnings;
use strict;

use Mojo::UserAgent;
use Mojo::IOLoop;

my $site = 'http://SITENAME/?id=';
my $cookie_name = 'cookienum123';

#open filehandle and write file header
open my $output_fh, q{>}, 'results.txt'
    or die $!;
print {$output_fh} "#\t\tValue\n";

# Use Mojo::UserAgent for concurrent non-blocking requests
my $ua = Mojo::UserAgent->new;

#create your requests
for my $i (1..10000) {

    #build transaction
    my $tx = $ua->build_tx(GET => "$site$i");

    #add cookie header
    $tx->req->cookies({name => $cookie_name, value => $i});

    #start "GET" with callback to write to file
    $tx = $ua->start( $tx => sub {
      my ($ua, $mojo) = @_;
      print {$output_fh} $i . "\t\t" . $mojo->res->dom->to_string;
    });
}

# Start event loop if necessary
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

#close filehandle
close $output_fh;


Rabbitmq pika on multi process and multi threaded architecture

Question: I have the following scenario. I have a

python based web server (which publishes) - (Single process and multi threaded)
Scheduled job (which publishes) (Single process and multi threaded to run different jobs)
Consumer from rabbitmq queue (Subscribes to rabbitmq topic) (Single process and multi threaded to consume different messages)

I am currently trying to use rabbitmq for the above stack. So for the above case I want to create single rabbitmq connection for each process and use multiple channels for supporting multi threaded tasks. The Rabbitmq documentation says its fine to use multiple channels to support multiple threads. But pika library doesn't seem to support this scenario. You can refer the following example I have tried
<code>import pika
import threading
import time

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))

def test_thread(a: int):
    channel = connection.channel()
    channel.exchange_declare(exchange='normal_ex', exchange_type='topic')
    channel.basic_publish(exchange='normal_ex', routing_key='test', body=str(a))

for i in range(0, 10):
    t = threading.Thread(target=test_thread, args=[i])
    t.start()

time.sleep(10)
connection.close()
</code>
When I run the above program which uses multiple channels across multiple threads I am getting the following errors
Stream connection lost: AssertionError(('_AsyncTransportBase._produce() tx buffer size underflow', -21, 1))
Answer: from https://pika.readthedocs.io/en/stable/faq.html#frequently-asked-questions

Is Pika thread safe?

Pika does not have any notion of threading in the code. If you want to use Pika with threading, make sure you have a Pika connection per thread, created in that thread. It is not safe to share one Pika connection across threads, with one exception: you may call the connection method add_callback_threadsafe from another thread to schedule a callback within an active pika connection.


Utilizar parâmetro passado em função dentro do map()

Question: Minha função:
nameById (url, list, getter = "name") {
    let name = '';
    let id = url.split('/').reverse()[1];
    list.map( user => user.id == id ? name = user.name : null); // name = user.getter
    return name;
},

Existe alguma forma de usar esse parâmetro getter dentro do map ?
Dessa forma eu poderia usar essa função não só para buscar por "name" mas por qualquer outra key.
nameById('http://localhost:8000/scrum-list/sprint-list/7/', sprintList, 'code') // O retorno seria a propriedade de code e não name

Comment: Tente dessa forma `list.map( user => user.id == id ? name = user[getter] : null);`
Comment: Funcionou, vlw!!! Não sabia que era possível fazer isso.
Answer: Ao passar uma variavel para selecionar uma propriedade em um objeto, use obj[variavel]. Considerando o seguindo objeto:
obj = {
    nome: 'Lucas',
    idade: 24
}

Se utilizarmos a seguinte função:
function a(key = "nome"){
    console.log(obj.key)
}

Não irá funcionar, porque assim estamos buscando por uma propriedade chamada key especificamente, e não o conteúdo da variavel key. Para isso podemos fazer:
function a(key = "nome"){
    // isso é mesmo que obj.nome
    console.log(obj[key]); // irá olhar para o conteúdo de key, nesse caso "nome"
}


Using ARMA when data is missing

Question: I am using ARMA over a dataset with missing samples. How do I treat them? Would you suggest to make linear/nonlinear interpolation or just keep them out and consider two samples with missing data in between as consecutive samples?
Answer: There is no need to do anything. An ARMA model can easily be estimated with missing values within the time series. You need to use the state space representation of an ARMA model to compute the likelihood. If you use R, this is already handled automatically via the arima() function.
Comment: The best approach to estimating an ARMA model is maximum likelihood estimation. To do that, you need to calculate the likelihood of the data given the model and parameters. Any decent ARMA software will do that, but not all of them do it using a state space representation which is needed in order to handle missing values.
Comment: thanks for your comment. What do you mean exactly by computing the likelihood? Are you saying that I should do some kind of regression for the missing samples?
Comment: could you, please, provide a reference? I need to implement it myself :)

Using ARMA when data is missing


Interpretation of the equation of a horocycle in the hyperboloid model.

Question: Let $v$ be non-zero with $B(v,v)=0$. I would like to show that an equation $B(u,v)=1$ defines a horocycle in the hyperboloid model.
A horocycle in the Poincare disk model has a touching point $v$ on the boundary of the unit circle. And if we see this $v$ in the hyperboloid model, $v$ will be a point at infinity on the asymptotic cone. In the hyperboloid model, a horocycle with $v$ is the intersection of the hyperboloid ($-x^2-y^2+z^2=1$) and some plane that is parallel to the vector $v$. Plus, as the asymptotic cone is defined by the equation $x^2+y^2=z^2$, we have $B(v,v)=0$ and $v \neq 0$.
If I have understood the equation correctly, for any $u$ in a horocycle that is (Euclidean Sense) parallel to the vector $v$, we have $B(u,v)=1$.
However, I'm not sure why we should have $B(u,v)=1$ for any $u$ on a horocycle.
Can you please help me in understanding this equation?
EDIT:
I found that $B(u,v)=1$ gives the equation of the plane. And this plane must have the normal vector $(v_1,v_2,-v_3)$ if $v=(v_1,v_2,v_3)$. Thus, by wikipedia definition of horocycle in the hyperboloid model, the equation $B(u,v)=1$ defines a horocycle if we just let $u \in H$ where $H$ stands for the hyperboloid.
Did I get it right?
Comment: I'm pretty sure the Wikipedia definition of horocycle is not the definition in your course or textbook. Even though it might be equivalent, this exercise is about *proving* this equivalence. If you want to solve the problem properly, you will need to show that your course/textbook's definition of horocycle is satisfied.
Answer: This answer assumes that the definition of a horocycle is in terms of constant curvature, which would be implied by the existence of isometric motion translating along it.
To show that the curve $C_v := \{u: \langle u,v\rangle = 1\}$ you define has constant curvature, you want to find a continuous family of hyperbolic isometries that preserves this curve. Once you find this family, all that remains is to show that it is the correct kind of constant-curvature curve, so not a circle or a hypercycle or a geodesic.
To find such a family of isometries preserving the given curve, you have basically two approaches:
Option 1: Pick your favourite $v$, e.g. $v = (1,0,1)$, and just find a family of isometries in $O(2,1)$ preserving this particular $v$, probably as a parametrized matrix. Isometries preserve $B$ by definition, so if they also preserve $v$, they automatically preserve $C_v$ too since it was defined in terms of $B$ and $v$.
Once you've showed that $C_v$ is a horocycle, by symmetry of the hyperboloid model you immediately obtain that all $C_w$ are horocycles too for any other $w \neq 0$ with $B(w,w)=0$: if an isometry maps $w$ to $v$, it will map $C_w$ to the horocycle $C_v$ (again since $C_w$ was defined in terms of $B$ and $w$), so $C_w$ is also a horocycle.
Option 2: Let $v$ be arbitrary instead of fixing it, and extend $v$ to a basis whose pairwise $B$-products have nice known values like $0$ or $1$ or $-1$ by applying some Gram-Schmidt analogous stuff. Now again, find a family of isometries preserving $v$, but instead of writing them in matrix form, try to write them in terms of your basis vectors and $B$. If you manage to do this, the part where you prove they are in fact $v$-preserving isometries will be a very simple term rewriting exercise which does not require any coordinate math.
Comment: Except constant curvature is not enough. A better definition is that a horocycle is an orbit of a 1-parameter parabolic (unipotent) subgroup.
Comment: @MoisheKohan Yes, that is what I meant by "correct kind of curve". There are several ways to define which kind of constant-curvature curve is a horocycle, and I didn't want to make more assumptions about definitions than necessary in my answer.


DirectX camera Positioning for First Person Shooter

Question: Hi i am using DirectX 10 and C++ to make a very simple first person shooter just a gun and targets, i have the gun and the target and the gun shoots bullets in the corrct direction etc.
however i cannot get the camera to be locked on the gun and looking at the crosshairs,
for the camera i have this
<code>vecEye.x = g_f_GunX;
vecEye.y = g_f_GunY + 3;
vecEye.z = g_f_GunZ - 5.0;

vecAt.x = g_f_CrossX;
vecAt.y = g_f_CrossY;
vecAt.z = g_f_CrossZ;

g_Camera.SetViewParams( &vecEye, &vecAt );
</code>
for the purpose of this my crosshair is just an object that is infront of the gun and it moves with the gun, i have put the code for the camera in the 'onFrameRender' method
it is my assumption that this code should put the camera just behind my gun and when the gun (and crosshairs) are moved the camera should be looking at the crosshairs all the time in the center of the screen, however on running it the camera is not doing this at all and doesnt move with gun or crosshairs at all
any help would be much appriciated
Answer:
for the purpose of this my crosshair is just an object that is in front of the gun and it moves with the gun

That's not going to work unless "eye" is located directly behind the gun barrel (gun will block the view) - if "eye" is even slightly above gun, you'll end up looking at ground through the crosshair object, and view direction won't match camera direction at all.
Several ways to deal with it:

Draw crosshair in the middle of screen as 2d shape, shoot bullets from the camera, and  draw gun model just for show. I think that was fairly common way to do it in the "old days" (doom 1 and such)
Draw crosshair in the middle of screen as 2d shape. Make a collision detection sensor (ray) that starts at the camera position, and points in same direction as camera. When user presses "fire" run a collision query using this ray sensor, and if it hits anything, fire gun at that point. That's the only real way to deal with aiming if you're writing 3rd person shooter.
Remove cross-hair and user laser pointer/sight to aim the gun (Might look cool), shoot bullets from gun. Laser pointer ray should originate from gun, of course. This was used in zero tolerance, avp and few other games.

Also in 3d shooters camera orientation is frequently stored as a yaw/pitch/roll combination of angles.
Comment: thanks for that ill give it a try now, dont suppose you could shed any light on another question of mine (pun not intended) http://stackoverflow.com/questions/9955762/directx-lighting


What does ":" do in jQuery?

Question:
Possible Duplicate:
What does ':' do in JavaScript?

I'm trying to learn jQuery and I noticed the following syntax in someone's code. It would be great if some one can explain it to me.
functionName: function(form, callback)
    {
        form.submit(function(event) {
            event.preventDefault();
            callback(TestPageUtils.getFormParams(form));
            return false;
        });
    }

Comment: Back to the basics. I suggest you start with JavaScript, and then go to jQuery, a whole different world!
Comment: @user1558274 - Actually, jQuery is a perfectly appropriate place to start.  It's a great way to just "get stuff done" (by not having to dwell on low level details and/or reinvent the wheel), studying jQuery is also a great way to learn "good style".  I think you're doing the right thing.  IMHO...
Answer: The syntax { property: value } is standard JavaScript notation.
At the left hand of your colon is the property name, in your case "functionName", at the right hand is its value, in your case a function definition.
These functions, then, are comma separated:
var obj = { x: 1, f: function(a) { alert(a); } };

alert(obj.x) // alerts 1
obj.f(1)     // alerts 1

Answer: That's "not" jQuery, but general Javascript syntax. And that is how you define a member inside an object literal, in this case, that member is a function.
For example:
person =
{
    name: "John",
    age: 432,
    walk: function (){alert("Walking!");}
}

Is another Javascript object. To access its members, simply do person.name. Or, if you want the person to walk, call its walk method like this: person.walk().
Answer: that's not "jQuery" per se - it's basic Javascript syntax.
The ":" says the property "functionName" has the value function(...) { ... }
Here's a good diagram (the same construct is often used in JSON syntax):
http://www.json.org/

What does ":" do in jQuery?


Writing an Excel file in EPPlus

Question: I have been stuck on this for days and despite all of the help out there, none of these solutions have been working for me. What I want to do is create an excel file using the EPPlus library with some basic data in it that I am pulling from a stored procedure. This is the code that I have in my ExportDocument.cs file:
public static ExcelPackage CreateExcelDocument(int [] arr)
{
    String path = @"D:\temp\testsheet3.xlsx";
    //FileInfo newFile = null;
    /*if (!File.Exists(path + "\\testsheet2.xlsx"))
    newFile = new FileInfo(path + "\\testsheet2.xlsx");
    else
        return newFile;*/
    using (ExcelPackage package = new ExcelPackage())
    {
        ExcelWorksheet ws = package.Workbook.Worksheets.Add("testsheet");
        ws.Cells["B1"].Value = "Number of Used Agencies";
        ws.Cells["C1"].Value = "Active Agencies";
        ws.Cells["D1"].Value = "Inactive Agencies";
        ws.Cells["E1"].Value = "Total Hours Volunteered";
        ws.Cells["B1:E1"].Style.Font.Bold = true;

        int x = 2;
        char pos = 'B';
        foreach (object o in arr)
        {
            String str = pos + x.ToString();
            ws.Cells[str].Value = o.ToString();
            if (pos > 'E')
            {
                pos = 'B';
                x++;
            }
            pos++;
        }
        package.Save();
        return package;
    }
}

All the commented code is different things that I have found on the internet to try. Note that this a school organization and we are not using MVC. I am then using the code behind file to pull this method like this:
protected void GenerateReport(Object o, EventArgs e)
{
    Session["reportSession"] = ddReport.SelectedItem.Value.ToString();
    int [] arr = new int [ReportRepository.GetAgencyCounts().Count];
    ReportRepository.GetAgencyCounts().CopyTo(arr, 0);

    ExcelPackage pck = ExportDocument.CreateExcelDocument(arr);
    /*try
    {
        byte [] data = ExportDocument.CreateExcelDocument(arr).GetAsByteArray();
        Response.Clear();
        Response.Buffer = true;
        Response.BinaryWrite(data);
        Response.AddHeader("content-length", data.Length.ToString());
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.Flush();
        Response.Close();
        Response.End();
    }
    catch (Exception ex) { }*/

    /*var stream = new MemoryStream();
    pck.SaveAs(stream);

    String filename = "myfile.xlsx";
    String contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    var cd = new System.Net.Mime.ContentDisposition
    {
        Inline = false,
        FileName = filename
    };
    Response.AppendHeader("Content-Disposition", cd.ToString());
    stream.Position = 0;

    return File(stream, contentType, filename);*/

    /*Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + file.Name);
    Response.TransmitFile(Path.GetFullPath(file.Name));
    Response.Flush();
    Response.Close();*/

    /*Response.ClearHeaders();
    Response.BinaryWrite(pck.GetAsByteArray());
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;  filename=Sample2.xlsx");
    Response.Flush();
    Response.Close();*/
}

Again note that all the commented code is things that I have found from various sources that have not worked.
So I am not getting any errors but when I click the button on my application to execute the code behind method, nothing is happening. It is loading and it runs through but there are no files created, nothing is opening up. This is the first time I have ever used EPPlus and I am not wholly familiar with exporting things to excel programmatically so I feel lost here.
Are there any suggestions that you guys have? I would be happy to clarify any points that I have not hit upon fully as well.
Comment: you've declared a `path`, but I don't see it used in the code (ignoring the commented bits). How are you telling excelpackage to save it to a location?
Comment: the path variable currently is not being used. The way it is written now, it is the ExcelPackage package object is using its save method and then I am calling that ExcelPackage in the codebehind file where I am writing it out using Response.BinaryWrite(byte[] arr). That was the last method I tried anyway. Using that, there is no need for a path.
Comment: Additionally, I also tried saving the file to a path and then opening it from there but I ended up getting the same issue I am having now. The file was never created and my code did not bomb or error out
Comment: OK - so [this answer](http://stackoverflow.com/a/13376386/326543) suggests that you need to use a stream to get content from `package` to file. Could you see if this works for you?
Comment: I tried that too. It is commented out in my ExportDocument.cs file. I get the same thing as before. No files are created and nothing shows up
Comment: Hmm that is really strange, I'll try to setup something quick and dirty, to play around and see if I can replicate this.
Comment: @DustinLeatherman -- I find myself with very similar issues -- did you ever get this bit of source working?
Answer: Have you looked at the samples provided with EPPlus?
This one shows you how to create a file
http://epplus.codeplex.com/wikipage?title=ContentSheetExample
This one shows you how to use it to stream back a file
http://epplus.codeplex.com/wikipage?title=WebapplicationExample
This is how we use the package to generate a file.
var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
    // do work here
    xlPackage.Save();
}

Comment: Use `SaveAs(FileInfo)` method to save to a new location. It also overwrites if file name already exists, unlike `Save` method which throws. Example: http://stackoverflow.com/a/38036089
Comment: You don't need to call xlPackage.Dispose() before the end of using block, because the whole purpose of a using block is to call a dispose method on an object created in the parentheses.
Comment: True, however it was pinched from the examples.
Answer: It's best if you worked with DataSets and/or DataTables. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:
ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);
.. which will produce a beautiful excelsheet with a nice table!
Now to serve your file, assuming you have an ExcelPackage object as in your code above called pck..
Response.Clear();

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);

Response.BinaryWrite(pck.GetAsByteArray());
Response.End();

Answer: If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection.
using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");

    worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);

    package.Save();
}

Writing an Excel file in EPPlus


How to reliably map vSphere disks <-> Linux devices

Question: Task at hand
After a virtual disk has been added to a Linux VM on vSphere 5, we need to identify the disks in order to automate the LVM storage provision.
The virtual disks may reside on different datastores (e.g. sas or flash) and although they may be of the same size, their speed may vary. So I need a method to map the vSphere disks to Linux devices.
Ideas
Through the vSphere API, I am able to get the device info:
<code>Data Object Type: VirtualDiskFlatVer2BackingInfo
Parent Managed Object ID: vm-230
Property Path: config.hardware.device[2000].backing

Properties

Name Type Value
ChangeId string Unset
contentId string "d58ec8c12486ea55c6f6d913642e1801"
datastore ManagedObjectReference:Datastore datastore-216 (W5-CFAS012-Hybrid-CL20-004)
deltaDiskFormat string "redoLogFormat"
deltaGrainSize int Unset
digestEnabled boolean false
diskMode string "persistent"
dynamicProperty DynamicProperty[] Unset
dynamicType string Unset
eagerlyScrub boolean Unset
fileName string "[W5-CFAS012-Hybrid-CL20-004] l****9-000001.vmdk"
parent VirtualDiskFlatVer2BackingInfo parent
split boolean false
thinProvisioned boolean false
uuid string "6000C295-ab45-704e-9497-b25d2ba8dc00"
writeThrough boolean false
</code>
And on Linux I may read the uuid strings:
<code>[root@lx***** ~]# lsscsi -t
[1:0:0:0]    cd/dvd  ata:                            /dev/sr0
[2:0:0:0]    disk    sas:0x5000c295ab45704e          /dev/sda
[3:0:0:0]    disk    sas:0x5000c2932dfa693f          /dev/sdb
[3:0:1:0]    disk    sas:0x5000c29dcd64314a          /dev/sdc
</code>
As you can see, the uuid string of disk /dev/sda looks somehow familiar to the string that is visible in the VMware API. Only the first hex digit is different (5 vs. 6) and it is only present to the third hyphen. So this looks promising...
Alternative idea
Select disks by controller. But is it reliable that the ascending SCSI Id also matches the next vSphere virtual disk? What happens if I add another DVD-ROM drive / USB Thumb drive? This will probably introduce new SCSI devices in between. Thats the cause why I think I will discard this idea.
Questions

Does someone know an easier method to map vSphere disks and Linux devices?
Can someone explain the differences in the uuid strings? (I think this has something to do with SAS adressing initiator and target... WWN like...)
May I reliably map devices by using those uuid strings?
How about SCSI virtual disks? There is no uuid visible then...
This task seems to be so obvious. Why doesn't Vmware think about this and simply add a way to query the disk mapping via Vmware Tools?
Comment: [Identifying disks when working with VMWare ESX/ESXi - VMWare KB 1014953](http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1014953)
Comment: Thank you for the link. The KB article is mostly based on identifiying disks directly on the ESX hosts. My mission is to identify it from within the virtual machine.
Comment: Um. You could simply expose / provide this information through a proxy service accessible by the guest OS. Dump it to text files on a web server, if you must.
Comment: I have only access to the vSphere system via the Vmware API. Also I do not know exactly where a VM is located. They may reside on different hosts and spread over different datastores.
Comment: esxcli *is* using the VMWare API. You can target individual ESXi systems as well as your vCenter host with it - see http://pubs.vmware.com/vsphere-50/index.jsp?topic=%2Fcom.vmware.vcli.getstart.doc_50%2Fcli_jumpstart.3.4.html. I am not quite sure what you are aiming at - is it that you do not want to use `esxcli` and want the property name to retrieve the disk's WWN using the API?
Answer: Use the SCSI ID to identify the virtual disk.  You seem to be under the impression that the SCSI ID is dynamically assigned when the VM powers on.  This is not the case.  In the properties of the VM, you can set the ID for your virtual disk to whatever you want, and it will not change unless you want it to.
Comment: Background: The automation is for a large scale deployment (>100 VMs; some of them are new VMs, others may already exist and will get multiple VMDKs added by the Vmware API). I know that Vmware will usually stick with the drive order once the machine is setup. But how do I distinguish all the disks on the VM when there may be additional disks raw device mapped or manually added to the VM because there was a ticket to increase some filesystem before our deployment starts. With the Vmware API I could get a list of existing disks and could get meta data of all new LUNs that I would add to them.


Turn "log slow queries" ON

Question: I'm trying to log mysql slow queries, but I can't turn it on.
I will explain all my steps:
Open and Edit my.cnf and add the following lines:
long_query_time = 5
slow_query_log_file = /myfolder/slowq.log
log_slow_queries = 1                     =>(I have MySQL 5.0.7)

Give mysql user permitions to write on the file:
chown -R mysql:mysql /var/lib/mysql

Create the file:
touch /myfolder/slowq.log

Chmod for this file to 777.
service mysqld restart

From MySQL Admin Panel I can see that the "log_slow_queries" var is OFF!
Also no logs are created.
Thanks in advance!
Best Regards, Panos.
Answer: into my.cnf write this under mysqld then you need to restart the server(mysql) also make sure you can write int the directory where you want to log
[mysqld]
log-slow-queries=/var/log/mysqld-slow-queries.log

Turn "log slow queries" ON


Flutter app crashes on firebase phone auth in iOS platform

Question: I have implemented Firebase Phone auth in my project,
On android side everything works fine, but for iOS side, when i try to send verification code from my end, app crashes and lost connection.
I have submitted my code below.
main.dart
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        home: new MyHomePage(),
        routes: <String, WidgetBuilder> {
          '/homepage': (BuildContext context) => MyApp(),
          '/landingpage': (BuildContext context) => MyHomePage()
        }
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String phoneNo;
  String smsCode;
  String verificationId;

  Future<void> verifyPhone() async {
    print("main");
    final PhoneCodeAutoRetrievalTimeout autoRetrieve = (String verId) {
      print("varification id");
      this.verificationId = verId;
    };

    final PhoneCodeSent smsCodeSent = (String verId, [int forceCodeResend]) {
      print("send code dilog");
      this.verificationId = verId;
      smsCodeDialog(context).then((value) {
        print('Signed in');
      });
    };

    final PhoneVerificationCompleted verifiedSuccess = (AuthCredential user){
      print('Phone Verification Completed');
    };

    final PhoneVerificationFailed veriFailed = (AuthException exception) {
      print('${exception.message}');
    };

    await FirebaseAuth.instance.verifyPhoneNumber(

        phoneNumber: "+919700000000",
        codeAutoRetrievalTimeout: autoRetrieve,
        codeSent: smsCodeSent,
        timeout: const Duration(seconds: 5),
        verificationCompleted: verifiedSuccess,
        verificationFailed: veriFailed);
  }

  Future<bool> smsCodeDialog(BuildContext context) {
    return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: Text('Enter sms Code'),
            content: TextField(
              onChanged: (value) {
                this.smsCode = value;
              },
            ),
            contentPadding: EdgeInsets.all(10.0),
            actions: <Widget>[
              new FlatButton(
                child: Text('Done'),
                onPressed: () {
                  FirebaseAuth.instance.currentUser().then((user) {
                    if (user != null) {
                      Navigator.of(context).pop();
                      Navigator.of(context).pushReplacementNamed('/homepage');
                    } else {
                      Navigator.of(context).pop();
                      signIn();
                    }
                  });
                },
              )
            ],
          );
        });
  }

  signIn(){
    final AuthCredential credential = PhoneAuthProvider.getCredential(
        verificationId: verificationId,
        smsCode: smsCode);

    FirebaseAuth.instance.signInWithCredential(credential).then((user){
      Navigator.of(context).pushReplacementNamed('/homepage');
    }).catchError((e){
      print('Auth Credential Error : $e');
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('PhoneAuth'),
      ),
      body: new Center(
        child: Container(
            padding: EdgeInsets.all(25.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                TextField(
                  decoration: InputDecoration(hintText: 'Enter Phone number'),
                  onChanged: (value) {
                    this.phoneNo = value;
                  },
                ),
                SizedBox(height: 10.0),
                RaisedButton(
                    onPressed: verifyPhone,
                    child: Text('Verify'),
                    textColor: Colors.white,
                    elevation: 7.0,
                    color: Colors.blue)
              ],
            )),
      ),
    );
  }
}

this is error while submit the button
Launching lib/main.dart on Dhruvin's iPhone in debug mode...
Automatically signing iOS for device deployment using specified development team in Xcode project: ******
Running Xcode build...
Xcode build done.                                           99.4s
Installing and launching...
Syncing files to device Dhruvin's iPhone...
Lost connection to device.

However i am not able to see stacktrace or log as app lost connection from debugger.
Comment: If seems like there is some iOS configuration issue in app, please refer iOS setup part and follow all the steps (You need to add reverse client id as well please check conform you have implemented it)
Answer: i Solved the Problem,
thank you so much @DevarshRanpura for Helping me,
1) replace
signIn(){
    final AuthCredential credential = PhoneAuthProvider.getCredential(
        verificationId: verificationId,
        smsCode: smsCode);

    FirebaseAuth.instance.signInWithCredential(credential).then((user){
      Navigator.of(context).pushReplacementNamed('/homepage');
    }).catchError((e){
      print('Auth Credential Error : $e');
    });
  }

to this
signIn() async {
    final AuthCredential credential = PhoneAuthProvider.getCredential(
      verificationId: verificationId,
      smsCode: smsCode,
    );
    final AuthResult authResult = await _auth.signInWithCredential(credential);
    final FirebaseUser user = authResult.user;
    print('User Id : ' + user.uid);
  }

also Define _auth on your dart file
final FirebaseAuth _auth = FirebaseAuth.instance;

2) adding reverse client id in to your project

open your project in xcode
double click on your project name
go to the info tab
In URL Types->URL schemes add the reverse client Id
Comment: Here is a good explanation: https://stackoverflow.com/questions/61514076/firebase-phone-auth-getting-ios-error-register-custom-url-scheme
Comment: "In URL Types->URL schemes add the reverse client Id" -> can you explain this, please?
Comment: thank you @ValentinSeehausen for more visual explaning the problem, now more devlopers can easy to solve this issue.


How to get hyper parameters in nested cross validation?

Question: I have read the following posts for nested cross validation and still am not 100% sure what I am to do with model selection with nested cross validation:

Nested cross validation for model selection
Model selection and cross-validation: The right way

To explain my confusion, let me try to walk through the model selection with nested cross validation method step by step.

Create an outer CV loop with K-Fold. This will be used to estimate the performance of the hyper-parameters that "won" each inner CV loops.
Use GridSearchCV to create an inner CV loop where in each inner loop, GSCV goes through all possible combinations of the parameter space and comes up with the best set of parameters.
After GSCV found the best parameters in the inner loop, it is tested with the test set in the outer loop to get an estimation of performance.
The outer loop then updates to the next fold as the test set and the rest as training set, and 1-3 repeats. Total possible "winning" parameters are number of folds designated in the outer loop. So if the outer loop is 5 folds, then you will have a performance estimation of an algorithm with 5 different sets of hyper parameters, NOT the performance of one particular set of hyper parameters.

This approach is illustrated on SKLearn's example page:
http://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html
Question:
After 4., how do you determine which hyper parameters worked the best? I understand that you want to train your algorithm (e.g. Logistic Regression, Random Forest, etc.) with the COMPLETE data set at the end. But how do you determine which hyper parameters worked the best in your nested cross validation? My understanding is that for each inner loop, a different set of hyper parameters will win. And for the outer loop, you are getting an estimation of your GridSearchCV performance, but you are not getting any one particular set of hyper parameters. So, in the final model creation, how do you know what hyper parameters to use? That's the missing logic I have trouble understanding from other treads.
Thank you in advance for any tips, especially if @Dikran Marsupial and @cbeleites can chime in!
Edit: If you can, please in your answer use terms like "algorithm" and "hyper parameters". I think one source of confusion for me is when people use the term "model" or "model selection". I get confused whether they are talking about selecting which algorithm to use or what hyper parameters to use.
Edit 2: I have created a notebook that shows two ways of doing nested cross validation. First way is the one shown in the SKLearn example, and another longer way is one that I wrote. The way shown in SKLearn doesn't expose the "winning" hyperparameters, but my longer way does. But the question remains the same. After I have completed the nested cross validation, even with the hyperparameters exposed, what do I do now? As you can see from the hyperparameters at the end of the notebook, they vary quite a bit.
Comment: +1 for the notebook. This question is of interest to me as well and will follow up.
Answer: (I'm sure I wrote most of this already in some answer - but can't find it right now. If anyone stumbles across that answer, please link it).
I see 2 slightly different approaches here, which I think are both sensible.
But first some terminology:

Coming from an applied field, a (fitted/trained) model for me is a ready-to-use. I.e. the model contains all information needed to generate predictions for new data. Thus, the model contains also the hyperparameters. As you will see, this point of view is closely related to approach 2 below.
OTOH, training algorithm in my experience is not well defined in the following sense: in order to get the (fitted) model, not only the - let's call it "primary fitting" - of the "normal" model parameters needs to be done, but also the hyperparameters need to be fixed. From my application perspective, there isn't really much difference between parameters and hyperparamers: both are part of the model, and need to be estimated/decided during training.
I guess the difference between them is related to the difference between someone developing new training algorithms who'd usually describe a class of training algorithms together with some steering parameters (the hyperparameters) which are difficult/impossibe to fix (or at least to fix how they should be decided/estimated) without application/domain knowledge.

Approach 1: require stable optimization results
With this approach, "model training" is the fitting of the "normal" model parameters, and hyperparameters are given. An inner e.g. cross validation takes care of the hyperparameter optimization.
The crucial step/assumption here to solve the dilemma of whose hyperparameter set should be chosen is to require the optimization to be stable. Cross validation for validation purposes assumes that all surrogate models are sufficiently similar to the final model (obtained by the same training algorithm applied to the whole data set) to allow treating them as equal (among themselves as well as to the final model). If this assumption breaks down and

the surrogate models are still equal (or equivalent) among themselves but not to the final model, we are talking about the well-known pessimistic bias of cross validation.
If also the surrogate model are not equal/equivalent to each other, we have problems with instability.

For the optimization results of the inner loop this means that if the optimization is stable, there is no conflict in choosing hyperparameters. And if considerable variation is observed across the inner cross validation results, the optimization is not stable. Unstable training situations have far worse problems than just the decision which of the hyperparameter sets to choose, and I'd really recommend to step back in that case and start the
modeling process all over.
There's an exception, here, though: there may be several local minima in the optimization yielding equal performance for practical purposes. Requiring also the choice among them to be stable may be an unnecessary strong requirement - but I don't know how to get out of this dilemma.
Note that if not all models yield the same winning parameter set, you should not use outer loop estimates as generalization error here:

If you claim generalization error for parameters $p$, all surrogate models entering into the validation should actually use exactly these parameters.
(Imagine someone told you they did a cross validation on model with C = 1 and linear kernel and you find out some splits were evaluated with rbf kernel!)
But unless there is no decision involved as all splits yielded the same parameters, this will break independence in the outer loop: the test data of each split already entered the decision which parameter set wins as it was training data in all other splits and thus used to optimize the parameters.

Approach 2: treat hyperparameter tuning as part of the model training
This approach bridges the perspectives of the "training algorithm developer" and applied user of the training algorithm.
The training algorithm developer provides a "naked" training algorithm model = train_naked (trainingdata, hyperparameters). As the applied user needs  tunedmodel = train_tuned (trainingdata) which also takes care of fixing the hyperparameters.
train_tuned can be implemented e.g. by wrapping a cross validation-based optimizer around the naked training algorithm train_naked.
train_tuned can then be used like any other training algorithm that does not require hyperparameter input, e.g. its output tunedmodel can be subjected to cross validation.  Now the hyperparameters are checked for their stability just like the "normal" parameters should be checked for stability as part of the evaluation of the cross validation.
This is actually what you do and evaluate in the nested cross validation if you average performance of all winning models regardless of their individual parameter sets.

What's the difference?
We possibly end up with different final models taking those 2 approaches:

the final model in approach 1 will be train_naked (all data, hyperparameters from optimization)
whereas approach 2 will use train_tuned (all data) and - as that runs the hyperparameter optimization again on the larger data set - this may end up with a different set of hyperparameters.

But again the same logic applies: if we find that the final model has substantially different parameters from the cross validation surrogate models, that's a symptom of assumption 1 being violated. So IMHO, again we do not have a conflict but rather a check on whether our (implicit) assumptions are justified. And if they aren't, we anyways should not bet too much on having a good estimate of the performance of that final model.

I have the impression (also from seeing the number of similar questions/confusions here on CV) that many people think of nested cross validation doing approach 1.
But generalization error is usually estimated according to approach 2, so that's the way to go for the final model as well.

Iris example
Summary: The optimization is basically pointless. The available sample size does not allow distinctions between the performance of any of the parameter sets here.
From the application point of view, however, the conclusion is that it doesn't matter which of the 4 parameter sets you choose - which isn't all that bad news: you found a comparatively stable plateau of parameters. Here comes the advantage of the proper nested validation of the tuned model: while you're not able to claim that the it is the optimal model, your're still able to claim that the model built on the whole data using  approach 2 will have about 97 % accuracy (95 % confidence interval for 145 correct out of 150 test cases: 92 - 99 %)
Note that also approach 1 isn't as far off as it seems - see below: your optimization accidentally missed a comparatively clear "winner" because of ties (that's actually another very telltale symptom of the sample size problem).
While I'm not deep enough into SVMs to "see" that C = 1 should be a good choice here, I'd go with the more restrictive linear kernel. Also, as you did the optimization, there's nothing wrong with choosing the winning parameter set even if you are aware that all parameter sets lead to practically equal performance.
In future, however, consider whether your experience yields rough guesstimates of what performance you can expect and roughly what model would be a good choice. Then build that model (with manually fixed hyperparameters) and calculate a confidence interval for its performance. Use this to decide whether trying to optimize is sensible at all. (I may add that I'm mostly working with data where getting 10 more independent cases is not easy - if you are in a field with large independent sample sizes, things look much better for you)
long version:
As for the example results on the iris data set. iris has 150 cases, SVM with a grid of 2 x 2 parameters (2 kernels, 2 orders of magnitude for the penalty C) are considered.
The inner loop has splits of 129 (2x) and 132 (6x) cases.
The "best" parameter set is undecided between linear or rbf kernel, both with C = 1. However, the inner test accuracies are all (including the always loosing C = 10) within 94 - 98.5 % observed accuracy. The largest difference we have in one of the splits is 3 vs. 8 errors for rbf with C = 1 vs. 10.
There's no way this is a significant difference. I don't know how to extract the predictions for the individual cases in the CV, but even assuming that the 3 errors were shared, and the C = 10 model made additional 5 errors:
> table (rbf1, rbf10)
         rbf10
rbf1      correct wrong
  correct     124     5
  wrong         0     3

> mcnemar.exact(rbf1, rbf10)

    Exact McNemar test (with central confidence intervals)

data:  rbf1 and rbf10
b = 5, c = 0, p-value = 0.0625
alternative hypothesis: true odds ratio is not equal to 1

Remember that there are 6 pairwise comparisons in the 2 x 2 grid, so we'd need to correct for multiple comparisons as well.

Approach 1
In 3 of the 4 outer splits where rbf "won" over the linear kernel, they actually had the same estimated accuracy (I guess min in case of ties returns the first suitable index).
Changing the grid to
params = {'kernel':['linear', 'rbf'],'C':[1,10]}
yields
({'kernel': 'linear', 'C': 1}, 0.95238095238095233, 0.97674418604651159)
({'kernel': 'rbf', 'C': 1}, 0.95238095238095233, 0.98449612403100772)
({'kernel': 'linear', 'C': 1}, 1.0, 0.97727272727272729)
({'kernel': 'linear', 'C': 1}, 0.94444444444444442, 0.98484848484848486)
({'kernel': 'linear', 'C': 1}, 0.94444444444444442, 0.98484848484848486)
({'kernel': 'linear', 'C': 1}, 1.0, 0.98484848484848486)
({'kernel': 'linear', 'C': 1}, 1.0, 0.96212121212121215)

Approach 2:
Here, clf is your final model. With random_state = 2, rbf with C = 1 wins:
In [310]: clf.grid_scores_
[...snip warning...]
Out[310]:
[mean: 0.97333, std: 0.00897, params: {'kernel': 'linear', 'C': 1},
 mean: 0.98000, std: 0.02773, params: {'kernel': 'rbf', 'C': 1},
 mean: 0.96000, std: 0.03202, params: {'kernel': 'linear', 'C': 10},
 mean: 0.95333, std: 0.01791, params: {'kernel': 'rbf', 'C': 10}]

(happens about 1 in 5 times, 1 in 6 times linear and rbf with C = 1 are tied on rank 1)
Comment: Thanks @cbeleites! I read your answers in other threads too and I was hoping you'd answer my question. Your answer is very in depth but what my question is really focused on is how to analyze the results of a nested CV; I'm still a little unclear as to "what to do after I do nested CV".

Can you take a look at the notebook I created (near the end of my post) and in layman's term explain what to do since two different sets of hyperparameters have been identified as optimal in a nested CV? It's a very very short notebook, I promise!
Comment: @HeavyBreathing I've read the answer, and I'm still not that clear about 'what to do after I do nested CV'. Have you clearly figure that out?
Answer: I have read your question and the answer above 2 times (1st time 3 month ago). I'm interested and also want to find the absolute appropriate way to do cross-validation for my data. After a lot of thinking & reading, it seems that I find the holes and here is my fix:

To explain my confusion, let me try to walk through the model selection with nested cross validation method step by step.

Create an outer CV loop with K-Fold. This will be used to estimate the performance of the hyper-parameters that "won" each inner CV loops.
Use GridSearchCV to create an inner CV loop where in each inner loop, GSCV goes through all possible combinations of the parameter space and comes up with the best set of parameters. (Note: here I assume: data for inner loop = training data for outer loop. You may ask: why ? Answer: https://stackoverflow.com/questions/42228735/scikit-learn-gridsearchcv-with-multiple-repetitions/42230764#42230764 read the answer section by Vivek Kumar step 4)
After GSCV found the "best parameters" in the inner loop (let's call it inner winner), it is tested with the test set in the outer loop to get an estimation of performance (let's call it outer_fold_score1).
The outer loop then updates to the next fold as the test set and the rest as training set (to evaluate the "inner winner" on outer loop), the "inner winner" is tested again with the new test set (outer_fold_score2). Then again the outer loop updates to the next fold until the loop is completed. Scores from each fold (outer_fold_score 1,2..) will be average to get the score of the "inner winner" for the outer loop (outer_score)
The outer loop then updates to the next fold as the test set and the rest as training set (to find the next "inner winner" , and 1- 4 repeats (note that when we repeat 1 we don't create the new K-fold but we use the same outer Kfold every time). With each of 1-4 cycle, we get a "best parameters" (or "inner winner") with an outer_score. The one with the best outer_score will be the winner of the winners

Reasoning:

Basically your question concerns that there are many "winning parameters" for the outer loop. The thing is u didn't complete the outer loop to evaluate and find the "outer winner". Your 4th step only evaluate the "inner winner" in 1 fold in the outer loop, but u didn't "loop it". Therefore I need to replace it with my 4th step - "loop" the evaluation step in the outer loop and get the outer score (by averaging)
Your 5th step did do the "looping" job in the outer loop, but it's just for building another "inner winner". It didn't loop the "evaluation" of this "inner winner" in the outer loop
Comment: Does this really answer the question?
Answer: You do not use nested cross validation to select the hyper parameters of the algorithm, this method is used for estimating the generalisation error of your model building procedure. Where by model building procedure I intend all the steps you applied to reach the final model you are going to be using on field.
A model building procedure could be composed by the rules you applied to decide which preprocessing to apply to the data, which feature to use and finally which hyper parameters to use. Think of this as a sort of "meta-algorithm" that receives as input a particular dataset $D$ and produces as output an "algorithm", composed of a fixed set of preprocessing transformations, features and finally hyper parameters values.
For example let's say you have  $X , y$ as design matrix and target and you want to train a classifier:
 1. that uses only the first $x$ features in $X$ that have highest correlation with $y$.
 2. you choose the hyper parameters values by minimisation of a 10-fold cross validation error estimate.
If you apply these two step to a particular pair of $X', y'$ you will obtain a specific algorithm with a definite set of features and fixed hyper parameters which will not necessarily be the same of the one you would obtain for $X, y$ although the model building procedure would be identical i.e.: steps 1 +  2 which are not tied to any particular dataset.
Let's say you did all of the above without having split your data into train-test because you have a small dataset, how do you estimate the generalisation error of the classifier you just created? Can you use the best error you found in the cross validation at step 2 ?
No, the first big problem is in step 1 where you use all the data to select the features to use. Therefore even when you do the cross validation in step 2, the features will already have seen and remember some information present in the test fold at every cross validation run. The result will be an overly optimistic estimate of the test error and this is called feature selection bias. To account for this in your estimation you would need to put the feature selection step inside the cross validation loop of step 2.
Ok, now are we good? Is the best error found in the cross validation with feature selection step inside the loop a fair estimate of the generalisation error?
In theory the answer is still no, the problem is that your hyper parameters have been chosen to minimise the cross validation error on the specific dataset at your disposal, so in a certain sense you are fitting the hyper parameters to your data with the risk of over-fitting them , and this is called model selection bias.  But is this a concern in practice? It depends by the specific application: it is likely to become more severe, as overfitting in training, when dataset is small and the number of hyper parameters to be tuned is relatively large. To account for this when estimating the generalisation error you would apply a nested cross validation as you described, that would then give you a correct estimate of your generalisation error.
Finally to answer your last question, after having a fair estimate of your "model building procedure" generalisation error with a nested cross validation, you would simply apply the procedure (step 1+2) to your entire dataset obtaining a model with a fixed set of feature and set hyper parameters values, but keeping in mind that the error we expect this model to have on unseen data is the nested cross validation estimate.
Comment: The hyperparameters may overfit the model inside the training data but this is not a problem because this model is later used with the validation data.