window.showModalDialog não funciona no Google Chrome, existe algo equivalente?

Question: Bom dia, estou tentando abrir uma modal no google Chrome... A aplicação atual já usa a anos o window.showModalDialog, ela funciona no IE... não posso fazer as alterações usando a tag dialog do html 5, existe algum outro método ou uma função jquey/javascript que realiza o mesmo e que funcione google Chrome?
OBS: O método window.open não atende a necessidade!!
function CredencialEletronica(operacao, paramsInt, paramsDecimal, paramsString, paramsDate, paramsBool)
{
    var params = {'CodigoOperacao' : operacao
        , 'paramsInt' : paramsInt
        , 'paramsDecimal' : paramsDecimal
        , 'paramsString' : paramsString
        , 'paramsDate' : paramsDate
        , 'paramsBool' : paramsBool
        , 'date:' : new Date()};

        var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
        var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;

        width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
        height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

        var left = ((width / 2) - (440 / 2)) + dualScreenLeft;
        var top = ((height / 2) - (220 / 2)) + dualScreenTop;

        var result = window.showModalDialog('nomTela.aspx?' + $.param(params), '', 'Imagens;dialogHeight: 220px; dialogWidth: 440px;resizable: No; status: No;center: Yes; help: No');

        if (result == 'Ok') { return true; }
        else { return false; }
}

Comment: Olá, eu respondi essa mesma pergunta em outro post aqui. Possível duplicata da [249447](https://pt.stackoverflow.com/questions/249447/equivalente-ao-window-showmodaldialog-para-o-google-chrome/249475#249475)
Comment: Olá, como falei ali a tag dialog não me atende
Comment: Li a sua resposta antes de publicar, ficou muito boa, porem  não me atende :/
Answer: Parece que o chrome desabilitou essa funçao.. tens nesse post as explicaçoes e algumas ideias para contornar a situacao
https://stackoverflow.com/questions/25663053/how-can-i-make-window-showmodaldialog-work-in-chrome-37
edit:
diria entao para usares outra library, pode ser mesmo o dialog do jquery por exemplo, mas como esta tens muitas.
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Dialog - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.

https://jqueryui.com/dialog/
Comment: Nenhuma resposta foi marcada como solução... testei algumas e nenhuma atendeu o problema.
Comment: e para eu realizar a chamada de outra page? ao invés de uma div da mesma page...
Comment: oi gabriel: voce chegou a tentar inclusive usando BootStrap/JQuery como o colega sugeriu em uma das respostas?
Comment: para usar assim, tenho que mudar a estrutura da pagina, ela esta em asp net, terei que mudar todas as funções de classe para poder realizar desta forma
Answer: A função window.showModalDialog se tornou absoleta não só no Chrome (v.43) como também no Firefox (v.56). Inclusive, lendo a especificação da função, provavelmente se tornará obsoleta em mais browsers.
Ainda consultando a MDN, a solução proposta para a substituição dessa função é utilizar a tag HTML5 <dialog>. Vou colocar um exemplo abaixo, que foi retirado da MDN e você pode verificar se atende sua necessidade:

(function() {
  var botaoUpdate = document.getElementById('atualizarDetalhes');
  var botaoCancelar = document.getElementById('cancelar');
  var favDialog = document.getElementById('favDialog');

  // Abre a modal de diálogo
  botaoUpdate.addEventListener('click', function() {
    favDialog.showModal();
  });

  // Botão de cancelar fecha a modal de diálogo
  botaoCancelar.addEventListener('click', function() {
    favDialog.close();
  });
})();
<dialog open id="favDialog">
  <form method="dialog">

Animal favorito:
      <select id="favAnimal">
        <option></option>
        <option>Panda</option>
        <option>Leão</option>
        <option>Cachorro</option>
      </select>

    <menu>
      <button id="cancelar" type="reset">Cancelar</button>
      <button type="submit">Confirmar</button>
    </menu>
  </form>
</dialog>

<menu>
  <button id="atualizarDetalhes">Atualizar detalhes</button>
</menu>

EDIT:
Não tinha lido os comentários na sua pergunta e vi que a tag <dialog> não atende sua necessidade. Irei deixar a resposta pois é uma das alternativas cabíveis, caso alguém tenha o mesmo problema futuramente.
No seu caso, sugiro a criação de uma modal utilizando Bootstrap/JQuery, carregando o conteúdo do seu antigo "dialog" dentro dela, e depois, fazendo a lógica necessária:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#minhaModal">Abrir   Modal</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Cabeçalho

Carregar conteúdo da caixa de diálogo aqui.

          <button type="button" class="btn btn-primary" data-dismiss="modal">Ok</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>

Answer: A função parece ter sido descontinuada, e seu problema é bem comum de acontecer em aplicações legadas.
O que é possível fazer é verificar a existência da função, e caso ela não exista, crie uma que produza um resultado semelhante ao que precisa.
 if (typeof window.showModalDialog === "function") {
      window.showModalDialog = function (url, params) {
           // Implementação que faça uma chamada Ajax e adicione
           // o resultado em algum elemento na página.
      }
 }

Como provavelmente não terá nenhum elemento nas páginas para receber o conteúdo da chamada Ajax, recomendo adicionar o elemento toda vez que a função for chamada, e removida toda vez que o modal for fechado.
As implementações deste modal são várias, assim como já foi exemplificado em outras respostas, ou mesmo poderá usar alguma biblioteca pronta de modal.


Join a user field to a profile2 field in a view

Question: What I am trying to do is to join fields that are a user type (e.g. image, and username) to Profile2 fields.
In the example I want to join:

teacher name (teacher profile2)
teacher date (teacher profile2)
username (drupal registration)

What I mean by Drupal registration is the fields used to register an account.
Answer: If you have to the display profile fields using the Views module, then follow these steps:

Add "User:profile" under "RELATIONSHIPS".
Select "Profile types" in which type you have your fields to be display (teacher name, teacher date), as you may have more than one profile types.
You can add the selected profile fields under "Fields".


Transformation of a regression coefficient when independent variable was log-transdormed

Question: In the context of a linear regression model where the independent variable ($X$) was log-transformed, like:
$Y = \alpha + \beta·ln(X)$
Is there a straightforward way to transform a regression coefficient ($\beta$) that was estimated using log-transformed independent variable $X$?
I know that in this model, an increase of 1% in $X$ would mean an increase of $\beta·ln(X)$ in the value of $Y$.
Is there a way to transform $\beta$ so I could say that an increase of 1% in $X$ means an increase of $\beta'·X $ in variable $Y$?
Comment: Possible duplicate of [Back-transformation of regression coefficients](http://stats.stackexchange.com/questions/27067/back-transformation-of-regression-coefficients)
Comment: But of course: it's right in front of us.  If $X$ changes to $\alpha X$ (for positive $\alpha$, of course) then $\log(X)$ becomes $\log(\alpha)+\log(X)$, whence $Y$ becomes $Y + \beta\log\alpha$.  *But there is no "back-transformation" of any sort needed in this analysis.*
Comment: @whuber, why not develop that into an answer? I don't see an answer beyond that, and this isn't really a duplicate of the linked thread as it is about the transformation of Y whereas this is about the transformation of X.
Comment: Since $X$ was transformed, not $\beta$, a "back-transformation" of $\beta$ would seem to make no sense.  Could you clarify what you are hoping to achieve?
Comment: $\beta$ is estimated here using $ln(X)$, so interpretation dependens on $ln(X)$ [as in the main text: an increase of 1% in $X$ results in an increase of $\beta·ln(X)$ for $Y$]. What I wonder to achieve (if possible) is an expression of the change in $Y$ due to $X$ in terms not of $ln(X)$ but $X$ itself, using $ln(X)$ in regression analysis.
Answer: You can get some intuition for small changes in $X$ by considering
$$
\begin{align}
Y+\delta Y&=\alpha + \beta \ln(X + \delta X)\\
&=\underbrace{\alpha + \beta \ln X}_Y + \beta\ln\left(1+\frac{\delta X}{X}\right)\\
\therefore\delta Y&\approx \beta\frac{\delta X}{X},
\end{align}
$$
where the approximation is obtained by a Taylor series expansion of the logarithm to first order in $\delta X$.
In other words, a 1% increase in $X$ gives you an increase of $0.01\beta$ in the dependent variable. But this only holds for small changes in $X$.
Comment: When $\log(X)$ is used in a model, the natural way to represent changes to $X$ is *multiplicative,* not additive.  The question is clear about that: it refers to a "1% change," which is multiplicative.
Answer: You can't transform in the sense you'd wish in the question, i.e. preserving the interpretation of the coefficient $\beta$. In the log transformed regression $\beta$ becomes the sensitivity of the dependent variable to the percentage change in the independent variable (IV), instead of the sensitivity to the simple change in IV. In other words, $\beta$ in the log transformed case isthe measure of the relative sensitivity rather than absolute one.


how to find the number of subsets?

Question:
Let A = {1, 2, 3, 4, 5, 6, 7, 8} $$S ⊆ P(A)$$ For every subset in S, each
  one contains 4 elements and for every element in A it belongs to 3
  subsets that are in S, how many subsets are in S?

Any ideas how to approach this questions?
Answer: The sum of cardinalities of sets in $S$ is $3×8=24$ since each of the $8$ elements in $A$ appears $3$ times. Since each set in $S$ has $4$ elements, $|S|=24/4=6$.

how to find the number of subsets?


Is there a better way to determine the most trusted users in a bookstore database?

Question: I'm building a web portal for a bookstore.
I want to allow users to mark other users as "trusted" or "not-trusted".
I want to figure out who are our stores most trusted users by ordering on their overall trust level.
Here's an example to illustrate how this trust level is calculated:
We are going to calculate Bob's trust level...
Bob has been marked as "trusted" by 100 other users, and marked as "not trusted" by 20 users. Bob's trust level = 100 - 20 = 80.
I have the following table:
Judges(judgerLoginName: VARCHAR(45), judgedLoginName VARCHAR(45), trustLevel SMALLINT)
Now, currently I have a trustLevel of 0 representing "not-trusted" and 1 representing "trusted".
So, I'm thinking about changing all the 0's to -1's, so I could do a simple:
SELECT judgedLoginName, SUM(trustLevel)
FROM Judges
GROUP BY judgedLoginName,
ORDER BY SUM(trustLevel) DESC

However, I would like to know if there was an equally simple means to subtract countOfNotTrusted from countOfTrusted. What do you suggest? I'm quite new to database development and would appreciate any guidance.
Comment: A bit of a newbie myself, but what you're suggesting sounds fine to me
Comment: You might leave a threshold of say 3 votes __having count(*) > 3; __ and display *unknown* if there are no rows in result set.
Answer: SELECT judgedLoginName, SUM(IF(trustLevel = 0, -1, 1))
FROM Judges
GROUP BY judgedLoginName,
ORDER BY 2 DESC

Check if your trust level is 0, then the value that is added is -1
Added the order by 2 to order by the second column if you need to
Comment: `ORDER BY 2` sorts by column name 2.
Answer: SELECT judgedLoginName, -COUNT(*)+2*SUM(trustLevel)
FROM Judges
GROUP BY judgedLoginName,
ORDER BY 2 DESC

gives all users a value of -1 and adds the trusted ones +2, resulting in +1 for them.


C++ Sorting problem

Question: I want to create a sorting system, it gets some numbers and sort it DESC.
if I enter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 (orderly), that code works fine ..
but if enter that numbers, disorderly, it is broken down ..
my code is::
#include <iostream.h>
main () {
 int a[10], max, temp;
 for (int i=0; i<10; i++) {
    cout << "Enter number " << i+1 << ": ";
    cin >> a[i];
 }

 for (int j=0; j<10; j++) {
  for (int x=0; x<=j; x++) {
    if (a[j] > a[j+1]) {
     temp = a[j];
     a[j] = a[j+1];
     a[j+1] = temp;
    }
  }
 }

 cout << "Sort [DESC]: \n";
 for (int w=9; w>=0; w--) {
    cout << w << ". " << a[w] << "\n";
 }
 //cout << "Max: " << max;
}

Thanks a lot...
Comment: Use ``. There is no `` in the C++ standard and never was.
Comment: It's `int main()`. The implicit int is no longer valid in C++.
Comment: This looks very homework-ish. If so we should tag it as such...
Comment: Am I the only one who finds it very amusing that this algorithm only works for the expected output?
Comment: Looks like a [traditional bubble sort](http://mathbits.com/mathbits/compsci/arrays/bubble.htm) from here.
Comment: You know you don't need to do that right? Unless this is for learning purposes only.  http://www.cplusplus.com/reference/algorithm/sort/ http://www.cplusplus.com/reference/std/functional/greater/
Comment: @Axel: Well, there was never an `` in standard C++, but that doesn't mean it was not there in pre-standard C++.
Comment: @Billy ONeal: It works in my compiler .. I have an old compiler!! :D
Comment: @kikio: Just because it works on your compiler doesn't mean that it is good. There are plenty of free and extremely good compilers available (i.e. MSVC++, G++, CLang, etc.). There's no reason to continue to use antiquated compilers like Turbo C++ and friends.
Comment: @the_drow: Well... it is not the algorithm, but a bug in the implementation, take a look at the loop indices and the operations performed in the inner loop (that refer only to the outer loop control variable, with the inner loop variable never being used)
Comment: @DavidRodríguez-dribeas: Well, the amusing thing is that he mentions that it works when it does nothing. But you are correct :)
Answer:
I want to create a sorting system

Already done for you as part of the standard library:
http://codepad.org/VBAB0JBo
#include <algorithm>
#include <iostream>
#include <functional>

void PrintNumbers(int * myArray)
{
    std::copy(myArray, myArray + 10, std::ostream_iterator<int>(std::cout, ","));
    std::cout << std::endl;
}

int main()
{
    int myArray[10] = {1,2,3,4,5,6,7,8,9,10};
    //Sort ascending
    std::sort(myArray, myArray + 10);
    PrintNumbers(myArray);
    //Sort descending
    std::sort(myArray, myArray + 10, std::greater<int>());
    PrintNumbers(myArray);
    return 0;
}

Answer: You're accessing a[10] (through a[j+1]), which surely can't be correct. Naive bubble sort would usually look like this, for instance:
for(int i = NUMBER_OF_ELEMENTS - 1; i > 0; --i)
for(int t = 0; t < i; ++t)
{
    if(item [t] greater than [t+1])
    {
        swap item [t] with [t+1]
    }
}

Comment: Don't understand why `> 0` is your comparison -- typically it would be either comparing the left element with the right element, or it would be a strcmp style comparison function in which case you need `!= 0` not `> 0`.
Comment: @Billy: Changed that, it was just an example. In case of integers, it would be `item[t] > item[t+1]`, for strings it would be `strcmp(item[t], item[t+1]) > 0`, and so on.
Answer: if you are using C++ you can use STL std::vector instead of array and then use STL algorithm std::sort
Comment: `std::sort` is good advice. However, given that the array is stack allocated it's perfectly fine -- no reason to use a vector here.

C++ Sorting problem


The title of a particular node became part of the breadcrumbs of administration pages

Question: In the Claro theme, I have the System breadcrumb block in the Breadcrumb region. The breadcrumb shows Homepage > [Title for node 444] > Structure > [Administration page title] instead of Homepage > Structure > [Administration page title], where [Title for node 444] is the title for the node whose ID is 444, and [Administration page title] is the title for the shown administrative page.
Upgrading to Drupal 10.1.2 didn't solve the issue.
How can I remove the node title, which should not be there since the shown page is an administrative page not related to nodes nor to that node in particular?
Answer: I can reproduce this problem by assigning an admin alias
<code>/admin/structure
</code>
to a node. Then the title of the node is displayed in the breadcrumbs.
To solve this problem search for the alias in the alias table:
<code>/admin/config/search/path?search=admin
</code>
Delete the alias and clear the cache.
You might also want to check the admin menu for an entry pointing at the node.


Definition of opposite category

Question: I don't quite understand the definition of opposite category.  Wikipedia defines $\mathcal{C}^\text{op}$ to be the category formed by 'reversing' morphisms. So for instance, in Grps, given a groups $G,H$ and a homomorphism $f: G \to H$, what does reversing $f$ mean?  Do we reverse $f$ into a homomorphism $H \to G$?
Answer: If $C$ is a category, we want to construct a new category $C^{op}$. To do so, we need to describe its objects, the set of morphisms between each of its objects and its composition rule $\circ_{C^{op}}$.

The objects of $C^{op}$ are just the objects of $C$.
If $a$ and $b$ are two objects of $C^{op}$,  then the set $\hom_{C^{op}}(a,b)$ is defined to be $\hom_C(b,a)$. Notice that this makes sense, for $a$ and $b$ are objects of $C$, so it makes sense to talk about $\hom_C(b,a)$.
If $a$, $b$ and $c$ are three objects of $C^{op}$ and $f\in\hom_{C^{op}}(a,b)$ and $g\in\hom_{C^{op}}(b,c)$, then the above definition means that $f\in\hom_C(b,a)$ and $g\in\hom_C(c,b)$, so it makes sense to compute the composition $f\circ_C g$ in $C$, which gives an element of $\hom_C(c,a)$. This last set is, by definition $\hom_{C^{op}}(a,c)$. We define the composition of $C^{op}$ so that $$g\circ_{C^{op}}f:= f\circ_Cg.$$

Let us give a concrete example. Suppose $C$ is the category which has exactly two objects, which are called $a$ and $b$ and three morphisms in all: the two identities and one morphism $f:a\to b$. Then $C^{op}$ has again $\{a,b\}$ as set of objects, and has exactly three morphisms: the two identities and one morphism from $b$ to $a$, which is $f$.
A slightly less silly example is the following: suppose $C$ is a category which has exactly one object, which I will call $x$. Then the set $\hom_C(x,x)$ is a set endowed with an associative multiplication admitting an identity element: it is what one calls a monoid. The opposite category $C^{op}$ has, again, exactly one object, which is still $x$, and has a monoid $\hom_{C^{op}}(x,x)$. Can you describe this monoid in terms of $\hom_C(x,x)$?
Comment: This construction is purely formal, and as such it has very little importance, really... Its role is to allow us to speak of contravariant functors and covariant functors uniformly, which is not that important.
Comment: Well in $C^{op}$, the the morphisms $hom_{C^{op}}(x, x)$ are exactly the morphisms $hom_C(x, x,)$, but in $C^{op}$ $f \circ g$ is defined to be $g \circ f$ in $C$.  Does that sound right?
Comment: The construction is more than just a formality. Non-commutative geometry for instance is defined as the study of an opposite category. Pontrajyn duality is the establishment of an equivalence between the opposite of a category and a familiar category. So is Stone duality. The fact that the opposite of the category of sets is equivalent to the category of complete atomic boolean algebras is also an interesting example of duality. So, the opposite construction is very simple and useful, but it hides some interesting subtleties.
Comment: Perhaps it's worth giving some example where such a construction is interesting, so that OP faster catches its importance?
Comment: Ok, that's good to know - thanks
Comment: @IttayWeiss, the "study of the opposite category" is just the study of the actual category: there is no content in doing that.
Comment: @MarianoSuárez-Alvarez there is content in understanding the opposite category in terms of more familiar categories. I think the examples I gave illustrate this.
Comment: Would you say that there is some content in the construction of the opposite ring of a ring?
Comment: How can we know that there exists a morphism from $b\rightarrow a$?

Definition of opposite category


Learning path advices

Question: I played guitar for a while 10 years ago, but I never learned music.
I was only playing the songs that I wanted to play by following YouTube videos.
I know I have to learn music to be able to improvise on blues and jazz tracks. That's why I need learn a lot of things. But I don't wanna get lost so I need an advice to build my own learning path.
What I've done so far:
I understand logic behind the CAGED, Circle of Fifths and intervals.
I can play C Major scale, C Maj and C Maj7 arpeggios and C chords all over the keyboard.
So what is next? Should I do these for other notes? (A G E D F B)
Also I can play a few minor pentatonic scales. But I don't know how to use them.
When I play I IV V (let's say A7 D7 E7), I can play these minor pentatonics but when I try to improvise solo over these chord changes, it doesn't sounds like blues. Because I don't know how to connect them. Or maybe I shouldn't try improvisations for a while and just focus the scales.
I don't wanna give up this time. So any advice would be helpful and keeps my motivation up.
Thanks in advance.
Answer: There have been, and will be, many many great Blues players who haven't 'learned music' - whatever that is. It could mean learning to read music, in which case, it's true! It could mean understanding what music does and how it works, in which case it may very well not be true!
Jazz can be a very different beast, with many more chords coming out to play, so having a fair bit of musical knowledge helps a lot here.
You've made a good start, knowing shapes of both chords, arpeggios and scales over the neck. Contnue with this, in other keys - A, D, E and G are good keys that are common in Blues. Add the flat 5 to your minor pents, and there's the minor Blues - maybe that missing note is the one that stops your solos sounding Blues-like?
Listen to those who can influence your playing. Try copying what they do. For now, in your Blues playing, try to play phrases which start on the root note of the chord at the time: in Blues in key A, play an A note in the A bars, D in the D bars, E in the E bars, as a start point. That sort of 'sets the scene' for mapping out what you play - at least you're with the backing all the time, rather than random widdling!
Comment: Thank you Tim, I'll keep working on other keys and definitely add the blue note to scale. As I learn new keys I will try to put them together.
Comment: I have one more question: Which one is the most efficient way: Learning all Majors then all minors? Or learning key by key(for example: C major and C minor, then A major and A minor)
Comment: Since there are only several 'patterns' for major, minor, and pent. scales, I don't see a problem. If you've learned, say, C major scale, two octaves across the strings, you're hardly going to have to learn C♯, D, E♭, E, as all you do is play one fret higher, same pattern, for each. Unless you only know with open strings, in which case, re-learn one - C, the move up a fret at a time, same pattern, for the others.
Answer: "I know I have to learn music to be able to improvise on blues and jazz tracks."
This is simply not true.  What you need to do is really like these musical forms, listen to a lot of "Blues" and "Jazz" and play what you like, just as you have been.
If you want to know how scales, and modes, and "connected" to chords and progressions then listen, listen, listen.  Trying to learn music theory may produce more of a misunderstanding than an understanding.  Theory does not produce creativity and music theory is descriptive, not predictive.  It can help explain why certain things work, but there are lots of other things that work that do not fit into theory.
Step one is listen and try to learn a song or two from TAB, or a video.  Then, once you have some idea of what you like start trying to learn the theory behind it.
As for doing the same things in different keys, this has marginal value for a guitarist since the patterns are all the same, just shifted.  It is worth your effort to learn to play in all 12 keys in the same position since the patterns will be different.
Learning the "modes" can be cool, it is valuable info but again, it kind of puts the cart before the horse from a creative point of view.  At the end of the day the 7 diatonic modes are all related to the Major scale so when one improvises it is not likely that they are thinking "I should be in Mixolydian right now for 2 beats then move to the relative Phrygian for one beat..." this will cripple the mind.  Rather, learn some riffs that you think are cool and try putting them into a tune, over chords with a backing track etc.  In this manner you are learning the language and being creative.  This is an approach described by Jerry Cocker and Kenny Werner.
If you don't love the music you are playing it will show.
Comment: Definitely by ear. That way, one gets to listen properrly. Tab merely lets people play 'what they're told. So many students have learned using tab, and learned it *wrong*. Because so much tab is %*&".
Comment: Nice answer, apart from 'learn from tab' - I think you know my thoughts on that...
Comment: I know but to be honest it doesn't matter how the data gets in the system.   By ear is the preferred method.  Im just trying to help the person get data.
Answer: I presume you are looking for different ideas and perspectives about learning music and will state the old saying that "there is more than one way to skin a cat". You will have success at learning about music no matter which direction you approach it from, but you won't learn anything if you don't make the approach. Some folks learn from books, others learn from friends, others learn in school, others learn by joining in jam sessions or bands and moving forward from there. Association and participation with other musicians has always been a very useful learning tool in my own experience. I've learned things from others without either one of us realizing the learning was taking place, it felt more like social interaction, and it felt good enough to keep me going forward. Each of us has our own best way to learn music and everything we learn helps to determine our personal style. Our interests and taste help determine the questions we seek answers for, so awareness of what trips our trigger is important. But the most important thing to know is that you have the interest and desire to learn and start looking for answers to each individual question as it appears in the learning process. It's a lot of work and a lot of play, some frustration and plenty of satisfaction. Do your best to enjoy the whole process.

Learning path advices


Using Multiple GTR, LEQ, etc "if" statements in Batch

Question: I have a batch file that asks the user to input a specific number. If the number is in between a given set of numbers, it goes to that label. However, say the user puts 100 it goes right to :smallsip
All in all, I'm trying to make it so that if the user types a number within a specific range (I.E 30-99) it goes to a specific label. Any suggestions?
:getadrink
cls
echo How many sips will Jackie Chan drink?

set /p numberofsips=Type Number of Sips Here:

if %numberofsips% LSS 0 goto waitwhat
if %numberofsips% GEQ 1 goto smallsip
if %numberofsips% GEQ 10 goto plenty
if %numberofsips% GEQ 30 goto toomuch
if %numberofsips% GEQ 100 goto waytoomuch

:waitwhat
cls
echo what
pause
:smallsip
cls
echo small sips
pause
:plenty
cls
echo plenty
pause
:toomuch
cls
echo too much!
pause
:waytoomuch
cls
echo WAY TOO MUCH
pause

P.S. I've been lurking around numerous posts on here, getting help for something I'm creating with Batch. Yes, I know batch is outdated, but I just seem to like it as I have discovered it about 2 months ago.
Answer: The if statements in your code work correctly, but your logic is wrong. For instance, when you type a number 50, the condition %numberofsips% GEQ 1 is already met, so the following if statements will never be reached. To solve this, simply reverse their order.
Another problem is, that you fall into fall into code which you do not want to be executed. For example, when the portion :smallsip has finished (and you confirmed the pause), execution continues at :plenty unintentionally. To avoid that, you will need a goto to jump somewhere else or an exit /B to leave the batch script.
Here is a fixed code:
:getadrink
cls
echo How many sips will Jackie Chan drink?

:askforsips
set numberofsips=0
set /p numberofsips=Type Number of Sips Here:

if %numberofsips% GEQ 100 goto waytoomuch
if %numberofsips% GEQ 30 goto toomuch
if %numberofsips% GEQ 10 goto plenty
if %numberofsips% GEQ 1 goto smallsip
goto waitwhat

:waitwhat
cls
echo what?
pause
goto askforsips
:smallsip
cls
echo small sips
pause
exit /B
:plenty
cls
echo plenty
pause
exit /B
:toomuch
cls
echo too much!
pause
goto askforsips
:waytoomuch
cls
echo WAY TOO MUCH
pause
goto askforsips

These are the things that I changed:

the order of if queries is reversed;
the if %numberofsips% LSS 0 query is removed, so :waitwhat is executed if the entered value is zero or less; in your code, :waitwhat was also executed in case the value was zero as none of the conditions were met; the final (lonely) goto waitwhat is not required here, but it is more obvious what happens;
a new label :askforsips is introduced to allow another user input in case an invalid value (zero or less) was given;
variable numberofsips is now reset before the user prompt, because set /P keeps the former value if the user just presses ENTER;
every section from :waitwhat down to :waytoomuch is terminated explicitly, either by goto askforsips or by exit /B;
Comment: Thank you so much! I'll test it when I get home. It's for a batch game I'm making called "Jackie Chan Goes to School" I won't go into details why, but it's from a part where Jackie Chan sees a water fountain, and drinking too much makes him sick. It's stupid, I know, but you get the point. Again, I'll test it when I get home. :)


How would I assign the optimal weight matrix to combine the following moment conditions in MM?

Question: The following information is given: Based on a sample x(n), with n = 1,..., 100 from the exponential distribution, we want to estimate lambda but the original data was lost; we only know that 38 observations are >= 1 and 11 observations are >= 2. Combining the information based on the 38 greater than or equal to 1 and the 11 greater than or equal to 2, what is the optimal weight matrix to combine the two moment conditions?
Comment: We welcome questions like this, @Jamie, but we treat them differently. Please tell us what you understand thus far, what you've tried & where you are stuck, & we'll try to provide hints to get you unstuck. To better understand the process, you should read the wiki for the `[self-study]` tag.
Answer: If $x \sim \exp(\lambda)$, as in $f(x) = \lambda^{-1} \exp( -x/\lambda)$, define $x_1 = 1[x\ge1]$ and $x_2=1[x\ge2]$ where $1[\cdot]$ is the 0/1 indicator of the event in brackets. They are obviously correlated as $x_2=1$ implies $x_1=1$, although not vice versa. You are given the sample means of these variables. Compute their variances and covariances as a function of $\lambda$, and invert the matrix to get the weight matrix you need.
In this problem, you arrive at the continuous updating version of the GMM estimator in which the weight matrix explicitly depends on the unknown parameter. This is kinda cute.


Ativando evento a partir de checkbox

Question: Eu tentei fazer o checkbox para mudar um input de hidden para text, mas não sei no que estou errando.

function myFunction() {

    const selecionado = document.querySelector("#quant");
    var checkBox = document.getElementById("ch_quant");

    var input = document.getElementById("quant").type = 'hidden';

    if (checkBox.checked == true){
       document.getElementById("quant").type = 'text'
    }
    else {
        document.getElementById("quant").type = 'hidden'
    }
}

  Marque P/ Informar Estoque
  <input type="checkbox" id="ch_quant" name="ch_quant" required>
  <input type="hidden" id="quant" name="quant">

Comment: Onde chamas essa função `myFunction`?
Comment: falou tudo não esta em nenhum lugar, teria como me mostrar como ficaria correto pois sou estudante então sou bem novato.
Comment: Sua pergunta tem resposta neste tópico: https://pt.stackoverflow.com/questions/5563/como-verificar-com-jquery-se-existe-um-checkbox-checado usando jQuery.
Answer: Primeiro de tudo você deve chamar a função que criou quando houver alteração no checkbox com o onchange="myFunction(this)".
Segundo, com o this você passa por parâmetro da função o próprio input (<input type="checkbox" id="ch_quant" name="ch_quant" onchange="myFunction(this)" required>).
Depois disso é só verificar se está marcado ou não, assim como você já tinha feito.

function myFunction(checkbox) {

  if (checkbox.checked)
    document.getElementById("quant").type = 'text'
  else
    document.getElementById("quant").type = 'hidden'

}

  Marque P/ Informar Estoque
  <input type="checkbox" id="ch_quant" name="ch_quant" onchange="myFunction(this)" required>
  <input type="hidden" id="quant" name="quant">

Comment: Acho que vc quis dizer "com o `this` você passa por parâmetro da função o próprio **checkbox**" (não "o próprio input"). Outro detalhe é que vc pode simplesmente fazer `if (checkbox.checked)` - comparar um valor booleano com `== true` é redundante
Comment: O **checkbox** não é o **input**? Acho que sim, veja: `<input type="checkbox"...`
Comment: @Natan O hidden/text também é input, então acho que ficaria mais claro dizer qual dos inputs está sendo passado :) Foi isso que eu quis dizer. Desculpe se meu comentário ficou confuso
Comment: @hkotsubo exatamente, é o `input type="checkbox"` que é passado, poderia estar mais claro kk. Apesar de que está explicito que passa o
 `próprio input`

Ativando evento a partir de checkbox


Determine for which value of x the infinite series converges

Question: $$\sum_{n=1}^\infty\frac{\sqrt{\vphantom{A^b}n+1}-\sqrt{n}}{n^x}$$
I multiplied by the conjugate and was able to simplify this to
$$\sum_{n=1}^\infty\frac{1}{n^x(\sqrt{\vphantom{A^b}n+1}+\sqrt{n})}$$
so the series will converge, as the values go to zero as $n$ goes to $\infty$. However, I can't figure out for which $x$ it converges. I want to say it's for all $x>0$, but I'm not sure how to justify this.
Any help appreciated!
Comment: if the values goes to $0$ that does not implies the series converges.
Answer: Hint: Your rewriting is indeed very useful. By limit comparison or just plain comparison, your series converges iff $\sum \frac{1}{n^{x+1/2}}$ converges. Now use known results about $p$-series. The conclusion should be that we have convergence if and only if $x\gt 1/2$.
Answer: If $\;x>\frac12\iff x=\frac12+\epsilon\,,\,\,\epsilon>0\;$ :
$$\frac1{n^x\left(\sqrt{n+1}+\sqrt n\right)}=\frac1{n^{1/2+\epsilon}\left(\sqrt{n+1}+\sqrt n\right)}\le\frac1{n^{1/2+\epsilon}\sqrt n}=\frac1{n^{1+\epsilon}}$$
and we have convergence by comparison.
If $\;x<\frac12\;$
$$\frac1{n^x\left(\sqrt{n+1}+\sqrt n\right)}\ge\frac1{n^{1/2}\left(\sqrt{n+1}+\sqrt n\right)}\ge\frac1{2n^{1/2}(n+1)^{1/2}}\ge\frac12\frac1{\sqrt{n+1}}$$
and the series diverges, again by comparison.


Issues with ridge regression

Question: I am running ridge regression on some data using a series of regularization params from 0.0001 to 1000. I was amazed to see that high values of lambda param 500-1000 is giving better results with cross validation.
Is it possible to get better results on such high lambda values?
Answer: Yes, it is possible. The order of lambda value depends on the difference between scales of residuals and coefficients. You have observed high lambda becouse your residuals are large when compared with beta coefficients. To make lambda independent of scales you should standardize your response and covariates.
Comment: So do I need to scale them within the range of [0 1] or zero mean unit variance is enough. I tried to standardize the inputs and outputs to have zero mean and unit variance but still it is not good enough. I still get very high value for $\lambda$
Comment: centering your data and standardizing to unit variance is fine. This is actually how the `penalize` and `glmnet` packages in R standardize. Another option is to standardize to unit norm, which is often recommended for Lasso regression (which are similar to ridge regression).
Comment: Zero mean and unit variance should be preferred. If this still has no effect, then something goes wrong. The covariates may be completely irrelevant, or your cross-validation code contain a bug, or something else. It would be useful to see your beta's, mean squared errors and cross-validation mean squared errors for non-standardized and standardized models.

Issues with ridge regression


insertdict_clean: Assertion error

Question: I get the following error in python 2.6.6:
python: Objects/dictobject.c:501: insertdict_clean: Assertion 'ep->me_value == ((void *)0)' failed.

Following is the distilled source:
pool = multiprocessing.Pool(32)
mutation_counts = pool.map(mutate, enumerate(data))
mutation_count = reduce(lambda a, b: a + b, mutation_counts)
args = [(interval, mutation_count) for interval in sub_intervals]
pool_results = pool.map(validate, enumerate(args)) # Issue occurs here

I suspect mutation_count is causing the issue, it is a counter defined by:
from operator import itemgetter
from heapq import nlargest
from itertools import repeat, ifilter

class Counter(dict):
    '''Dict subclass for counting hashable objects.  Sometimes called a bag
    or multiset.  Elements are stored as dictionary keys and their counts
    are stored as dictionary values.

    >>> Counter('zyzygy')
    Counter({'y': 3, 'z': 2, 'g': 1})

    '''

    def __init__(self, iterable=None, **kwds):
        '''Create a new, empty Counter object.  And if given, count elements
        from an input iterable.  Or, initialize the count from another mapping
        of elements to their counts.

        >>> c = Counter()                           # a new, empty counter
        >>> c = Counter('gallahad')                 # a new counter from an iterable
        >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
        >>> c = Counter(a=4, b=2)                   # a new counter from keyword args

        '''
        self.update(iterable, **kwds)

    def __missing__(self, key):
        return 0

    def most_common(self, n=None):
        '''List the n most common elements and their counts from the most
        common to the least.  If n is None, then list all element counts.

        >>> Counter('abracadabra').most_common(3)
        [('a', 5), ('r', 2), ('b', 2)]

        '''
        if n is None:
            return sorted(self.iteritems(), key=itemgetter(1), reverse=True)
        return nlargest(n, self.iteritems(), key=itemgetter(1))

    def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        If an element's count has been set to zero or is a negative number,
        elements() will ignore it.

        '''
        for elem, count in self.iteritems():
            for _ in repeat(None, count):
                yield elem

    # Override dict methods where the meaning changes for Counter objects.

    @classmethod
    def fromkeys(cls, iterable, v=None):
        raise NotImplementedError(
            'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')

    def update(self, iterable=None, **kwds):
        '''Like dict.update() but add counts instead of replacing them.

        Source can be an iterable, a dictionary, or another Counter instance.

        >>> c = Counter('which')
        >>> c.update('witch')           # add elements from another iterable
        >>> d = Counter('watch')
        >>> c.update(d)                 # add elements from another counter
        >>> c['h']                      # four 'h' in which, witch, and watch
        4

        '''
        if iterable is not None:
            if hasattr(iterable, 'iteritems'):
                if self:
                    self_get = self.get
                    for elem, count in iterable.iteritems():
                        self[elem] = self_get(elem, 0) + count
                else:
                    dict.update(self, iterable) # fast path when counter is empty
            else:
                self_get = self.get
                for elem in iterable:
                    self[elem] = self_get(elem, 0) + 1
        if kwds:
            self.update(kwds)

    def copy(self):
        'Like dict.copy() but returns a Counter instance instead of a dict.'
        return Counter(self)

    def __delitem__(self, elem):
        'Like dict.__delitem__() but does not raise KeyError for missing values.'
        if elem in self:
            dict.__delitem__(self, elem)

    def __repr__(self):
        if not self:
            return '%s()' % self.__class__.__name__
        items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
        return '%s({%s})' % (self.__class__.__name__, items)

    # Multiset-style mathematical operations discussed in:
    #       Knuth TAOCP Volume II section 4.6.3 exercise 19
    #       and at http://en.wikipedia.org/wiki/Multiset
    #
    # Outputs guaranteed to only include positive counts.
    #
    # To strip negative and zero counts, add-in an empty counter:
    #       c += Counter()

    def __add__(self, other):
        '''Add counts from two counters.

        >>> Counter('abbb') + Counter('bcc')
        Counter({'b': 4, 'c': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem in set(self) | set(other):
            newcount = self[elem] + other[elem]
            if newcount > 0:
                result[elem] = newcount
        return result

    def __sub__(self, other):
        ''' Subtract count, but keep only results with positive counts.

        >>> Counter('abbbc') - Counter('bccd')
        Counter({'b': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem in set(self) | set(other):
            newcount = self[elem] - other[elem]
            if newcount > 0:
                result[elem] = newcount
        return result

    def __or__(self, other):
        '''Union is the maximum of value in either of the input counters.

        >>> Counter('abbb') | Counter('bcc')
        Counter({'b': 3, 'c': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        _max = max
        result = Counter()
        for elem in set(self) | set(other):
            newcount = _max(self[elem], other[elem])
            if newcount > 0:
                result[elem] = newcount
        return result

    def __and__(self, other):
        ''' Intersection is the minimum of corresponding counts.

        >>> Counter('abbb') & Counter('bcc')
        Counter({'b': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        _min = min
        result = Counter()
        if len(self) < len(other):
            self, other = other, self
        for elem in ifilter(self.__contains__, other):
            newcount = _min(self[elem], other[elem])
            if newcount > 0:
                result[elem] = newcount
        return result

if __name__ == '__main__':
    import doctest
    print doctest.testmod()

I only see this issue when I have approx 1M keys and occurs in about 20% of runs.
Comment: Unfortunately Python 2.6.6 is out of maintenance, so you really should upgrade your Python interpreter if you possibly can. Even an upgrade to 2.6.9 might be worth considering.
Comment: Thanks for the suggestion, but if I were able to upgrade I would use colletions.Counter in 2.7.
Answer: If you go to the dictobject.c source (on Python trunk, I did not bother to look for 2.6), you can read that the function insertdict_clean is an

Internal routine used by dictresize() to insert an item which is known to be absent from the dict.  This routine also assumes that the dict contains no deleted entries.

What the exception is telling you is that the assert(ep->me_value == NULL);, on line 574 in the current trunk, is actually finding an element in the dictionary, when it should be missing. Probably, you are hitting this line because you subclassed Python's built-in dict, instead of holding a dict within your Counter class.
I would suspect the implementation of the __missing__ magic method. It returns a 0 instead of a None. Also, why don't you use the collections.Counter class? It is already in Python 2.6.
Comment: From the docs: http://docs.python.org/2/library/collections.html, counter was added in 2.7, otherwise I would have. I am unable to upgrade, it must be compatible with RHEL 6.

I will try reimplement the counter having a dict instead of inheriting from one.
Comment: You are right, sorry :) I just looked at the whole module, which is available from Python 2.4
Comment: Also, if the reason why you can't upgrade to python 2.7 is the dependency in RHEL 6 of `yum` on python2.6, you can perform an `altinstall` (alternative install) from source, as described [in this other question](http://stackoverflow.com/questions/4149361/on-linux-suse-or-redhat-how-do-i-load-python-2-7)
Comment: So oddly removing unused methods in Counter seems to have resolved the issue... But I chose not to stop there and not inherit from dict, which also seems to resolve the issue. Still testing but will give you the check now.

insertdict_clean: Assertion error


How do I configure git to use a folder on another network?

Question: I have a local git repository with two folders running on my windows machine. One of the folders has .net code, the other has php code.
What I'd like to do is have the php code stored on a Ubuntu installation I have running on VirtualBox and git would use that instead of the windows directory.
How would I go about setting that up? I tried to create a shortcut to the ubuntu folder but git didn't want to follow it.
Answer: Ideally, you install git on your Ubuntu guest, and activate git daemon.
That will allow you to push your repo from the Windows host to your Ubuntu guest.
Then, one solution would be to plit your repo in two repos, that you can keep joined in one global repo through submodules.
That would allow you to push only the one with php content to your Ubuntu.
Or, simpler: you push everything, and have a post-receive hook deploying your php code where you need it.
Comment: I definitely broke them up into two repos. Submodules looks like the way to go if i want to keep everything together with a "super" repo. Thanks for the answer Von.


If $x = e^t$, than what is the partial with respect to $\dot{x}$ of $\dot{x}^2-x$?

Question: The Motivation:
I am learning the basics of Lagrangian mechanics. The usual example of using Lagrangian mechanics is to find the equation of motion of a pendulum. Since this forum is about math and not physics, I will simply write down the expression which is confusing me.
The Lagrangian ($\mathcal{L}$) is
$$\mathcal{L} = \frac{m}{2}\left(l\frac{d{\theta}}{dt}\right)^2 - mgl(1-\cos(\theta))$$
(Where $m$ is the mass of the bob and $l$ is the length of the string.) The issue is when I try to find the quantity $\frac{\delta\mathcal{L}}{\delta \theta}$: the solution simply means treating $\dot{\theta}$ as a variable independent of $\theta$, even though since they are both functions of $t$ we can write down a relationship between the two.
The Problem:
So there's no point in making the algebra messy, so let's use an easier example. Let's pretend
$\mathcal{L} = \dot{x}^2 - x$
and furthermore, let's pretend $x=e^t$.
This is a problem! Obviously, in this special case, $x=\dot{x}$, so wouldn't $\frac{\delta\mathcal{L}}{\delta\dot{x}}=2\dot{x}-1$? Apparently, $\frac{\delta\mathcal{L}}{\delta\dot{x}}$ is actually $2\dot{x}$.
We could also give a different example. Now, let's use the same $\mathcal{L}$, but let $x=e^{7t}$. In this slightly different case, $x=\frac{1}{7}\dot{x}$, so shouldn't $\frac{\delta\mathcal{L}}{\delta\dot{x}}=2\dot{x}-\frac{1}{7}$? Once again, apparently, $\frac{\delta\mathcal{L}}{\delta\dot{x}}$ is actually $2\dot{x}$.
The Question:
The reason I brought up the motivation for this problem is just in case the math is special for the case of Lagrangian mechanics (which I wouldn't expect).
Otherwise, why is it that when we take the partial of $\mathcal{L}$ with respect to $\dot{x}$, we can, with impunity, ignore the implicit relation between $\dot{x}$ and $x$ and just treat $\dot{x}$ as a variable completely independent of $x$?
Comment: You are not taking a total derivative. So you can ignore such relationships.
Comment: This is a hard thing for people to get past initially. But before solving the Euler-Lagrange equation you take $\dot{x}$ and x to be independent. So for your "problem" $\frac{\partial \mathcal{L}}{\partial \dot{x}}=2\dot{x}$
Answer: The Lagrangian is a function that takes in functions $x(t)$ and $\dot{x}(t)$ and outputs a function $L(x,\dot{x})(t)$. The arguments in the Lagrangian, $x$ and $\dot{x}$, are treated as independent variables when working out derivatives. Thus we always have $\frac{\partial \dot{x}}{\partial x} = 0$ and $\frac{\partial x}{\partial \dot{x}} = 0$. Many authors use a different name for $\dot{x}$ like $p=\dot{x}$ to avoid this confusion (which is very common). In practice $L(x,\dot{x})$ can be treated as a normal function in two variables when working out the derivatives. Thus for your example $\frac{\partial L}{\partial x} = -1$ and $\frac{\partial L}{\partial \dot{x}}=2\dot{x}$.
It does not make sense to substitute in a function $x(t)$ in the Lagrangian and then asking what the derivatives $\frac{\partial L}{\partial x},\frac{\partial L}{\partial \dot{x}}$ are. If you substitute in a function like $x(t) = e^{t}$ you are left with a normal function and the functional information about how the Lagrangian looks like is lost.
Comment: Hmm, this does answer the question. I certainly will need to learn more to fully understand, but for now I am okay. And just to confirm, the notation for a functional derivative is "partial with respect to this function", as opposed to "partial with respect to this variable", right?
Comment: @Mahkoe Yes that is a good way to state it. Also for normal Lagrangian Mechanics one does not really need the functional derivative concept as long you remember that $x$ and $\dot{x}$ are independent variables.
Comment: I disagree that the Lagrangian is a functional; the action is a functional...
Comment: @JLA I think I was thinking about the action when writing this. I changed the wording of the answer. Thanks.
Answer: It's been a while since I asked this, but I stumbled onto something that is conceptually helpful.
Imagine $x(t)$ takes a particle from point $a$ to point $b$. Pretend that the time it takes to go from $a$ to $b$ is 10 seconds and that it travels in a straight line. However, it might travel at a constant speed, or it might start out really fast and go slowly the rest of the way.
So now it is conceptually easy to accept that $x(t)$ and $\dot{x}(t)$ are like independent variables in the Lagrangian.
Comment: I don't think this is correct. If the speed changes, then the position is a different function of time. $x(5) = \frac{a+b}{2}$ if the speed is constant, but not if it's variable. $x$ and $\dot x$ are not independent.
Comment: I think part of the problem is conflation of functions with variables: if variables $x$ and $y$ are related by $y=f(x)$, that doesn't mean that $y$ _is_ the function $f$; the same variable could be a different function of another variable, like $y=f(x)=g(z)$. In your example, the same curve is traced by different parametrizations.


Are there two definitions of the word bias?

Question: I hear the term bias being thrown around a lot in statistical literature.
For example,

By using mean-wise imputation, we are adding bias to our estimate.

Another example,

The bias-variance trade-off is an important subject when picking models.

Are these the same "bias"?
Comment: @StatsStudent those are not definitions of it's *statistical* meaning
Comment: There are actually 12 definitions:  http://www.dictionary.com/browse/bias?s=t
Comment: But when you hear "bias," even in the statistical literature, it does not necessarily have a statistical meaning...
Answer: The term "bias" has a specific definition in the statistical literature (the difference between the expected value of an estimator and the thing being estimated), but that isn't to say it loses its original, more general meaning.  Which one is intended will depend on context, and oftentimes you will have a mixture of the two.
I would say the first usage is in general the less precise kind, as data imputation is a method that's used in applied problems where one need not assume that any true value of the parameter even exists.  Here it's basically synonymous with "shrunk towards zero."
As far as the second usage is concerned the term bias-variance trade-off does originally derive from the more formal definition of bias, but nonetheless I would still say this refers more to the general "inflexibility" of a model fitting procedure, and not necessarily the question of whether or not an estimated regression function is correct on average.
Comment: Hm - for the first one: the whole point of mean-wise imputation is to maintain the mean of the original sample. Hence both parameters should be the same - so it has no bias.\
Comment: I'm fairly sure they're talking about the bias of the coefficient estimate and not the bias of the sample mean.  Also, the sample mean need not be unbiased when you have missing data.
Answer: I agree that this terminology is confusing.  Bias has one meaning in both of these contexts: distance from ideal or target values, but the interpretation depends on which space we are talking about.  I'll explain what I mean with regard to the two quotes in your question.

By using mean-wise imputation, we are adding bias to our estimate.

This refers to bias in the data space.  Mean-wise imputation influences the position of your estimates relative to the target values.

The bias-variance trade-off is an important subject when picking models.

This refers to bias and variance in the parameter space of models.  That is, if you trained a stochastic model 1000 times, you could observe bias or variance of the parameter values.  A high bias model has consistent parameters, but they differ from an 'optimal' solution.  A high variance model will get different values for the parameters each time it's trained.


NTP Server in Network Switch

Question: Is it possible to set up a Switch to acts an NTP Server for the devices connected to its VLAN ?
If so ,how can I implement it my HP Switch A3600 JG299A.
I want to do this because I do not have external NTP Time Source for proper time synchronization.
Comment: What does the documentation for this switch say ?
Answer: Yes, this switch can act as an NTP server.
There are different ways to set it up, namely client/server, symmetric peers, multicast and broadcast modes. Most often you will likely set it up in a client/server mode. For this to work you  need to set up NTP synchronization on the switch itself and then it can act as a server for other devices on your LAN.
For more information look for 3600 v2 Switch Series Network Management and Monitoring Configuration Guide on HP website. This document has a section explaining NTP configuration.
Answer: After setting up your switch to some source and filtering traffic by VLAN which is why I'm assuming that your servers don't have external access. Then just set your DC (If you are running a Windows domain controller) which if needed you can check out this article to set it up quickly: http://www.1337admin.org/windows-server/windows-server-2012-r2/set-domain-controller-to-use-external-ntp-time-source/ and when using the flag /manualpeerlist set it to the IP of the switch that it can access on it's VLAN.

NTP Server in Network Switch


Visual Studio 2005 Quick find missing Search in solution

Question: If I open a solution then press CTRL + F and select Quick Find, the Look in drop-down doesn't have "Entire solution" as an option (Find in files still has it).
Any idea how to fix this?
Thanks!
Answer: According to a response on Experts exchange(a community where experts in .Net answer), that option is missing in VS2005 pre-SP1. Install SP1 and it should be there.


Why does the Title in my UIButton misalign vertically in iOS8?

Question: I have a UIButton created in a Storyboard. It has no special constraints / insets or anything. The only changes in code to it are :
<code>[btn setBackgroundImage: [UIImage imageNamed:@"SomeImage"]];
[btn setTitle:@"Done"];
</code>

However, the button seems to be middled up whenever I use it in Autolayout :

The only way I could get it back was when I changed the background image to something else, like in :

So there seems to be something rather messed up with the Background image. However, I don't get why it doesn't work badly in pre-iOS8 then. Also, when I changed the insets :
<code>self.closeButton.contentEdgeInsets = UIEdgeInsetsMake(-15.0, 0.0, 0.0, 0.0);
</code>
Then I got the content inside the Button again. But now, the iOS-7 button was misaligned. Can someone help me out over here?
Comment: How big is your background image? Try setting the background image and name in the storyboard instead of in code.
Comment: It is double the size of the button.
Answer: This is an iOS bug, fixed in iOS 8.1


Constantes de tipos não primitivos

Question: Em Java, constantes são declaradas com a sequências das keywords static e final.
Quando temos public static final int UM = 1; "faz sentido" chamar de constante, uma vez que seu valor não pode ser alterado.
Agora, falando de tipos não primitivos, ainda "faz sentido" chamar de constante, uma vez que seus atributos podem ser alterados através de métodos?
A única coisa que fica constante é a referência, não os valores dos atributos.

Até hoje não precisei criar uma constante de tipo não primitivo (confesso que não via sentido para isso), mas vendo esse código no GitHub me veio a dúvida.
Comment: Eu sei, mas após ler essa, me pareceu a mesma duvida perguntada em outro cenario.
Comment: Meio duplicata: [Por que as constantes da classe File não seguem a convenção de constantes?](https://pt.stackoverflow.com/q/219206/28595)
Comment: @Articuno não é. Fui eu mesmo quem fez essa pergunta
Answer: Não.
O Maniero colocou uma resposta que explica os motivos técnicos para isso. Vou colocar aqui os motivos pelos quais o que o autor do código fez é errado.
O trecho relevante do código mencionado é esse:
private static final Random RANDOM = new Random();

A palavra-chave final garante que quem contém um valor ou referência não poderá mudá-lo após a inicialização - mas isso é desnecessário nesse caso, pois o campo acima já é privado. O autor do código só está protegendo seu código contra o próprio autor. Por ser privado, o campo só poderia ser alterado por método da própria classe (o que é uma decisão de quem for manter o código), ou por reflexão (que é o cheat supremo de qualquer forma).
Isso parece mais excesso de engenharia, provavelmente fruto de comportamento condicionado. Isso ocorre, por exemplo, quando ouvimos coisas na faculdade como "sempre declare algo assim", "sempre use esse padrão" etc. e não questionamos o motivo.

Quanto a dúvida original, se o objeto seria uma verdadeira constante, visto que seus membros ainda poderiam ser alterados... Como o Maniero falou, talvez o desejo seja se ter algo imutável. Não me parece ser o objetivo do código relevante para a pergunta, pois o que o código se propõe a fazer é dar uma caixa-preta para a geração de números (pseudo-)aleatórios. De qualquer forma, o objeto RANDOM irá alterar seu estado interno a cada número obtido.
E finalmente, falando de uma forma conceitual... Se você tem um objeto constante e estático que possui membros imutáveis, você poderia cortar o intermediário e declarar os mesmos atributos do objeto imutável na classe que guarda sua instância. Assim você teria uma árvore mais rasa. Acho que salvo alguma necessidade muito específica isso seria mais direto e fácil de compreender.
Comment: @CarlosHeuberger eu concordo sobre o acesso a variáve estática. Agradeço por me chamar a atenção, corrigi o erro. Agora sobre ter 38 autores - isso distribui a responsabilidade sobre as coisas, mas não a exime de ninguém.
Comment: Seguindo o que o @CarlosHeuberger disse, um membro estático pode sim ser acessado/manipulado por um membro não estático. O que não pode é o contrário.
Comment: @CarlosHeuberger eu penso que outras pessoas podem usar o redistribuível de um código. Modificadores de acesso devem ser usados para controlar como outros projetos vão utilizar o que a gente faz, não para nos protegermos de nós mesmos.
Answer: Primeiro, no meu entender Java não tem constante, tem campos estáticos que não podem ter seu valor alterado depois de definidos, o que por ser estático ocorrerá sempre antes de ser acessado a primeira. Não sei se Java tem alguma especificação que indica o momento exato da atribuição. Então pra mim o termo constante nem pode ser usado no caso mostrado na pergunta, ela é uma variável estática imutável.
Em C# existe variável imutável, estática ou não e constante que sempre é estática e garantidamente é o mesmo em toda execução (se o programador não fizer barbeiragem e usar constante como se fosse variável imutável). Claro que constante deve ser resolvida em tempo de compilação sempre, não pode ser inicializada depois, então nem todos os tipos podem ser usados.
Se isso não responde a pergunta como desejaria, então eu diria que um tipo por referência, chamado na pergunta de não primitivo*, colocado em uma variável final, que a torna imutável, poderia ser chamado de constante, independente de ser estática ou não, afinal se o termo é usado errado em variáveis estáticas, não vejo porque não usar em variáveis de instância. Então seria o valor indicado por aquele identificador, que é a referência para um objeto é "constante", mas o objeto apontado por ela pode ser variável.
Ter capacidade de variar é diferente de ser uma variável. Assim como não ter a capacidade de variar não pode ser automaticamente considerado constante.
Imutabilidade é diferente de constância. Embora eu sabia que algumas pessoas possuem outro entendimento. Eu acho que a própria matemática não define bem o que é uma constante. Existe algo que não varia no algoritmo e algo que não varia nunca, que eu acho que é a verdadeira constante.
Não entrei no mérito disso ser desnecessário no código linkado na pergunta porque não é o foco dela, mas se quiser saber tem a resposta do Renan que é bem no estilo que gosto, desmistificando mitos.
* isso vai dar confusão quando Java futuro permitir tipos por valor não primitivos, por isso que eu falo pra sempre conceituar certo, mesmo quando parece que não precisa
Comment: Em outros termos, o que no Java chamamos de constantes são, na verdade, variáveis estáticas imutáveis?
Comment: @IgorVenturelli Isso, exatamente como está na resposta. Melhorei.
Comment: @CarlosHeuberger E pomo definiria esses membros de estado que estão estáticos?
Comment: ah, é só uma questão linguística, bom o termo me parece ser esse então acho que por você não estar acostumado achou estranho. Pensei que o termo estivesse errado. Eu até prefiro usar campo, como em C#, mas em Java há preferência por atributo, então tento usar o que mais se usa em cada comunidade.

Constantes de tipos não primitivos


The difference between the user and the bot

Question: I practice in rails and the following question arose - how does the site is determined by the user, person or bot?
I use RoR - Capybara with Poltergeist
There is the following code:
require 'capybara/poltergeist'
options = {}

Capybara.register_driver :poltergeist do |app|
  Capybara::Poltergeist::Driver.new(app, options)
end

session =Capybara::Session.new(:poltergeist)
session.driver.headers = { 'User-Agent' => ''}

session.visit 'https://gumtree.com'
session.save_and_open_page

In the User-Agent field, I set my data and execute the code.
If i just go to URL - the page is displayed correctly. If i run the code, it saves a blank page to where it redirects.
I have cleaned cookies. We have the same IP address. What other signs do we have different?
Answer: There are many many ways for a site to determine that you using an automation tool. The two easiest in this case are

Poltergeist loads some JS into every page which is easily detectable.
Poltergeist doesn't support a ton of new CSS/JS so the site could be feature testing the browser, seeing that it looks like a 7 year old version of Safari and finding that suspicious enough to assume it's a bot.

Beyond that there are many more methods which would need complete analysis of the pages JS to see exactly what they're doing. Gumtree is very aggressive about detecting bots in order to prevent people from violating their terms of use, and bypassing that is well beyond a stackoverflow answer.


I making Restaurant app form Udemy tutorial it show me this error

Question: I facing this error
Error: The argument type 'Object?' can't be assigned to the parameter type 'Widget?'.
tabs_screen.dart:34

Object is from dart:core.
Widget is from package:flutter/src/widgets/framework.dart

('/C:/flutter_windows_3.3.4-stable/flutter/packages/flutter/lib/src/widgets/framework.dart').
framework.dart:1

body: _pages[_selectPageIndex]['page'].

Code
class TapScreen extends StatefulWidget {
  const TapScreen({super.key});

  @override
  State<TapScreen> createState() => _TapScreenState();
}

List<Map<String, Object>> _pages = [
  {'page': CategoriesScreen(), 'title': 'Catergories'},
  {'page': FavoitesScreen(), 'title': 'your Favorites'}
];

class _TapScreenState extends State<TapScreen> {
  int _selectPageIndex = 0;
  void _selectPage(int index) {
    setState(() {
      _selectPageIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("meal"),
      ),
      body: _pages[_selectPageIndex]['page'],
      bottomNavigationBar: BottomNavigationBar(
        onTap: _selectPage,
        backgroundColor: Theme.of(context).primaryColor,
        unselectedItemColor: Colors.white,
        selectedItemColor: Colors.amber,
        currentIndex: _selectPageIndex,
        type: BottomNavigationBarType.shifting,
        items: [
          BottomNavigationBarItem(
            backgroundColor: Theme.of(context).primaryColor,
            icon: Icon(Icons.star),
            label: 'Favorites',
          ),
          BottomNavigationBarItem(
            backgroundColor: Theme.of(context).primaryColor,
            icon: Icon(Icons.category),
            label: 'Favorites',
          ),
        ],
      ),
    );
  }
}

Answer: In Dart Object can be anything and the body of the scaffold expects only the type Widget thus causing the error. It is always better to use Widget type annotation.
In your case, Check if that Object is a widget type or not
 _pages[_selectPageIndex]['page'] is Widget ?  _pages[_selectPageIndex]['page'] as Widget : Text("Page not found");

Full code
class TapScreen extends StatefulWidget {
  const TapScreen({super.key});

  @override
  State<TapScreen> createState() => _TapScreenState();
}

List<Map<String, Object>> _pages = [
  {'page': CategoriesScreen(), 'title': 'Catergories'},
  {'page': FavoitesScreen(), 'title': 'your Favorites'}
];

class _TapScreenState extends State<TapScreen> {
  int _selectPageIndex = 0;
  void _selectPage(int index) {
    setState(() {
      _selectPageIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("meal"),
      ),
      body: _pages[_selectPageIndex]['page'] is Widget ? _pages[_selectPageIndex]['page'] as Widget : Text("Page not found"), // Change here
      bottomNavigationBar: BottomNavigationBar(
        onTap: _selectPage,
        backgroundColor: Theme.of(context).primaryColor,
        unselectedItemColor: Colors.white,
        selectedItemColor: Colors.amber,
        currentIndex: _selectPageIndex,
        type: BottomNavigationBarType.shifting,
        items: [
          BottomNavigationBarItem(
            backgroundColor: Theme.of(context).primaryColor,
            icon: Icon(Icons.star),
            label: 'Favorites',
          ),
          BottomNavigationBarItem(
            backgroundColor: Theme.of(context).primaryColor,
            icon: Icon(Icons.category),
            label: 'Favorites',
          ),
        ],
      ),
    );
  }
}

Answer: You can provide default widget on null case.
body: _pages[_selectPageIndex]['page'] as Widget? ?? Text("not found"),


Why applying the same test to several hypotheses reduces its rejection power?

Question: UPDATE: after more study on the subject, I noticed that I didn't have a good grasp on the difference between $p$-value and significance. In particular in the last portion of the question I use the term $p$-value instead of significance. I'll leave the question as is for future reference, just keep in mind that it is a bit imprecise :)
Reading "Kernel Methods for Pattern Analysis", by John Shawe-Taylor, I've got stuck into this sentence:

[...] if we applied the same test for $n$ hypotheses $P_1, \dots, P_n$, and found that for one of the hypotheses, say $P^*$, a significance of $p$ is measured, we can only assert the hypothesis with significance $np$. This is because the data could have misled us about any one of the hypotheses, so that even if none were true there is still a probability $p$ for each hypothesis that it could have appeared significant, giving in the worst case a probability $np$ that one of the hypotheses appears significant at level $p$.

This sentence doesn't make any sense to me, since each test is independent of the other $n-1$. Can you provide me with a clear example of the contrary? Can you provide me a mathematical proof, or at least an insight?
EDIT: Thanks for the link in the comment (for future reference: xkcd: Significant). Let me elaborate further.
Let's suppose I have a training algorithm $f(\alpha)$, that is, a function $f$ that returns the parameters of a classifier. $\alpha$ is a custom parameter that can be set by the experimenter. If I vary $\alpha$, let's say, between $0$ and $1$ with step $0.1$, I'll get $11$ different results for the classifier parameters. Let's suppose that only in one case this trained classifier (e.g., for $\alpha = 0.6$) is better than a "reference", with $p$-value $0.01$. I still have to say that the overall $p$-value for the null hypothesis is $11 \times 0.11 = 0.121$?
Comment: I believe this question may be answered at http://stats.stackexchange.com/questions/88065. Certainly the "clear example" portion of it is!
Comment: I'm having trouble following the new paragraph because classification and hypothesis testing differ in aims and approach. Could you explain what "null hypothesis" is being evaluated in this procedure?
Comment: @whuber the null hypothesis is "there is no difference in classification performance (error rate) between the reference classifier and the classifier trained using $f(\alpha)$"
Comment: Thank you--that makes the situation clearer. In order to test such a hypothesis, we need a probability model for the distribution under the null. That model will depend on whether you are using the same data to test each classifier. This is an important issue, because any overlap in such datasets will introduce statistical dependencies among the results that ought to be accommodated in any p-value calculation.
Comment: Thank you for the insight! I'm using the "standard" paired t-test, using a large number of cross-validation runs to build the sample. What I didn't consider is the dependence between two experiments with different $\alpha$ values! I guess it would be easier to make each experiment as independent as possible from the others, by using a different seed each time.
Comment: Maybe this is helpfull for you http://stats.stackexchange.com/questions/164181/family-wise-error-boundary-does-re-using-data-sets-on-different-studies-of-inde/164232#164232
Answer: The p-value adjustment you describe is known as the Bonferroni correction.
Regarding your follow-up question about picking the best classifier: in that case you might also be concerned about overfitting to the evaluation set. There are a couple recent papers dealing with this problem that might interest you:
http://jmlr.org/proceedings/papers/v37/blum15.html
http://www.sciencemag.org/content/349/6248/636.full
Answer: Look at this from a different perspective with just P1 and P2. lets say you're looking for p significance level, that is, the chance to regect P1 if P1 is true is less or equal to p.
lets assume that P1 and P2 are indepentent.
what is the chance to not reject P1 and P2 if both are true: (1-p)^2. so the chance to reject atleast one: 1-(1-p)^2 = 2*p - p^2 --> 2*p for small p.
The same methodology applies for n>2.
When we use instead of P, P/n than we will have the desired significance level of p that atleast one of the hypothesis will be rejected when all the null are trues.
Comment: Isn't $p$ the chance of accepting $P_1$ even if $P_1$ is false?


How to make SCSI enclosure LEDs blink?

Question: I have a SCSI enclosure (supermicro BPN-SAS-825TQ) residing on Ubuntu 16.04.
Is there an sg_ses (or sg_senddiag or other) command I can send to the enclosure, that will make the Rear LEDs blink, even if there's no disk in the enclosure?
Answer: After having spent an hour trying to figure out how to get the correct indices for sg_ses command to work, I ended up using encled utility from this project https://github.com/amarao/sdled which has much more intuitive interface. It's a python script, so no compilation required, you can just download it and use right away.

Encled - utility to change location / fault LED for enclosure.

"location" and "fault" is just how LEDs are named. They both may actually be represented by a single LED, but locate would make it blink, while fault would just turn it on continuously.
Note: the project has both sdled and encled utilities — you want the latter.
Examples:

List devices and LED status on them: ./encled
Turn on "locate" LED on /dev/sdbe device: ./encled sdbe locate
Turn off all LEDs on all devices: ./encled all off
Answer: That depends on your particular backplane being visible to the host system (it should be visible as SCSCI device under lsscsi -g). In general, to turn on ID LED in a slot 1 of the /dev/sg4 enclosure you should issue
sg_ses --dsn=1 --set=ident /dev/sg4
and, alike, to turn it off
sg_ses --dsn=1 --clear=ident /dev/sg4

How to make SCSI enclosure LEDs blink?


VBA - Sem permissão para compactar

Question: Boa tarde peoples.
Estou trabalhando em um código que descompacta um arquivo ".xlsm", troca o VBProject e compacta denovo. Porem surgiu um problema de permissão na hora de compactar, espero que possam me auxiliar.
Dim Fname As Variant, FileNameFolder As Variant, DefPath As String, strDate As String

Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(ThisWorkbook.Path)
Set fc = f.Files

For Each f1 In fc
na = na & f1.Name
If Not na Like "*Update.xlsm" And Not na Like "*.bin" Then GoTo conl
na = ""
Next
Exit Sub

conl:

pat = ThisWorkbook.Path & "\"
fs.copyfile pat & na, pat & na & ".zip"

Fname = pat & na & ".zip"

DefPath = ThisWorkbook.Path
If Right(DefPath, 1) <> "\" Then DefPath = DefPath & "\"

FileNameFolder = DefPath & "pasta\"
MkDir FileNameFolder

Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).Items
fs.copyfile pat & "vbaProject.bin", pat & "pasta\xl\vbaProject.bin", True

Kill Fname

'alternativa(ocorre o mesmo problema)
'Open pat & na & ".zip" For Output As #1
'Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
'Close #1

'oApp.Namespace(Fname).CopyHere oApp.Namespace(FileNameFolder).Items

Set Folder = fs.GetFolder(FileNameFolder)

zipName = Folder.Name + ".zip"
fs.CreateTextFile(pat & zipName, True).Write "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)
Set zipFile = fs.GetFile(pat & zipName)
Set Source = oApp.Namespace(Folder.Path).Items

oApp.Namespace(zipFile.Path).CopyHere (Source)

On Error Resume Next

fs.deletefolder Environ("Temp") & "\Temporary Directory*", True
End Sub```

Grato desde já.

Comment: Qual a mensagem de erro?
Comment: @Evilmaax | Acredito que a mensagem não vem do Excel, ela é a seguinte: **"Arquivo não encontrado ou nenhuma permissão de leitura"** e o título é **"Erro de pastas compactadas (zipadas)"** ;)
Answer: Felizmente consegui resolver este problema... na verdade eu usei outro código, mias simples de certa forma. Para o bom funcionamento dele é necessário add as referências: "Microsoft Scripting Runtime" e o "Microsoft Visual Basic for Application Extensibility 5.3".
Segue o código:

Private Const IMPORT_DELAY As String = "00:00:03"
Private Const proj_name As String = "vpject365"
Public componentsToImport As Dictionary, vbaProjectToImport As VBProject, i As Integer, pat As String

Public Sub Workbook_Ca1culate()
Stop
Dim FSO As Object, fn, f, fc, fl, i As Integer, msgTitle As String
Set FSO = CreateObject("Scripting.FileSystemObject")
Set f = FSO.GetFolder(ThisWorkbook.Path)

msgTitle = "Selecione o arquivo Acob"
If i = 1 Then msgTitle = "Selecione o arquivo Combo"

With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.InitialFileName = f
.Title = msgTitle
.Show
Workbooks.Open .SelectedItems(1)
pat = .SelectedItems(1)
Build.testImport
End With

ThisWorkbook.Saved = True
ThisWorkbook.ChangeFileAccess xlReadOnly

Kill f & "\" & "update.xlam"
Workbooks(fn).Close SaveChanges:=True
ThisWorkbook.Close
End Sub

Public Sub testImport()
'Nathan

Dim vbaProject As Object: Set vbaProject = Application.VBE.VBProjects(proj_name)

On Error Resume Next
On Error GoTo 0

Dim FSO As New Scripting.FileSystemObject, export_path As String, c As VBComponent, bas As String, vComponentName As Variant

bas = "cb"
If i = 1 Then bas = "cmb": i = 1

export_path = FSO.GetParentFolderName(vbaProject.fileName) & "\"
Set c = vbaProject.VBComponents("Compilado")
Set componentsToImport = New Dictionary
Set vbaProjectToImport = vbaProject

vbaProject.VBComponents.Remove c

componentsToImport.Add bas, ThisWorkbook.Path & "\" & bas

Application.OnTime Now() + TimeValue(IMPORT_DELAY), "'Build.importComponents'"

If i = 1 Then Workbook_Ca1culate

End Sub

Public Sub importComponents()

Dim componentName As String, vComponentName As Variant

For Each vComponentName In componentsToImport.Keys
componentName = vComponentName
vbaProjectToImport.VBComponents.Import componentsToImport(componentName)
Next

Set componentsToImport = Nothing: Set vbaProjectToImport = Nothing
Stop
Application.Wait (Now() + TimeValue("0:00:05"))

'Dim FSO As Object, fn, f, fc, fl
'Set FSO = CreateObject("Scripting.FileSystemObject")
'Set f = FSO.GetFolder(ThisWorkbook.Path)
'Set fc = f.Files

'For Each fl In fc
'fn = fl.Name
'If fn Like "*.xlsm" And Not fn Like "~$*" And Not fn Like "update.xlsm" Then GoTo jmpa
'Next
'MsgBox "Macro não encontrada": Exit Sub
'jmpa:

Kill pat 'f & "\" & "update"

End Sub

Agora ao invés de mover o VBProject inteiro ela move somente o módulo, como desejado. ;)

VBA - Sem permissão para compactar


NBA Team Scoring Averages 2015 vs 2014

Question: What is the NBA's average team score from season to season; 2014 season vs 2015 season?
Answer: These charts show each team's average points per game as well as a bunch of other stats:
NBA Team Statistics Comparison 2014/15
NBA Team Statistics Comparison 2015/16

NBA Team Scoring Averages 2015 vs 2014


Logistic Regression Model inquiry with binary data

Question: The short version of my model is that I have ran a logistic regression (logisticmodel<-glm(FishObs~CGDD, family = binomial, data = dat1)) looking at when fish were observed (denoted by 0 or 1, 1 being observed) against thermal cues (CGDD). I ran this core model with three years of data (2015-2017) that I pooled together and did not account for year. I then used this core model and trained it on an additional year of data(2018) to look at misclass, sensitivity and specificity. 2015, 2017, and 2018 have 365 points of data. 2016 has 366 points of data for the leap year.
Where I am stuck is understanding some theory…

I was advised to pool data from (2015-2017) and train it against the 2018 data. But I am wondering if this model is inaccurate without considering year as a random factor. I am wondering under what conditions it makes sense or is appropriate to pool the data? I did run the model with year as a random factor, and the model worked but I was unable to determine the predicted probabilities. Perhaps limited by my R knowledge.

When using 2015-2017 data and training it against 2018, is there logic to this decision? My concern would be had I of ran 2016-2018 against 2015 for example, the outcome of the core model would be different.
Answer:
I am wondering under what conditions it makes sense or is appropriate to pool the data?

The model without year as a factor looks like
$$ \operatorname{logit}(p) = \beta_0 + \beta_1 {CGDD} + \beta_2{t} $$
Where $t$ is a year factor.  If $\beta_2$ is small enough to be negligible over the three years or so you choose to pool the data then it makes sense to pool.
We can actually test this assumption statistically.  Fit two models (one with year and one without) and perform a likelihood ratio test.  If you treat year as a continuous variable (and you should) this will be equivalent to the Wald test reported in the summary of the model.

When using 2015-2017 data and training it against 2018, is there logic to this decision?

This is something for you to convince us of.  It makes most sense to forecast on unseen data from the future (I disagree that accuracy, sensitivity, and specificity are the best measures).  Clearly, if the model is going to be used, it will be used to predict the future from the past (not the past from the future).  But I would encourage you to justify your approach rather than asking the reader to infer proper justification.


Analysis techniques for two continuous independent variables: Sales and Commodity Prices

Question: I have a hypothesis that the transactional volume (sales per time period) of the business where I work is related to outside economic indicators/commodity prices.
Example: When Crude Oil prices go down, the activity of my business goes up.  In my business, that is probably a true statement with Crude Oil, but of course, that needs proving!
Additionally, Crude Oil is not the only economic indicator/commodity, right?  There are hundreds (if not thousands) of economic indicators/commodities that are being tracked and reported.
I have a dataset of our daily sales volumes for the last 10 years.  I also have datasets of the daily prices of commodities (Oil, Fuel, Gold, Metals, etc.)
What analysis and tests do I perform to show a relationship between Crude Oil and our sales volume, or show that there is (likely) no relationship with Soybeans or Hog Futures!
The basic intent would be to then monitor those commodity forecasts to do early warning on our business activities.  The next level of maturity would be to then predict our performance-based the economic forecasts.
Comment: The simplest place to start is [ordinary least squares regression](https://en.wikipedia.org/wiki/Ordinary_least_squares) and trying to estimate some linear function for expected sales conditional on various right hand side variables. Be aware that doing an excellent job with sensible standard errors will be tricky. There are numerous statistical issues such as: (i) are your processes [stationary](https://en.wikipedia.org/wiki/Stationary_process)? (ii) Your residuals may be [autocorrelated](https://en.wikipedia.org/wiki/Autocorrelation)? etc...
Comment: You may want to find someone with a background in linear regression and time series analysis or perhaps develop your own knowledge.
Answer: To check for correlation, you can do the following:
1) Calculate Pearson's correlation coefficient $\hat\rho$ for the sales volume and any commodity. If you think that the commodity prices don't have an immediate effect on the sales, work with lagged values
(i.e. check the correlation between the sales volume $V_p,\dots,V_n$ and the commodity prices $p$ days ago, $C_1,\dots,C_{n-p}$).
2) Next, you should test whether the correlation is significantly different from zero. The correlation coefficient is approximately following a gaussian distribution for large sample sizes: $\mathcal{N}(\rho,1/\sqrt N)$, with $\rho$ being the real correlation and $N$ again denoting the sample size that is used in the correlation coefficient (if you test lagged values, use $N=n-p$).
You can thus construct a two-tailed hypothesis test with null hypothesis $\mathcal H_0: \rho=0$, alternative $\rho\ne0$ and test statistic $\hat\rho$.
The null hypothesis can be rejected at significance level $\alpha$, if
$$|\hat\rho|>\frac{q_{1-\alpha/2}}{\sqrt N},$$
where $q$ denotes the respective gaussian quantile. For example, considering a significance level $\alpha=5\%$, we have $q_{0.975}\approx 1.96$.
3) If the null hypothesis above can be rejected, simply check whether $\hat\rho$ is positive or negative. A negative coefficient would confirm your suspicion that lower commodity prices imply higher sales volume.
With this knowledge, you could then proceed to forecast volume sales, incorporating commodity prices in an appropriate modelling framework.


How can I deduce in which scales and mode to play?

Question: This is maybe a naive question.
Often, guitar tabs are given as a succession of chords (and/or a melody).
Is there a method to know systematically in which scale and/or mode can I play?
Maybe this could be illustrated by these chord change:

Bm - D - F#m7 - E
Answer: With tabs you need to know some theory first on how to determine the key by the chord progression. A quick and simple way to do this is to find the first and/or last chord of the song. But learn I - IV - V twelve bar blues and how to solo with pentatonics first before hitting the modes.  You need to understand basic theory before you get into anything beyond a Pentatonic scale. Your example chord progression is more complicated then a typical pop or blues song.  Although it starts on Bm it can be thought of a B Dorian progression.
Your chord example with the notes are:
Bm = B D F#
D = D F# A
F#m7 = F# - A - C# - E
E = E - G# - B
Those notes from these chords would be in A Major/F# Minor key:
A B C# D E F# G#
Modes derived from scale:

A - Ionian (Major)
B - Dorain
C# Phrygian
D - Lydian
E - Mixolydian
F# - Aeolian (Minor)
G# - Locrian

Modes that can be played over the chords:

Bm - B Dorian
D - D Lydian
F#m7 - F# Aeolian (Minor)
E - E Mixolydian

Try Bm Pentatonic Scale to solo with first
B D E F# A
Comment: Thanks a lot, this answers well my questions. I have some knowledge with pentatonic scales and 12 bar blues. Stepping in modes is another story.
Answer: You ask for a systematic method. If there is only tab to follow, unless you know all the note names on guitar, it's difficult. When the music is there too, it's easier, provided you can name the dots.
Make a list of all the notes used, not including the accidentals with a #, b or natural before them. There should be 7, but not all notes are used in every song. See TTSTTTS to find the missing one or two.Put them in order, in a circle works best. Find the first note of the major scale they belong to. This is the one that gives a clockwise spacing of T T S T T T S between notes. T=2 frets, S= 1 fret. When you've found that note (A in the example above), you've found the major key.
When you've learnt the modes, you'll know that the 1st note is the start of Ionian, 2nd Dorian, 3rd Phrygian, 4th Lydian, 5th Mixolydian, 6th Aeolian, and 7th Locrian. Since the tune you mention is based around the B, the 2nd note, you can use Dorian.
You may notice that all the above 'belong' to A major, and all play the same set of notes, albeit with different tonal centres. E.g. E Mixolydian uses the same notes as A Ionian (major).
This may appear complex, but after doing it with lots of songs, it becomes easier. You'll probably find more songs in maj. (Ionian)  or minor (Aeolian) than the others, depending of course on genre.


Inter-(-intra) class correlation coefficient or intra-(inter-) concordance coefficient in python

Question: My question is about how to calculate inter-(intra-) class correlation coefficient (ICC) or intra-(inter-) concordance coefficient (CCC), ideally in python. My dataset consists of several dozen subjects. For each subject a feature was calculated using three different algorithms and each algorithm was repeated three times. So, I have 3x3=9 measurements for each subject. There is a lot of information on this forum about ICCs. But it is not clear to me which ICC I have to use. Ideally, I would like to make these calculations in python. Are there any python libraries for this?
Answer: I see no one has answered in 3 years and question may not be relevant.
But I would like to provide answer for future users.
Firstly, in Python you can use pingouin package:
import pandas as pd

#create DataFrame
df = pd.DataFrame({'exam': [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6,
                            1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6],
                   'judge': ['A', 'A', 'A', 'A', 'A', 'A',
                             'B', 'B', 'B', 'B', 'B', 'B',
                             'C', 'C', 'C', 'C', 'C', 'C',
                             'D', 'D', 'D', 'D', 'D', 'D'],
                   'rating': [1, 1, 3, 6, 6, 7, 2, 3, 8, 4, 5, 5,
                              0, 4, 1, 5, 5, 6, 1, 2, 3, 3, 6, 4]})

import pingouin as pg

#https://pingouin-stats.org/generated/pingouin.intraclass_corr.html
icc = pg.intraclass_corr(data=df, targets='exam', raters='judge', ratings='rating')

icc.set_index('Type')

It returns a dataframe with lots of different ICC computed (ICC1, ICC2, ICC2). Just read the docs and choose the right one.
Secondly, you can also do the same thing in R
library(irr)
data1 <- data.frame(A=c(1, 1, 3, 6, 6, 7, 8, 9, 8, 7),
                   B=c(2, 3, 8, 4, 5, 5, 7, 9, 8, 8),
                   C=c(0, 4, 1, 5, 5, 6, 6, 9, 8, 8),
                   D=c(1, 2, 3, 3, 6, 4, 6, 8, 8, 9))

icc(data1, model = "oneway", type = "consistency", unit = "single")

Don't forget to read the package docs.


How to find the maximum peak of $\phi$ on $[0,l]$.

Question: You are given, $\phi(r)=a_1J_0(\alpha r)+a_2J_0(\beta r)$, where $a_1$ and $a_2$ are constants so that $a_1+a_2=1$, and $r\in[0,\infty)$. $\alpha$ and $\beta$ are parameters, which are positive. If there is some $l>0$ such that $\phi(l)=0$ and $\phi$ is non negative on $[0,l]$. How to find the maximum peak of $\phi$ on $[0,l]$.
Here $J_0$ denotes the Bessel function of the first kind.
Answer: As usual, the maximum occurs at a critical point.  We want to solve
$$ \phi'(r) = -\alpha a_1 J_1(\alpha r) - \beta a_2 J_1(\beta r) = 0$$
for $r$, which will generally have to be done numerically.
Comment: But $\alpha$ and $\beta$ are positive parameters, How to sort out that problem
Comment: @DilrukGallage First step could be substituting $a_2 = 1 - a_1$ to get rid of one variable.


Find Fraction of the Area of Square Shaded With Pink

Question: From the image below, the given and question is:

They are two identical squares and four identical pink triangles. $'A'$ is the midpoint, what fraction of the square on the right is shaded pink?

Now, I can very much understand that since $A$ is the midpoint, each of the $4$ identical triangles is split into a total of $8$ triangles with a {height:width}=${4:1}$ and that the sides of the square is split into two lengths with ratio $1:3$ on where the pink lines intersect with it.
However, with those I have no idea what to do next. Can anyone confirm the answer of $\frac{2}{5}$ and a solution?
Answer: Let $a$ be the edge of the square. Consider the following picture:
Note that $DE\parallel CK$, so $AI:IC= AE:EK= 1:4$. Thus $d(I,AB):d(C,AB)=AI:AC=1:5$, i.e. $d(I,AB)=\frac{a}{5}$. So $Area(AED)= \frac{a^2}{8}$, $Area(IEB)= \frac{EB\cdot d(I,AB)}{2}= \frac{3a^2}{40}$, so shaded area is $2\cdot(\frac{a^2}{8}+\frac{3a^2}{40})= 2\cdot \frac{a^2}{5}$. Therefore, the ratio of the shaded area and the area of the square is $2:5$.