finding intermediate fields of field extensions: simple method vs. Galois theory

Question: I am looking for a straightforward way to find all intermediate fields of a field extension. Let's take the splitting field of $X^3-2$ over $\Bbb Q$ as an example.
If we adjoin the roots of $X^3-2$ to $\Bbb Q$ we get $\Bbb Q(\sqrt[3]{2}, \zeta_3)$ with $\zeta_3$ a primitive root of unity different from $1$. My idea for finding the intermediate fields would be to look at the $\Bbb Q$-basis derived from the minimal polynomials of the successive extensions $\Bbb Q(\sqrt[3]{2}, \zeta_3)/\Bbb Q(\sqrt[3]{2})/\Bbb Q$.
This basis would be $\{1, \sqrt[3]{2}, (\sqrt[3]{2})^2, \zeta_3, \zeta_3 \sqrt[3]{2}, \zeta_3 (\sqrt[3]{2})^2\}$. Now I look for basis elements which can be turned into other basis elements by field operations like squaring, adding, etc. This is obviously the case for $(\sqrt[3]{2})^2$ but also $(\zeta_3 (\sqrt[3]{2})^2)^2 = -2\zeta_3 \sqrt[3]{2}$. So I get the following intermediate fields: $\Bbb Q(\sqrt[3]{2})$, $\Bbb Q(\zeta_3)$, $\Bbb Q(\zeta_3 \sqrt[3]{2})$.
Does this method give me all intermediate fields? If yes, what's the advantage of an analysis using Galois theory? If no, what am I missing?
Comment: Interesting "challenge" to Galois theory! But/and, the fatal issue is that intermediate fields could conceivably (in general, if not necessarily in your example) be generated by _linear_ _combinations_ of whatever basis elements one chooses. Maybe not, in some examples, as in your "simple method", but that needs proof... which is "field theory" and "Galois theory".
Comment: Depending on what you mean about "turned into basis elements by field operations", inside $\mathbb Q(\zeta_5)$ (fifth root of unity) there is a unique subfield $\mathbb Q(\sqrt{5})$. Is this addressing your question?
Comment: @Marc Btw, you missed one intermediate field extension.
Comment: @paul: can you please give an example where this occurs?
Comment: @user26857: can you please tell me which one, so I can see where the method goes wrong?
Comment: @Marc $\Bbb Q(\zeta_3^2 \sqrt[3]{2})$
Comment: Ah, ok, yes I forgot this one. This is also generated by the basis element $\zeta_3 (\sqrt[3]{2})^2$, so it hasn't much to do with the method.
Comment: Thanks, I need to think about this
Answer: How do you prove you've found all possible relations between basis elements? This is especially difficult if you're unlucky in your choice of basis, or in how the field is given. For example, the field $\mathbb{Q}(\sqrt[3]{2},\zeta_3)$ can just as validly be presented as $\mathbb{Q}(\sqrt[3]{4}-5\sqrt[3]{2} + \zeta_3)$. What do you do now?
More importantly, how do you know you've captured all intermediate fields $\mathbb{Q}\subset K\subset \mathbb{Q}(\sqrt[3]{2},\zeta_3)$ that are of the form $K=\mathbb{Q}(a)$ for some $a$ that's not a basis element?
Comment: I don't know how to prove what you ask for. But if the field extension is given the way you write it, I can still try to successively add the elements and analyze the minimal polynomials which leads me to $\Bbb Q(\sqrt[3]{2}, \zeta_3)$.
Comment: Your second objection seems fatal because it implies that the method wouldn't work even if one could prove what you asked me to. Can you please give an example of such a situation? I think I haven't seen this yet.


Notepad++ Function List plugin: Javascript parsing rules to support nested functions

Question: [Using Notepad++ 5.5.1 and Function List plugin v2.0beta]
I'm trying to add to or modify the existing rules for Javascript functions in order to show nested (or member) functions in the function list.  For example:
function parentA (base){
  function childA (exp){
    return Math.pow(base, exp);
  }

  alert(childA(2)); // call private function
}

parentA(4); // alerts 4^2 = 16

var parentB = function(str1){
  return {
    childB: function(str2){
      alert(str1 + str2);
    }
  };
}('foo');

parentB.childB('bar'); // alerts 'foobar'

The parentA and parentB functions are listed, but the childA and childB functions are not listed.  This nested-child paradigm is common within Javascript libraries and reusable code, and important to be fully navigable in the function list.
Can this be done with groups and/or subgroups?  I've tried digging through the parsing rules for other class-based languages (that list member functions using subgroups), but I can't seem to get this to work for Javascript.
Any suggestions?  Has anyone accomplished this for their own use?  I'm probably being stupid, but I'm going crazy trying to figure this one out - please help!  ;)
Answer: Remove the "body begin" and "body end" characters and it will work:
<Group name="Functions" subgroup="" icon="" child="" autoexp="0" matchcase="0" fendtobbeg="" bbegtobend="" keywords="">
     <Rules regexbeg="^\s*function" regexfunc='\s*["\w_]+' regexend="" bodybegin="" bodyend="" sep="" />
</Group>

(this example works only for the first type of functions you have put as an example)
Comment: Thanks!  I've long since been using the SourceCookifier plugin (which is outstanding) instead of FunctionList, so I can't test this to verify - but I'll accept it for the effort ;)


How can I add hatching for specific bars in sns.catplot?

Question: I use seaborn to make a categorical barplot of a df containing Pearson correlation R-values for 17 vegetation classes, 3 carbon species and 4 regions. I try to recreate a smaller sample df here:
import pandas as pd
import seaborn as sns
import random
import numpy as np

df = pd.DataFrame({

    'veg class':12*['Tree bl dc','Shrubland','Grassland'],
    'Pearson R':np.random.uniform(0,1, 36),
    'Pearson p':np.random.uniform(0,0.1, 36),
    'carbon':4*['CO2','CO2','CO2', 'CO', 'CO', 'CO', 'CO2 corr', 'CO2 corr', 'CO2 corr'],
    'spatial':9*['SH'] + 9*['larger AU region'] + 9*['AU'] + 9*['SE-AU']

    })

#In my original df, the number of vegetation classes where R-values are
#available is not the same for all spatial scales, so I drop random rows
#to make it more similar:
df.drop([11,14,17,20,23,26,28,29,31,32,34,35], inplace=True)

#I added colums indicating where hatching should be
#boolean:
df['significant'] = 1
df.loc[df['Pearson p'] > 0.05, 'significant'] = 0
#string:
df['hatch'] = ''
df.loc[df['Pearson p'] > 0.05, 'hatch'] = 'x'

df.head()

This is my plotting routine:
sns.set(font_scale=2.1)

#Draw a nested barplot by veg class
g = sns.catplot(
data=df, kind="bar", row="spatial",
x="veg class", y="Pearson R", hue="carbon",
    ci=None, palette="YlOrBr", aspect=5
    )

g.despine(left=True)
g.set_titles("{row_name}")
g.set_axis_labels("", "Pearson R")
g.set(xlabel=None)
g.legend.set_title("")
g.set_xticklabels(rotation = 60)

(The plot looks as follows: seaborn categorical barplot)
The plot is exactly how I would like it, except that now I would like to add hatching (or any kind of distinction) for all bars where the Pearson R value is insignificant, i.e. where the p value is larger than 0.05. I found this stackoverflow entry, but my problem differs from this, as the plots that should be hatched are not in repetitive order.
Any hints will be highly appreciated!
Answer: To determine the height of individual bars and hatching, we get a container for each graph unit, get the height of that individual container, determine it with a specified threshold, and then set the hatching and color. Please add the following code at the end.
for ax in g.axes.flat:
    for k in range(len(ax.containers)):
        h = ax.patches[k].get_height()
        if h >= 0.8:
            ax.patches[k].set_hatch('*')
            ax.patches[k].set_edgecolor('k')

Edit: The data has been updated to match the actual data, and the code has been modified accordingly. Also, the logic is conditional on the value of the hatching column.
for i,ax in enumerate(g.axes.flat):
    s = ax.get_title()
    dff = df.query('spatial == @s')
    dff = dff.sort_values('veg class', ascending=False)
    ha = dff['hatch'].tolist()
    p = dff['Pearson R'].tolist()
    print(ha)
    for k in range(len(dff)):
        if ha[k] == 'x':
            ax.patches[k].set_hatch('*')
            ax.patches[k].set_edgecolor('k')

Comment: I think the method of judging from the height of the graph is also useful, so I left it and added code to judge from the value of the data frame.
Comment: thanks for sharing your idea! However, the significance is not determined by the R value itself, but by the p value (separate column in the df -> R value is significant where p value < 0.05). Thus relating the hatch to the bar height is not what I want.
Comment: This looks exactly like what I want, but if I add it to my plotting routine, the following error message pops up: "list index out of range" (relating to p[k], I think). I assume this might happen because in my original df, the four different spatial scales do not contain the same number of R-values (some vegetation classes do not exist on the smaller scales). So the number of vegetation classes with R-values is 17 for "SH", 15 for "larger AU region", and 14 for both "AU" and "SAU"...
Comment: I am creating the code based on the data presented, so it may be different with actual data. Can you provide sample data with the same structure as the actual data?
Comment: Absolutely. I just added a line where I drop random rows to make it more similar to my original df. I hope this helps!
Comment: What do the four blanks refer to? When I run the code, it creates a list of hatching by graph. I think the hatching matches that list. And am I referring to the hatching columns in the wrong way?
Comment: The following code is used for sorting. `dff = dff.sort_values('veg class', ascending=False)` Try this: `print(dff)`
Comment: I achieved my goal with this answer and a tiny adaptation: I removed  the line ```dff = dff.sort_values('veg class', ascending=False)```, as this yielded hatching of the bars in the wrong order. Thank you so much solving my problem in no time!


Quando uso essa permissão ocorre um erro no TODO. O que eu faço?

Question: Quando uso essa permissão ocorre um erro no TODO. O que eu faço?
 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return TODO;
            }

Este é o erro:

Error:(40, 20) error: incompatible types: unexpected return value
Comment: Tem que retornar alguma coisa então. O que seria TODO?
Comment: mano vc sabe pra q serve essa permissao?
Comment: esse TODO ele cria automaticamente
Comment: Localização. Mas sua dúvida não parece ser sobre isso. Você não parece entender o que está fazendo. Você copiou e colou?
Comment: nao sei mesmo nao. Estou tentando fazer um projeto q retorna a latitude e longitude atual e quando uso o LocationManager.requestLocationUpdate() ele pede essa permissao.
Comment: Procure aqui no site sobre pedir permissões no Android 6. Você tem que entender o que está fazendo antes de perguntar por que o código não funciona.
Answer: O erro ocorre pois está retornando uma variável que não existe !
Além de verificar se existe a permissão é necessário solicitar, caso não exista!
Segue um exemplo:
public static final void checarPermissao(final Activity activity) {
    if(null == activity) return;

    // VErifica se você tem uma permissão específica.
    if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        // Obtém se você deve mostrar  a UI com justificativa para solicitar uma permissão.
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {

            Toast.makeText(activity, "Por favor, permita o acesso a localização", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    CODE_PERMISSION_LOCATION);
        } else {
            // Chama a Activity que irá solicitar a permissão ao usuário
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    CODE_PERMISSION_LOCATION);
        }
    }
}

Answer: Observe isso:
return TODO;

Quem é TODO? Que bicho é esse? O que come? Onde vive?
A resposta é que TODO vem do inglês to do que significa "a fazer". Ou seja, isso é algo que foi gerado automaticamente para dizer que o código está incompleto e que você tem que colocar alguma coisa lá.
Entretanto você não colocou nada e deixou o TODO do jeito que estava. O compilador vai tentar ver isso como um nome de variável, mas esta variável não existe, e portanto você vai tomar um erro de compilação.
Além disso, veja o comentário que antecede isso:
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.

Traduzindo para o português:
            // A FAZER: Considere chamar
            //    ActivityCompat#requestPermissions
            // aqui para requisitar as permissões que estiverem faltando, e então sobreescrever
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // para tratar o caso onde o usuário concede a permissão. Veja a documentação
            // de ActivityCompat#requestPermissions para mais detalhes.


Quando uso reverse() a saída é "None"

Question: continua = 'p'
valores = []
cinco = 5
while continua != 'n':
   valores.append(int(input('Digite um numero')))
   continua = input('Deseja continuar? [S/N]').lower().strip()[0]

   if continua =='n':
       print('Fechando programa')
       break
   if continua =='s':
       print('Continuando o programa.')

print(f'Foram digitados {len(valores)} valores \n Sendo eles {valores.reverse()} \n ', 'Não teve 5 na lista.'if not 5 in valores else 'Teve 5 na lista.' )

Quanto tento rodar esse codigo na parte do print 'sendo eles' ele me retorna ' none '
ficando assim
' Foram digitados 3 valores
 Sendo eles None
  Não teve 5 na lista.'

Answer: Tente usar o reverse antes do print
continua = 'p'
valores = []
cinco = 5

while continua != 'n':
   valores.append(int(input('Digite um numero')))
   continua = input('Deseja continuar? [S/N]').lower().strip()[0]

   if continua =='n':
       print('Fechando programa')
       break
   if continua =='s':
       print('Continuando o programa.')

valores.reverse()

print(f'Foram digitados {len(valores)} valores \n Sendo eles {valores} \n ', 'Não teve 5 na lista.'if not 5 in valores else 'Teve 5 na lista.' )

Quando uso reverse() a saída é "None"


Is Twinkle twinkle little star based on a drone/bourdon?

Question: Is Twinkle twinkle little star based on a drone/bourdon?
If you say no then what is it based on?
Comment: Drone in English but bourdon in french.
Comment: "In music, a [drone](https://en.wikipedia.org/wiki/Drone_(music)) is a harmonic or monophonic effect or accompaniment where a note or chord is continuously sounded throughout most or all of a piece."
Answer: I've just played it on bagpipes so it certainly works with a drone, but I don't think it's particularly based on a drone, no.
It's more based on straightforward open up and down chords if anything.
Comment: What are open up and down chords?
Comment: Arpeggios is the word I was struggling for! Although really it's pretty much all chromatic runs apart from the I - V leap at the start.
Answer: Yes, we can! (of course not the variations by Mozart)
https://en.wikipedia.org/wiki/Twelve_Variations_on_%22Ah_vous_dirai-je,_Maman%22
Actually there can play every tune based on I IV V accompanied  with a drone as example the canon "frère Jacques" can be harmonized I V I or just with a drone... another known example with more chords is "amazing grace"
Comment: You can add a drone to just about any melody with at least interesting results. :)
Comment: yes, "joyful, joyful" will work too ;)
Comment: In der Tat.  Unisono kommen wir weiter. Wenigstens als Anfang. :)


Rebuild images from image style

Question: I have an image style in Drupal 7. I attached several images to a nodes and display the images based on this style. I then changed the effects on this image style but the existing images are not being recreated with the new image style effects. They show with the old image style effects.
If I attach new images, they use the new effects. Deleting an existing image and re-uploading causes the image to use the old effects.
The manual (incorrectly I assume) states that just saving an image style causes a rebuild:
http://drupal.org/documentation/modules/image
I have cleared the cached.
How do I force a rebuild?
Comment: Did you actually clicked on the **Update style** button when being at the Image Style page? I just did a few tests and verified that when you click it, all the generated files at the **files** directory get deleted.
Comment: The manual is correct. Changing an image style, e.g. by adding, editing or deleting an effect, does flush the image style. It may be your browser (or another in between) cache or a rights problem when the derivatives are deleted.
Comment: I used custom drush command to regenerate images https://gist.github.com/typhonius/8599853
Answer: Clearing cache, won't flush image styles: http://drupal.org/node/997332
You could:

delete them manually
use image_style_flush
use the command line: rm -rf sites/default/files/styles
use drush: drush image-flush
Comment: drush image-flush style_name is a godsend. :-)
Comment: this may need a drush clear caches as well, specially if you are using CloudFlare on top
Answer: To flush Image Style Names in Drupal 7 through the UI, try this contrib module:
http://drupal.org/project/imagestyleflush
It gives you a flush option for each Image Style Name. It also has an option to flush all the Image Style Names at once.
Once the module is enabled, in the admin UI go here to flush a particular image style:
admin/config/media/image-styles

Answer: This is a bug with image styles. If you are editing an image style and edit an effect that is already present, the images will not be flushed on update. However, if you delete that effect (I'm not talking about deleting the image style - delete the effect within the particular image style) and create a new one, the images will be flushed on update.
Comment: Just because something's getting called doesn't mean that it's not a bug.  Functionality is not present when it should be.  That's the definition of a bug...
Comment: function image_effect_save() does call image_style_flush(), so this is not a bug.
Answer: There is another, easier way. It's more a replacement than update, but it works fine. You can create a new image style based on the old one, but with new features (image actions) you wish. Then delete the old style; on the deletion confirmation page, you will find a drop list with available image styles, which you can use to replace the old one. This is a standard image style replacement function, I assume.
Answer: Just for information in Drupal 8 you have an "flush" option in the "Edit" dropdown in /admin/config/media/image-styles you can flush one by one.
Answer: Edit the style you want from admin/config/media/image-styles.
Click on 'update style' button on bottom, that will flush all the existing generated images in style folder and create new ones.
Answer: if u have a custom template and wanna force style for an image field :
 $style='full_content_width';
 $path=$node->my_img_field['und']['0']['uri'];
 $style_url = image_style_url($style, $path);
  print "";

Answer: If you are using Drupal Console (and let's face it, why not?) then you can use:
drupal image:styles:flush image_style

Or
drupal isf image_style

Documentation:
https://drupalconsole.com/docs/ca/commands/image-styles-flush

Rebuild images from image style


RequireJS sporadic failure

Question: I'm working on a Magento2 site. Magento2 uses requirejs and the theme I'm using makes use of it as well. Part of the theme uses Owl Carousel. The code used to load the carousel was originally
require(['jquery', 'owl.carousel/owl.carousel.min'], function($) {
    $("#banner-slider-demo-1").owlCarousel({
        // carousel settings
    });
});

However I noticed sometimes when I load the homepage (where the carousel is used) the carousel doesn't display, and there are errors in the console

Uncaught TypeError: $(...).owlCarousel is not a function

Thinking jQuery might not be loaded, I changed the require code to serialize the requirements
require(['jquery'], function($) {
    require(['owl.carousel/owl.carousel.min'], function () {
        $("#banner-slider-demo-1").owlCarousel({
            // ...

but this had no effect... Sometimes the carousel loads and there are no errors, other times there are errors and it doesn't load.
Even when there is an error the carousel file has been fetched by the browser. It also seems require has loaded the carousel script per developer tools

Any idea what could be going on?
Answer: Your issue is that you are loading jQuery through a script element and through RequireJS. You have to use one method, not both.
If I run this in the console:
console.log("owlCarousel", typeof jQuery.fn.owlCarousel)

I get:
owlCarousel function

But with this:
require(["jquery"], function ($) {
  console.log("owlCarousel", typeof $.fn.owlCarousel);
})

I get:
owlCarousel undefined

And if you try require(["jquery"], function ($) { console.log("equal", $ === window.jQuery); }) you'll get equal false. So you have two instances of jQuery loaded. The code that uses RequireJS to access jQuery gets a version without .owlCarousel. That's because Owl Carousel installed itself on window.jQuery.
If you must load jQuery through script for some reason, you should move the script element that loads it before you load RequireJS. (You should do this for all scripts you load that you want to load with script and that are AMD-aware.) Then for RequireJS, you should just define this fake module:
define("jquery", function () {
    return jQuery;
});

This makes it so that when RequireJS loads jQuery it just uses the jQuery already defined in the global space. The ideal place for this fake module would be just before you configure RequireJS.
While you're at it you should define a shim for owl.carousel/owl.carousel.min:
`owl.carousel/owl.carousel.min`: ['jquery']

This way there's no need to nest the call to load owl.carousel/owl.carousel.min inside a call to load jquery. You can just do what you were trying initially:
require(['jquery', 'owl.carousel/owl.carousel.min'], function($) {
  $("#banner-slider-demo-1").owlCarousel({
    // carousel settings
  });
});

Comment: Thanks for this cogent answer Louis. I'm working with your answer and [the appropriate Magento2 dev docs regarding requirejs](http://devdocs.magento.com/guides/v2.0/javascript-dev-guide/javascript/js-resources.html) to get everything square now.

RequireJS sporadic failure


Does it holds that $A - \epsilon B \succeq 0$ as $\epsilon \to 0$?

Question: Let $A, B$ be two equal-sized, symmetric matrices with $A,B \succeq 0$, and let $\epsilon > 0$. I am conjecturing that:  $$A - \epsilon B \succeq 0 \quad\text{as}\quad \epsilon \to 0$$ if (i) $rank (A) \ge rank(B)$, and
(ii) all diagonal entries of $A>0$.
My question is whether my conjecture is true and, if yes, how to prove it.
Any help is much appreciated.
EDIT: The question is whether the above holds for small but positive $\epsilon$; i.e., whether there exists some $\bar\epsilon$ such that the condition holds for all $0 < \epsilon < \bar \epsilon$
Comment: I don't understand your conjecture.  What does $A - \epsilon B \succeq 0$ as $\epsilon \to 0$ mean, and how is it distinct from $A \succeq 0$?
Comment: @Omnomnomnom, It seem to me, the things mentioned here concern to close to $A$ matrices, and not to exactly $A$. The conjectured thing is that close to $A$ matrices are also non-negative -definite, if they are of the form above, with the conditions satisfied.
Comment: One question to clear all up. What if I take exactly positive-definite matrix. Is this case solved?
Comment: @kolobokish if $A$ is positive definite, then the statement holds.  In particular, the positive definite matrices form the interior of the cone of positive semidefinite matrices, within the space of symmetric matrices
Comment: Yes, the clarification of kolobokish is indeed the one I had in mind. I'll edit to make it clear
Answer: Your conjecture, if I understand it correctly, is false. Take
$$
A = \frac 12 \pmatrix{1&1\\1&1}, \quad
B = \pmatrix{1 &0\\0&0}
$$
verify that for all $\epsilon > 0$: $\det(A - \epsilon B) < 0$.
Comment: I'm pretty sure what you need is $\ker(A) \subset \ker(B)$.  I know it's sufficient, but I don't know if it's necessary. An equivalent condition to this one (since our matrices are symmetric) is $im(B) \subset im(A)$
Comment: Thanks, your interpretation was indeed the one I had in mind and the example proves my conjecture wrong.
Comment: One quick follow-up question: Does someone have an idea how one could refine my original conjecture so that $A - \epsilon B$ holds for small but positive $\epsilon$. The trivial case of $A$ being strictly positive-definite that was mentioned above is not an option here). I guess $A$ needs to be "similar" to $B$ in some way, but I don't have a good idea which type of similarity that would need to be


Is the myth that if you can play one instrument, you can learn another instrument with ease true?

Question: I've heard many people say this:

"If you can play one instrument, other instruments will be easy to learn"

I just can't help but wonder if this is true. Suppose I'm a professional flute player. Would learning an instrument, suppose guitar (while being the professional flute player) be simpler to learn than if I didn't play the flute?
Comment: I suggest clarifying the question. First, you ask whether the second instrument will be *easy* to learn, but later, whether it will be *easier*. These are quite different questions.
Comment: IMO, no dupe. It's close, but that one asks about a more specific scenario.
Comment: Not a dupe. The other question regards a particular issue with learning a second instrument. This one is general. It's also not really opinion-based; all 3 answers are in agreement.
Comment: @replete Oops. I typed faster than I could think. I'll clarify.
Comment: With a little editing, this could stop being a dupe.
Comment: @Tim but it's still a "Primarily Opinion-Based" question.
Answer: You wouldn't need to relearn theory or reading music. You wouldn't need to learn to establish a practice regimen. You wouldn't need to relearn to hear intervals or feel a beat.
Going from flute to guitar, you would need to memorize the positions of notes and chords. You would need to develop calluses. You would have to suffer the pain of learning to contort your hand to make barre chords. It would take a lot of practice to develop the muscle memory you need to play proficiently.
If you're going between similar instruments—organ to piano, for example—you would certainly be influenced by the techniques of your original instrument. It could be an advantage. Chords are fingered the same on both instruments. But you'd have a set of disadvantages to overcome as well. In this example, you'd have to learn dynamic expression in a whole new way. Suddenly, the force you put on the keys matters in a way it never did before!
The answer definitely depends on what instrument you're coming from and what instrument you're going to. But, in general, yes, as an experienced musician, you have a considerable advantage that an absolute beginner lacks.
Comment: @replete You're saying that on an organ, if you press keys harder you get a change in timbre? I had no idea. Are there any videos out there that demonstrate that?
Comment: @BobRodes This is true only of proper mechanical action or tracker organs. Many organs have an electric action reducing the keys to mindless on/off operation. Tracker organs are interesting because of a fellow named J. S. Bach who wrote good music for them. Yes my tongue is in my cheek. He did not write for mindless bloated electric action instruments which began to proliferate a century and a half ago. The mechanical action gives a direct connection to the pallet which allows air into the pipe, allowing the player to control the consonant somewhat like the tonguing of a wind player.
Comment: +1, but an extremely minor quibble: "Suddenly, the force you put on the keys matters in a way it never did before!" It matters on the organ too, it is just that the result is different: a change in timbre versus a change in dynamic level.
Comment: Another disadvantage is that you are going from being able to play an instrument fluently to not really being able to speak, if you will. This can be quite frustrating and held me back from learning a second instrument for some time.
Comment: @replete Very interesting. Are there many of those organs still around, or are they all also of the type from the pre-electric days where someone had to work the bellows or whatever?
Comment: @BobRodes Many new ones have been built, spurred on by the HIP craze. It is now widely seen as desirable to have this kind of instrument. The expressive potential due to control of attack (and release!) is wonderful and you won't find many organists willing to go back after experiencing it.
Comment: @replete Never heard of that either. Learned something new.
Comment: @b3ko Good point. I learned drums as a second instrument; it was so completely different I never even thought of that.
Comment: I reckon playing an instrument decently is worth three grades-worth of work on a new one and maybe more.
Answer: Well, it certainly won't be easy, but I think it'll be easier than starting as a complete beginner.
For starters, you'll know the musical side of things. Everyone who's played an instrument knows music theory to some extent, and even if you just know what notes are in a scale, you'll have an advantage over a complete beginner. Any music theory knowledge will help one understand more what one is learning. It may seem like there's a longer way to go because you know from learning one instrument what it takes to learn another, but you're closer than you think, and closer than beginners.
For some instruments, there is a bit of correlation in the actual playing. I imagine most keyboard instruments share similar technique and ergonomics, and instruments of the same family are similar to play (like saxophones). I wouldn't count on much of it for flute and guitar, though, besides maybe the fingering aspect being similar.
I play a couple instruments (decently), and I think the most important thing to remember is that each instrument is different, and serves a different role. Keyboard instruments, like piano, can certainly be melodic, but flute is nearly always carrying the melody, and guitarists need to be able to create harmony in a way that flautists don't usually need to learn.
Best of luck in this endeavor!
Answer: This is no myth!

It is absolutely obvious that you won't have to start at zero as you know already the basics and the grammar of music language, (notation system, staffs, chords, clefs and keys).
Many related instruments of the same section have similar systems of construction and technics of playing.
Mind that practicing a second instrument will be for benefit in any other direction of learning something  new (look up "super learning" in my answer to the other question:

Problems With Learning a Second Instrument


Understanding random forest, gini, and KS

Question: I'm a beginner machine learning user, doing my first predictive model using random forest.
I have some questions regarding the way to measure how good a model is (Gini area from roc curve, and KS), and some about random forest algorithm. Thanks a lot for your help.
1) Which metric is better to compare models? Gini or KS? For example, I have two versions of my model, one in which gini is greater than the other but lower KS.
2) Once I run my model, I can see how significant are each variable I created using VarImpPlot in R. All of them "explain" something, but I struggle to know "when my model is optimal". For example, some times I remove one of the variables and it improves, or sometimes I remove not one but a combination of two, and it improves... but some times it gets worse. Is there any way to know when I reached an "optimal combination" given my set of variables?
Thanks a lot
Answer: Measuring the quality of any predictive model is heavily dependent on the scope of the problem you are working on. Therefore it is very hard to generally say that one measure of goodness is better than another. However, I think the two questions you are working on would benefit from some cross validation.
In regards to your first question, you can use the fact that random forests automatically give you an estimate of their out-of-bag error. This is essentially an unbiased estimate of how the random forest will perform on unseen data. Thus, instead of trying to pick between your two models based on their splitting quality (an indirect measure of prediction quality), you can pick the model that has the lowest out of bag prediction error. If you are not satisfied with the bootstrapped out of sample data that a random forest uses, you can hold out a portion of totally unseen data and run an additional validation test to choose between the two models. As a side note, once you have chosen the "best" model of the two, you do need a totally fresh testing set so can estimate the out-of-sample prediction error for the best member.
For your second question, identifying which variable combination is optimal, again I would recommend using cross validation. Simply train all of your candidate models (different combos of variables) on the training data set. Then pick the model that performs the best on the out of bag error estimate or on your validation data set. That's the best guess of which variable set is optimal. Then test the optimal combo on an untouched testing set to get an unbiased estimate of it's out of sample error.


Homogeneous Markov chains with general state space

Question: I found in the book Markov Chains by Revuz the following definition of a Markov chain.  In the following $(X_n)_{n \in \mathbb{N}}$ is a sequence of random variables on a probability space $(\Omega,\mathcal{F},P_0)$ and the range is a measurable space $(E,\Sigma)$, and $\mathcal{F}_n^0  =\sigma(X_m , m \leq n)$

Definition.1 $(X_n)_{n \in \mathbb{N}}$ is a Markov chain if for every
  $B \in \Sigma$ we have $$P_0 [ X_m \in A \mid \mathcal{F}_n^0 ] = P_0[
 X_m \in A \mid X_n] $$ for all $m\geq n$

For a transition probability $P : E \times \Sigma \to [0,1]$, i.e $x \to p(x,A)$ is measurable for all $A\in \Sigma$ and $A\to p(x,A)$ is a probability measure for all $x\in E$ he defines a family of transition probabilities $(P_n)_{n \geq 0}$ by $$ P_{n} (x,A) = \int_E p(y,A) \, P_{n-1}(x,dy)  $$
and $$ P_0 := P.$$ Then he defines a homogeneous Markov chain by

Definition 2. $(X_n)_{n \in \mathbb{N}}$ is called a homogeneous
  Markov chain with respect to transition probability $P$ if $$ P_0[X_m
 \in A \mid \mathcal{F}_n^o] = P_{n-m}(x,\{X_m \in A\}).$$

I would like to know if $(X_n)$ is a Markov chain with
$$ P_0[X_n \in B \mid X_0 \in A] = P_0[X_{n+m} \in B \mid X_m \in A] $$
for all $n,m\geq 0$ and $A,B \in \Sigma$, does this imply that one can find a transition probability $P$ such that $(X_n)$ is a homogeneous Markov chain with respect to $P$?
Answer: Thankfully, YES :)
You can very simply define the needed probability transition by :
\begin{equation}
P : x, \mathcal{A} \mapsto P_0[X_1 \in \mathcal{A} | X_0=x]
\end{equation}
You can then deduce from the definition of the family $(P_n)$ that :
\begin{equation}
P_n ( x, \mathcal{A} ) = P_0[X_{n+1} \in \mathcal{A} | X_0=x]
\end{equation}
!
Then verify that your Markov chain satisfies the condition to be homogeneous with respect to $(P_n)$, by using the definition of a Markov chain and the property.


Determining modes in a minor Key

Question: Speaking of Functional harmony; If a song is in key C, then we call the C major scale from E to E is a Phrygian mode. Good, what if a song is in key Am, which is actually relative of C and also Am scale can be called aeolian here) what happens?
I mean if somewhere in the song we want to play a Phrygian in key of Am, are we going to play the same (from E to E) notes as we played as if we were in key of C ? Or let me put it other way; In key of Am and the the tonal center is in Em is that correct to play the Phrygian there?
Answer: Let me rephrase your question:
Is the set of notes used for the E phrygian scale the same as the set of notes used for the A natural minor (or A aeolian) scale?
Answer: Yes.
Answer: Well yes, but it won't make any sense.
All of the modes you've mentioned are diatonic to C major. That means that regardless of the tonal center, you're only playing natural notes that also exist in the C major scale.
When you're playing music in a given key, you are tonicizing one note over another. Meaning, the "Do", or tonic note exists in your melodic line the same as it would in your harmony (as a I chord). When you play E phrygian, you are tonicizing E. The notes are the same as those in C major, but if the rest of the music is tonicizing C, then playing a line tonicizing E is not going to make a whole lot of sense!
You should think about modes not as different starting points on a scale, but as different alterations to a scale. If you're playing a piece of music in A minor, you might play an A phrygian solo over a pedal tone, but the notes are not going to be diatonic to C major or A minor! You will alter the 2nd of A minor, by flatting it. The notes will be diatonic to F major starting on A, but realize that F doesn't really have anything to do with the music you are playing--that's just one way to figure out what notes are in a mode.
The other way of figuring out which notes are in a mode is by learning the scale alterations. This will clarify other things for you as well. The simplest examples are lydian, where the 4th note of the major scale is raised; mixolydian, where the 7th note of the major scale is lowered, or dorian, where the 3rd and the 7th of the major scale are flatted. You already know Aeolian/natural minor, where the 3rd, 6th, and 7th notes of the major scale are flatted.
This question/answer will be helpful to you: https://music.stackexchange.com/a/6890/133
Comment: @Spring: Yngwie is playing the notes of an A **harmonic** minor scale which uses the same note material as E **dominant** phrygian (or E mixolydian b2 b6) scale.
Comment: @Ulf is completely correct. I find that guitar players tend to confuse the issue of modes since they spend so much time practicing scale permutations. What Yngwie is playing there is not what I would necessarily call modal--he's in A harmonic minor, but starting on E in order to play over a V-I resolution. He's not tonicizing E--rather, E has dominant function in that context. It would only really be modal playing if E was being fully tonicized.
Comment: Why not make any sense to play E Phrygian over am key? Isnt that's what modes for, as long as I emphasis the Em chord tones during e Pygrigan
Comment: If you emphasize the Em chords, then you aren't playing in Am anymore, you've changed keys to E.
Comment: please read the question well, "In key of Am and the tonal center is in Em is that correct to play the Pyhrigan there?"
Comment: My point is that if your tonal center is different from your "key", the "key" doesn't matter. The other point is that you shouldn't be choosing to play modes just based on what's diatonic to your key signature. That's a convenience-based decision, not a musical one.
Comment: please..what you are saying is the context of the music and its key, "does not matter" how is that possible? what you are saying "might" be true in modal harmony where chords in the progression are unrelated but not in functional harmony
Comment: Btw, I do not mean to imply that "you know it wrong", instead you look very knowledgeable, but my feeling is that we are talking about different things.
Comment: If what you are calling the "key" and "tonal center" are different things, then one of them is not relevant unless you are doing something with bitonality (and I'm pretty sure we are not). If I am writing a piece in C major and the bridge is in G you will usually not bother writing a completely new key signature for the bridge--but the music is still in G. The concept of C major is no longer relevant for the music in that bridge except for notational concerns (there will be F#s in the music instead of in the key signature)--and we should not be considering notation at all in this situation.
Comment: So for the situation you are asking about, the answers to the questions "What key is the music in?", "What is the tonal center?", and "What is the tonic?" should all be the same. And, in order for it to make sense to play E phyrigian over it, it's probably going to be some kind of E minor key. We're also completely ignoring what this actually sounds like--not knowing what exact notes you're playing, does it actually sound musical when you play it? If it does, chances are you're correct and we're just experiencing difficulty in communication what you're actually doing.
Comment: Last try, question is very simple and no need to over-complicate or think deep; Song is Am, you have a chords progression, and one chord in this progression is Em, So if song was in a "major" key, meaning (A but not Am) I would know which mode applies to which chord in that progression.But if that's a minor key (Am), then how can i know which mode applies for given chord like "Em"? SO I "thought" Am is already relative to C major, and if I were playing Em in a C progression that would be E phyrigan!SO even my key is Am I could treat it as if it was its relative Major and find the mode to play.
Comment: Yes; that's correct--the mode on E diatonic to A natural minor is going to be Phrygian. That was literally the first two words of my answer. :-) I just can't see how it would make musical sense to apply modes that way, and we'd really have to hear what you're doing in context in order to evaluate that.
Comment: at 2.18 he tells something, trying to figure out that structure http://www.youtube.com/watch?v=ZNsccTEmIPg
Comment: so you can listen this and evaluate if its right or wrong :)
Comment: I'm with NReilingh, context is the music. And music includes: MELODY, RHYTHM, AND HARMONY.  So remember rhythm is just as important.  Your key, yea, ok, is written down.  But tonal center takes Rhythm into account by like, A LOT.
Comment: tnx good answer, but what is "being fully tonicized" ? and what you mean by "modal playing" is using modal harmony? I hope not
Comment: This comment thread is already too long--please ask other questions or pop into chat if you're confused about something else.

Determining modes in a minor Key


How to reference a JavaScript library in Haxe

Question: I was reading about fluid dynamics and came across this awesome project. After building it, I noticed that the little option menu that appears in the demo is not showing.
So, as I am completely new to Haxe, I thought that adding the little GUI options panel would be a great little challenge in an attempt to familiarise myself with Haxe. However, I have fallen at the first hurdle as I am getting the following error whilst trying to build the GUI that sits on top of the fluid experiment as shown in the demo:

Uncaught ReferenceError: dat is not defined

Inside the projects route directory, I have an src folder, then Main.hx; inside Main.hx at the bottom of the init() function, I am doing the following:
import dat.GUI;

function init():Void {
    //other unrelated code goes here

    var gui = new dat.GUI({autoPlace: true});
    //particle count
    var particleCountGUI = gui.add(particles, 'count').name('Particle Count').listen();
}

When I run the program, the console prints the error mentioned.
Things I have done:
Inside project.flow in the route directory, I have made reference to dat in the build dependencies (and downloaded dat.gui of course).
I have even tried using other frameworks to build the GUI, but I keep getting errors in the console log even if the build is successful. I did have luck getting a panel added, but rather than sitting on top of the fluid experiment, it pushed the whole thing down so there was a space between the panel and the fluid experiment.
Ideally, I want to recreate the options panel shown in the demo, but make it a scrollable list instead. However, I need to understand why I am having issues with dat first!
Answer: The simplest solution I can think of is to add this to init() (assuming the .js is located in the project root):
haxe.macro.Compiler.includeFile("dat.gui.min.js");

includeFile() is a macro that directly embeds the file into the .js generated by Haxe (by default at the top of the file). That's enough to make the UI show up for me:

The alternative would be to add a


Counting repeating numbers in an Array

Question: Fairly new to C#. Have an assignment for class that asks us to generate an array from user inputted values. This part is done and work's perfectly.
Now that the array is completed I need to be able to display each distinct number entered in the array in a Console.WriteLine, and how many times that number appeared and I'm a little lost on how to accomplish this.
Comment: rather than someone else doing your homework for you, do a little research and come back when you have a specific problem and you might just learn a little along the way.
Comment: Which .NET framework are you using? helps to figure if you can use Generics and/or LINQ or none.
Comment: this is more of a problem-solving question rather than a programming question IMO
Answer: Are you allow to use LINQ? If so, investigate GroupBy and Count(). Basically there's a one-liner which will work here, but as it's homework I'll let you work out the details for yourself... ask for more help when you've had a go though, if you run into problems.
Comment: +1 for pointing to the start of the path, rather than the end
Answer: You can create a dictionary in that the keys are numbers, and the values are counts of that specific number in the array, and then increase the values in the dictionary each time a number is found:
Example:
        int[] arrayOfNumbers = new int[] { 1, 4, 2, 7, 2, 6, 4, 4, };
        Dictionary<int, int> countOfItems = new Dictionary<int, int>();
        foreach (int eachNumber in arrayOfNumbers)
        {
            if (countOfItems.ContainsKey(eachNumber))
                countOfItems[eachNumber]++;
            else
                countOfItems[eachNumber] = 1;
        }

This code works in all C# versions, but if you are using C# 3 or greater you could use LINQ, as others are suggesting. =)
Answer: You can use LINQ Distinct() extension method.
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx
Comment: As for the time they appeared, you can use the Distinct()'s result to use Count() for each ocurrence.
Answer: foreach (int item in array)
{
     Console.Write(item.ToString() + " ");
     int frequency = 0;
     for (int i = 0; i < array.Length; ++i)
     {
         if (array[i] == item) ++frequency;
     }
     Console.WriteLine(frequency.ToString());
}

A dirty and brute force way. Considering your array is an "int" array. Otherwise, just change the types.
Comment: Note that this will print each number as many times as its count - so { 1, 1, 1 } would give "1 3;1 3; 1 3".
Comment: Good point. I'd use a dictionary solution to avoid such problems. Or a List instead of an array w/ IndexOf() checking to avoid duplicates.
Answer: Without LINQ, you could keep track of the numbers you're generating. A data structure like a Dictionary could work well, mapping the numbers to how many times you've seen them so far.

Counting repeating numbers in an Array


Expected Value for Random Variable for an Algorithm

Question:
Question:
Algorithm WhoGoesFirst(k):
// k >= 1, the die is fair, and all rolls are independent
Andy rolls the die, let a be the result;
Sean rolls the die, let s be the result;
if a > s
then print Andy goes first;
return k
endif;
if a < s
then print Sean goes first;
return k
endif;
if a = s
then WhoGoesFirst(k + 1)
endif
The algorithm WhoGoesFirst(1) is run, i.e., with k = 1. Define the random variable X to be the value of the output of this algorithm.
What is the expected value E(X) of the random variable X?
Answer: 6/5
Attempt:
I'm not sure how to get an output from this algorithm. Wouldn't the result of rolling the die for both of them have a probability of  1/6? How can I come up with a result that says one person has a higher chance of a roll then the other? And if I assume it is the same, then the recursive function would just loop through the algorithm again. I'm struggling to come up with any output from this algorithm to use to calculate the expected value.
Answer: In the first try, with probability 5/6 one is going to roll higher (they roll different) and with probability 1/6 they'll roll the same and the k is going to increase.
In the next roll, k is going to increase by one so the next who goes next algorithm has expected value of the previous one + 1. Using this we can write
E(X) = 5/6 * 1 + 1/6 (1 + E(X))
solving this yields to 6/5
Alternatively, with probability 1/6 we go to the next roll. Probability that k = 1 is 5/6.
p(k = 2) is 1/6 * 5/6 (first one drew, second one different)
p(k = n) is (1/6) ^ (n-1) * 5/6 (first n-1 drew, last one different)
If you sum the infinite series of k*p(k), you'll get the same result as above.
Hope it helps


ThreadPoolExecutor: how does it reuse threads

Question: I read that ThreadPoolExecutor has pool of threads and this pool is destined to reduce cost of creation new threads (at least I understood phrase below in such way):

When you send a task to the executor, it tries to use a pooled thread
  for the execution of this task, to avoid continious spawning of
  threads. [Java 7 Concurrency Cookbook]

BUT, as I know we have got no way to restart thread in Java.
Question: How does ThreadPoolExecutor avoid creation of new threads?
Answer: It's very simple - in essence the Threads sleep, waiting to be woken by a task - they run that task and then sleep again.
public static void main(final String[] args) throws Exception {
    final BlockingQueue<Runnable> blockingQueue = new LinkedBlockingDeque<>();
    final Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            while (true) {
                try {
                    blockingQueue.take().run();
                } catch (InterruptedException ex) {
                    return;
                }
            }
        }
    });
    t.start();
    blockingQueue.add(new Runnable() {

        @Override
        public void run() {
            System.out.println("Task 1");
        }
    });
    blockingQueue.add(new Runnable() {

        @Override
        public void run() {
            System.out.println("Task 2");
        }
    });
}

The BlockingQueue will block a Thread while it is empty. When I add an item, and Thread(s) currently blocked are awoken and one will take the task (LinkedBlockingDeque is thread safe). When the Thread is done with the task it goes back to sleep.
The JavaDoc for ThreadPoolExecutor describes the logic in detail. All of the constructors for ThreadPoolExecutor take a BlockingQueue<Runnable> - this should give you a hint as so how the logic works.
NB: This is not the same as busy waiting. A BlockingQueue uses wait and notify to suspend and wake Threads, this means that the Threads in the pool are not doing any work when they are not processing tasks. A busy wait based approach would not work because the Threads would block up all the CPU cores with their polling not allowing the program to proceed (or at least severely impairing it).
Comment: @ante.sabo no. Threads are fully blocking so they will not return to the pool until `run()` returns regardless of calls to sleep or blocking IO. What you talk about are, in Java terms, called Fibres and are due to be included in the JDK soon. A reactive programming library can also help here, but you need to be very careful to call it's sleep methods (usually called something like `delay`) and not sleep itself as ... threads are fully blocking.
Comment: Nice info by Boris. In addition they wrap every call to the worker run method around a try-catch throwable so that the thread is never eixted, no matter what error occurs in the called method. Or some other way to keep track of live threads and make a new one when needed?
Comment: @tgkprog Indeed yes - the submitted code is wrapped in a custom `Runnable` that deals not only with `Exception` handling, but also with returning values from execution via the `Callable -> Future` API. If you want implementation details it's best just to look at [the source code](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/ThreadPoolExecutor.java).
Comment: This is not the whole story. ThreadPoolExecutor may allow threads to die and new threads are constructed in their place. See "Keep-alive times" in the documentation for ThreadPoolExecutor.
Comment: @cambunctious that's around the pooling mechanic itself - which is not really related to how a `Thread` is reused.
Comment: The answer to the question "How does ThreadPoolExecutor avoid creation of new threads?" should include "it doesn't".
Comment: I am interested to know what happens with thread in pool when task sleeps for some given time. Does thread go back to pool to overtake another task and when is time to 'wake up' task, another thread from pool will take over half-done task and try to finish it, or existing thread will be just taken until task is finished. I think it's the latter, just would like someone document that part too


How to configure nginx to use same port with same server name for 2 sites

Question: I have 2 sites in one debian machine. Currently one is running on port 443/80 and another one is running on port 8090. My requirement is to run both sites on 443 and if I enter site.com/1 - I should be redirected to site 1 and if I enter site.com/2 - I should be reached to site 2. How to achieve this with nginx?
I have tried proxying but the problem is - If I use the same port for both listen's it's ignoring stating already in use.
Answer: As per your requirement you want to run two sites with same domain. Lets say
<code>example.com/site1
example.com/site2
</code>
for this you need to modified the nginx configuration file as per the following template
open the nginx config file assosiated to example.com domain and add following code.
<code>    server {
      listen 80;
      server_name  example.com;
      return 301 https://example.com$request_uri;
    }

    server {
      listen 443 ssl http2;
      server_name example.com;
      modsecurity_transaction_id "example.com-$request_id";
      access_log           /var/log/nginx/access.log;
      error_log            /var/log/nginx/error.log;
      include              /etc/nginx/default.d/example.com/*.conf;
location / {
            try_files $uri $uri/ =404;
    }

    location /site1 {
            index index.php index.html index.htm;
            try_files $uri $uri/ /site1/index.php?q=$uri&$args;
    }

    location /site2 {
            index index.php index.html index.htm;
            try_files $uri $uri/ /site2/index.php?q=$uri&$args;
    }
}
</code>


Correct use of the Substitution Rule (or Integration by Substitution)

Question: When using the Substitution Rule (or Integration by Substitution), Stewart (Calculus: Early Transcendentals, 8e, 2016, p. 413) writes $$\int\sqrt{1+x^2}2x\,dx\overset{1}{=}\int\sqrt{u}\,du.$$
But strictly speaking, is $\overset{1}{=}$ correct?
I thought $u$ was just a dummy variable that can be replaced by any other letter, e.g. $x$. In which case, $$\int\sqrt{u}\,du=\int\sqrt{x}\,dx=\frac{2}{3}x^{3/2}+C,$$ which is clearly not equal to $\int\sqrt{1+x^2}2x\,dx$.
And if $\overset{1}{=}$ is wrong, then what is the correct way to use the Substitution Rule?
Comment: You cannot substitute by the same variable given in the question. If you do that you are assuming $1+x^2=x$ which is absolutely not right.
Comment: Let $u=x^2+1$. Then, $du=2xdx$.
Comment: @tomriddle99: So you're saying that in general, the following statement is false? $$\int\sqrt{u}\,du=\int\sqrt{x}\,dx$$
Comment: The above statement is correct (as the variable on the right of the integration sign can be replaced by any letter). However, changing $u$ to $x$ doesn't make the integral any easier to solve. The author of textbook did not set $u=x$ to get the RHS of $(1)$. They choose $u=x^2+1$.
Answer: $x$ is not a dummy variable, as that is an indefinite integral. You are likely thinking of definite integrals, in which case rewriting the integral using the same variable is fairly common, as it would indeed be a dummy variable:
$$\int_0^12x\sqrt{x^2+1}~\mathrm dx=\int_1^2\sqrt x~\mathrm dx$$
since the variables vanish after performing the integration. The same is not true for indefinite integrals, where the variable remains after integration:
$$\int2x\sqrt{x^2+1}~\mathrm dx=\frac23(x^2+1)^{3/2}+C_1=\frac23u^{3/2}+C_1=\int\sqrt u~\mathrm du\ne\int\sqrt x~\mathrm dx=\frac23x^{3/2}+C_2$$
where $u=x^2+1$.
Answer: The thing about variables in places like this is you need to be careful to keep track of the scope of their definitions.
In a definite integral the scope of the variable of integration is strictly confined to the integrand. For example, in
$$ \int_0^\pi x^2 \sin(x)\, dx $$
the variable $x$ that occurs in the $dx$ is the same $x$ that is found in $x^2\sin(x),$ but a completely distinct variable from any other occurrence of the letter $x$ anywhere. You can even replace $\pi$ with $x$ at the upper limit of the integral and it (technically) is unrelated to the $x$ in the $dx.$
In an equation such as
$$ \int x^2 \, dx = \frac13 x^3 + C, \tag1$$
however, while the $x$ is a dummy variable in the sense that you could just as well write
$$ \int y^2 \, dy = \frac13 y^3 + C \tag2$$
without changing the fundamental meaning of the equation,
the scope of $x$ is not strictly limited to the integrand.
It is closely related to (if not exactly the same as) the $x$ in $\frac13 x^3.$
After all, writing
$$ \int y^2 \, dy = \frac13 x^3 + C \tag3$$
(replacing $x$ with $y$ inside the integral but not elsewhere)
would not preserve the meaning of Equations $(1)$ and $(2)$;
in order to say the same thing as those equations do, you could give Equation $(3)$ and the stipulation that $y = x,$ but Equation $(3)$ by itself is not enough.
In short, when you use a dummy variable such as $x$ in writing an equation for the indefinite integral of a function, the scope of $x$ is not just the integrand within the integral; it's the entire equation. Hence
$$\int\sqrt{u}\,du = \int\sqrt{x}\,dx = \frac23 x^{3/2}+C $$
makes sense only if you stipulate that $u = x$; if you have in mind that $u = 1 + x^2$ then the first equality sign is not correct at all.
On the other hand, in a context where you have declared that $u = 1 + x^2,$ you can very well say that
$$\int\sqrt{u}\,du = \frac23 u^{3/2}+C,$$
and then, remembering that $u = 1 + x^2,$ you can substitute $1+x^2$ for the $u$ on the right-hand side.
You cannot just substitute $x$ for $u$ anywhere in that context, because then you would be mixing inconsistent relationships between $u$ and $x$:
implicitly saying that $u = 1 + x^2$ and $u = x$ at the same time.

For completness, I'll attempt to derive the substitution rule from the chain rule while taking proper care about notation.
The chain rule says that if $F(x) = G(u(x)),$ then
$$  F'(x) = \frac{d}{dx} G(u(x)) = G'(u(x))\, u'(x). $$
(You might see $G'(u(x))$ written $\frac{dG}{du}$ and $u'(x)$ written
$\frac{du}{dx},$ that is, in Leibniz notation, since that notation has some strong mnemonic properties in this usage.)
Therefore, given that $F(x) = G(u(x)),$
if we define a function $g = G',$
we have that $F(x)$ is an antiderivative of
\begin{align}
\int g(u(x))\, u'(x) \, dx
&= \int G'(u(x))\, u'(x) \, dx \\
&= \int F'(x)\, dx \\
&= F(x) + C \\
&= G(u(x)) + C.
\end{align}
The substitution rule is really just an application of this formula.
In order to find $\int f(x)\,dx,$
we first guess functions $g$ and $u$ such that
$f(x) = g(u(x))\,u'(x)$ and such that $g$ has a known antiderivative $G.$
Then we can define $F(x) = G(u(x))$ and apply the equations above to show that
$$ \int f(x)\,dx = G(u(x)) + C. $$
In writing out the substitution rule, however, one often uses a convenient notation in which we write $u$ instead of $u(x)$ and $du$ instead of $u'(x) \, dx.$
In that form the rule is much easier to remember:
$$ \int f(x)\,dx = \int g(u)\,du = G(u) + C = F(x) + C. $$
(There is a way to make the substitution of $du$ for $u'(x) \, dx$ more than just a notational gimmick, but that would take a lot more development and for our purposes here I think the notational gimmick is enough.)
The important thing here is that we did not just rename the dummy variable $x$;
we introduced a function of $x$ named $u.$
Because of the chain rule, we are able to integrate $g(u(x))\, u'(x)$
(with respect to the original variable $x$)
using a known formula for the antiderivative of $g,$
obtaining a compound function $G(u(x)),$ which we can then write in a form
that more clearly shows it as a function of $x.$
Keeping a consistent relationship between our uses of the symbols
$u$ and $x$ is essential to this process.

Instead of (or in addition to) this attempt to prove the substitution rule, one could also look at the answers to Proof of the substitution rule for integrals for the indefinite case
Answer: You are violating the transitive relation by:
$$\underbrace{\int\sqrt{1+x^2}2x\,dx}_{I_1}\overset{1}{=}\underbrace{\int\sqrt{u}\,du}_{I_2}=\underbrace{\int\sqrt{x}\,dx}_{I_3}.$$
If $I_1=I_2$ and $I_2=I_3$, then $I_1=I_3$, however, the last relation is obviously incorrect, consequently you can not claim $I_2=I_3$, because $u=1+x^2\ne x$.
In the Wikipedia article Integration by substitution, Example 3, it is stated:

An antiderivative for the substituted function can hopefully be determined; the original substitution between u and x is then undone.

So, you need to determine the antidervative of substituted function and then undo (i.e. return to $x$) the substitution between the $u$ and $x$.


If $a_n+b_n\rightarrow a$, then $b_n\rightarrow 0$

Question: I want to show for $a_n\rightarrow a$ and $b_n$ convergent, if $a_n+b_n\rightarrow a$, then $b_n\rightarrow 0$.
$\textbf{Pf.}$ Suppose $a_n+b_n\rightarrow a$. Then, for all $\epsilon>0$,  $\exists$ $N$ with $|a_n+b_n-a|<\epsilon$. When I use the triangle inequality, I can brea up the abs value and I end up with $|b_n|$ by itself and I don't know how to complete it.
Answer: Hint: prove that if $a_n\to a$ and $b_n\to b$ then $a_n+b_n\to a+b$. Then note that limits are unique (or prove this) and then $a+b=a$ and the result follows
Comment: @Moz, yes just take Ihf's approach. For any $\varepsilon > 0$, there exists $N_1 \in \mathbb N$ such that for all $n \geq N$, $|a_n + b_n - a| < \varepsilon$ and $N_2 > N_1$ such that $n > N_2$ implies $|a_n - a| < \varepsilon$. By the triangle inequality, $n > N_2$ implies $|b_n| = |a_n + b_n - a + a - a_n| \leq |a_n + b_n - a| + |a - a_n| < \frac{\varepsilon}{2} \cdot 2 = \varepsilon.$
Comment: Ok, that works. Is there a direct approach to the proof?
Answer: $b_n = (a_n+b_n) - a_n$ and so $\lim b_n = \lim (a_n+b_n) - \lim a_n= a-a=0$.
Answer: If you want to do this by definition, let $\varepsilon >0$ and $\varepsilon' = \frac{\varepsilon}{2}$. We know there exists integers $N,M$ such that $$\left|a_n-a\right| =  \left|a-a_n\right|  <\varepsilon' \quad \left|(a_m+b_m)-a\right|<\varepsilon'$$ Take $N \geq M$ without loss of generality so that  $\left|(a_n+b_n)-a\right|<\varepsilon'$. Then $$\begin{align}\varepsilon &= \varepsilon'+\varepsilon' \\ &> \left|a-a_n\right|+ \left|(a_n+b_n)-a\right| \\ &\geq   \left|(a-a_n)+[(a_n+b_n)-a]\right| \tag{Triangle Inequality} \\ &=  \left|b_n+(a-a)+(a_n-a_n)\right| \\ &=  \left|b_n-0\right|\end{align}$$


Developer comments in handlebars with no output in client side

Question: I'm using Express Handlebars as a template engine for node.
I know there's an option to add HTML comments with it, but is there a way to add developer comments that won't get printed on the final source ?
This is what I found:
{{! This comment will not be in the output }}

But looking for:
{{! This comment should only be visible in the source file, not in the client side }}

Similar to what can be done in PHP in a view:
<?php
/* Comment here */
?>

Comment: You could use a library to minimize the code removing the comments, or use a preprocessor to have them removed. There is also a npm package for this, https://www.npmjs.com/package/gulp-remove-html-comments
Comment: I'm currently using my own helper to remove them, but just wondering if it is possible somehow else.
Answer: The correct answer is:
{{!-- This comment won't get printed in this view --}}

https://handlebarsjs.com/guide/#template-comments
Answer: I ended up creating my own handlebars helper:
Handlebars.registerHelper('comment', function(whatever) {
  return '';
});

This way I can do:
{{comment 'this field is here to indicate...'}}
<input type="hidden" name="demo" value="4554">


When to use tied notes vs. an unconnected "laissez vibrer" (l.v.) tie?

Question: Consider this little passage on the orchestral bass drum (time is 4/4), where bars 62 and 63 are meant to be played identically:

I want to indicate clearly that the third note (second 8th) is meant to ring on through the last two beats of the bar. I can think of two ways to write this: using a tied note (bar 62), or using an LV tie[*] (bar 63).
My two-part question: A) Which is more appropriate to use here? B) Is there a rule, guideline or other way of determining when to use a tied note vs. when to use an LV tie?
(To clarify: The assumption here is that the next bar – such as bar 64 in the screencap above – has notes in it, as I know you do use LV ties to indicate an instrument should ring on across empty bars.)

[*] I'm not sure whether there's a more proper name for it; I get the name from Sibelius, which calls it an "l.v." tie (for "laissez vibrer", or let ring).
Comment: @ElementsinSpace Nope, just a li'l mistake I didn't notice.
Comment: I could be wrong , but I don't think I've ever come across a laissez vibrer tie in sheet music. First time I saw one was in the lilypond docs. Perhaps they are frequently used for some instruments/genres.
Comment: is there a reason you have the quavers unbeamed in the second instance?
Answer: They both equate to the same thing.  Since there are more notes in bar 64, it might look better to use the first example.
If bar 64 were empty, then the second example would be appropriate if you didn't mind how long it rang on for. With or without the letters l.v., any musician would understand the tie to mean let ring.
Comment: To Walter, it is pretty standard.  It is common to see it for pizzicato double bass too.  And no, there is no hard rule.  As I said, in the end they equate to the same thing.
Comment: Thanks for the reply. So basically, presuming the subsequent bar has notes, it's up to the composer to decide whether they prefer one or the other, and whilst the first may look neater, there's no hard rule about it?
Comment: _Any_ musician would understand the tie? It would confuse the hell out of most learners.
Comment: It's not the most obvious or common notation. I saw it in a score once and looked it up. It simply means to let an instrument (usually percussion or harp) resonate indefinitely, ignoring any silences that follow.
Comment: To Bob, that's why leaners have teachers.  The teacher is a musician.  The learner wants to 'become' a musician.
Answer: Restating the answer of Jomiddnz:
Tie to a note if its precise endpoint matters -- if at a particular point the percussionist should dampen the drum head, the pianist should release the keys, etc.
Tie to a rest or write l.v. to explicitly indicate a fade-out without a discernible ending.  The fondness of Debussy and Ravel for this may be how the French term came to dominance in the anglophone world.

When to use tied notes vs. an unconnected “laissez vibrer” (l.v.) tie?


Using Blazor WASM, I want to display the dimensions of a Browser window in a  when the window opens

Question: The solution is built using the Blazor WASM template. I can display the window dimensions when the window is resized ok.
I cannot see how to display the window dimensions when the window opens.
My HTML is in a .razor file.  The contents are:
@page "/termsAndConditions"
@inject IJSRuntime jsRuntime

        @code {

        }

My Javascript is in a .js file.  The file contains the following code that works fine:
//Display browser window dimensions as they change
window.addEventListener("resize", function () {
    document.getElementById("windowInnerWidth").innerHTML = "Width of inner window is: " + window.innerWidth;
});
window.addEventListener("resize", function () {
    document.getElementById("windowInnerHeight").innerHTML = "Height of inner window is: " + window.innerHeight;
});

I've tried many ways to display the window dimensions when the window first opens including:
window.addEventListener("open", function () {
    document.getElementById("windowInnerWidth").innerHTML = "Width of inner window is: " + window.innerWidth;
});

Nothing works.  Can anyone tell me what I'm doing wrong please?
Comment: I edited my answer based on your updated question.
Comment: and where is the Blazor part?
Comment: I've amended the example to show the full contents of the .razor page located in the Pages subdirectory of the solution..
Answer: try this:
window.addEventListener("load", function () {
  document.getElementById("windowInnerWidth").innerHTML = "Width of inner window is: " + window.innerWidth;
});

Update
(based on your edited question)
create a new function in your .js file like this:
function windowLoaded() {
  document.getElementById("windowInnerWidth").innerHTML = "Width of inner window is: " + window.innerWidth;
}

and add this to your .razor file:
@code {
  protected override Task OnAfterRenderAsync(bool firstRender)
  {
    jsRuntime.InvokeVoidAsync("windowLoaded");
    return base.OnAfterRenderAsync(firstRender);
  }
}

Comment: makes a function that return the values:https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-5.0, then override OnAfterRenderAsync: https://learn.microsoft.com/en-US/aspnet/core/blazor/components/lifecycle?view=aspnetcore-5.0#after-component-render , call the function and show the values
Comment: Thanks Saleh.  Unfortunately that doesn't work.  Any other ideas?
Comment: Thanks Saleh for your example.  I spent a day trying to solve this.
Thanks also to Eliseo for pointing me to the doco.


how to get a panda column returning the minimum values between another column and a min_val

Question: I whave a pandas dataframe and I would like to create a column that contains the minimum values between another column and a min_val. I created the simplified problem below:
import pandas as pd
import numpy as np

min_val = 0.5

np.random.seed(100)
df = pd.DataFrame(np.random.rand(10, 4), columns=['col{0}'.format(i) for i in range(1, 5)])

df['col_4_min'] = df['col4'].apply(lambda x: min(x, min_val))

df
    col1   col2   col3   col4  col_4_min
0 0.7425 0.6302 0.5818 0.0204     0.0204
1 0.2100 0.5447 0.7691 0.2507     0.2507
2 0.2859 0.8524 0.9750 0.8849     0.5000
3 0.3595 0.5989 0.3548 0.3402     0.3402
4 0.1781 0.2377 0.0449 0.5054     0.5000
5 0.3763 0.5928 0.6299 0.1426     0.1426
6 0.9338 0.9464 0.6023 0.3878     0.3878
7 0.3632 0.2043 0.2768 0.2465     0.2465
8 0.1736 0.9666 0.9570 0.5980     0.5000
9 0.7313 0.3404 0.0921 0.4635     0.4635

Problem with this method is that I will perform the calculation on a dataframe containing an incredibly high number of rows, so the calculation needs to be fast (and therefore apply isn't really privileged in my case)
Answer: Use np.minimum to compare a scalar (or array), with your col
In [94]:

min_val = 0.5
df['col_4_min'] = np.minimum(min_val, df['col4'].values)
df
Out[94]:
     col1    col2    col3    col4  col_4_min
0  0.7425  0.6302  0.5818  0.0204     0.0204
1  0.2100  0.5447  0.7691  0.2507     0.2507
2  0.2859  0.8524  0.9750  0.8849     0.5000
3  0.3595  0.5989  0.3548  0.3402     0.3402
4  0.1781  0.2377  0.0449  0.5054     0.5000
5  0.3763  0.5928  0.6299  0.1426     0.1426
6  0.9338  0.9464  0.6023  0.3878     0.3878
7  0.3632  0.2043  0.2768  0.2465     0.2465
8  0.1736  0.9666  0.9570  0.5980     0.5000
9  0.7313  0.3404  0.0921  0.4635     0.4635

Thanks to @Divakar that calling df['col4'].values will speed this up even more than using clip
Comment: Thank you both guys. @EdChum there is something I still don`t understand. I extended my problem to a min-max, so the clip method form pandas was performing well. However, I noticed a clip method under numpy. Testing for speed, both methods (pd.clip and np.clip) yield similar results for speed. Is it possible that the difference in speed between your answer (np.minimum) and @StevenG answer (pd.clip(upper)) is just due to the method itself?
Comment: And some more speedup with the array data : `df['col4'].values`.
Comment: this is actually faster for some reason
Comment: @StevenG the numpy methods will typically work on numpy arrays without any error handling, the pandas version have more built-in error handling which is why they are typically slower, additionally when the data is a numpy array it can just re-use this for the block array, for the other case it needs to allocate and copy the values
Comment: I understand, but still, assuming that your col is of dtype float, I would be fine with 10% slower, but the numpy approach is 2 time faster... that's just insane
Comment: @StevenG that still doesn't surprise me, the pandas method will be check the dtype, whether there are missing values, homogenous dtypes, etc. The numpy method just needs to make a boolean mask against the array and generate the numpy array with the appropriate values and these can be handled much faster by pandas with little overhead because of the numpy restrictions
Comment: There's probably some implementation detail as to why `np.clip` is the same speed as `pd.clip` which `np.minimum` doesn't need to care about
Comment: @Divakar that's true, have edited, will attribute also
Answer: use clip()
df['col_4_min'] = df['col4'].clip(upper=0.5)


Checking if operator is isometrics

Question: Let's consider the operator
$$F: C([0,1]) \rightarrow l^\infty$$
$$F(g) = (g(q_n))$$
where $\{q_n\} = \Bbb Q \cap [0,1]$
I want to check whether this operator is well defined, bounded and if it's an isometry.
Bound of this operator is straightforward:
$$|F(q_n)| = |g(q_n)| \le \|g\|$$
What about isometrics (i.e. $\|g\|_\infty = \|T(g)\|_\infty$) ?
$$\|g\|_\infty = \sup\{|g(x)| , x \in [0,1]\}$$
$$\|T(g)\|=\|g(q_n)\| = \sup\{|g(x)|, x \in \Bbb Q \cap [0,1]\}$$
And, in my opinio,n those two expressions are equal, since $g$ is a continuous function and $\Bbb Q$ is dense, so this supremum, even if it's not reached on rational number, it's not a problem.
Am I thinking correctly ? Is this justification sufficient ?
Comment: Please rewrite the first paragraph so it makes sense.
Answer: It should be $\|F(g)\|=\sup_{n\geq 1}|g(q_{n})|$.
We know that $\|g\|_{\infty}=\max_{[0,1]}|g|=|g(x_{0})|$. Now pick a sequence $(r_{n})\subseteq\mathbb{Q}\cap[0,1]$ such that $|g(r_{n})|\rightarrow|g(x_{0})|$, then $|g(x_{0})|=\lim_{n}|g(r_{n})|\leq\sup_{n\geq 1}|g(q_{n})|$.

Checking if operator is isometrics


R-squared and variance relation

Question: According to Wiki:
https://en.wikipedia.org/wiki/Fraction_of_variance_unexplained
$1 - R^2 = VAR_{err}/VAR_{tot}$
Where $VAR_{err} = \sum_{i = 1}^N (y_i - \hat{y}_i)^2$
is the variance of the residuals.
I don't see how this is correct, unless the residuals have mean zero. To see this, define the residuals:
$e_i = y_i - \hat{y}_i$
The variance of the residuals is:
$\sum_{i = 1}^N (e_i - \bar{e}_i)^2 =
\sum_{i = 1}^N (y_i - \hat{y}_i - \bar{e}_i)^2 $
Do you disagree or is Wikipedia wrong?
Answer: Note that in OLS regression with an intercept term, due to the "first order condition", when you take derivative w.r.t. $\beta_0$ you have
$$
-2\sum_{i=1}^n (y_i - \hat{\beta}_0 - \hat{\beta}_1x_{1i} - \cdots \hat{\beta}_px_{pi}) = -2\sum e_i =0,
$$
hence
$$
\bar{e}_n = 0,
$$
thus
$$
\hat{\sigma}^2 = \frac{1}{n}\sum(e_i - \bar{e})^2 = \frac{\sum e_i ^ 2}{n}.
$$
Comment: Thanks for the answer, but this not only hold for linear models? I think Wiki is wrong since it treats the more general case, but still imposes this assumption.
Comment: @hans The residuals have zero mean for any model with an intercept term and least-squares estimation.

R-squared and variance relation


Find $\lim_{n\to\infty} \frac{n^{1296}}{6^n}$

Question: I need to find $$\lim_{n\to\infty} \frac{n^{1296}}{6^n}$$ I have nothing yet, maybe sandwich theorem but I'm not sure.
Thanks in advance  for help.
Comment: L'Hopitale rule 1296 times?
Comment: @ShirMoshe More like this : create the statement $\lim_{n \to \infty}\frac{n^k}{6^n} = 0$ for all integers $k$, to prove by mathematical induction. Prove the base case, and then use L'Hopital for the inductive case. This means you don't need to do L'Hopital 1296 times.
Comment: @ShirMoshe If you are not willing to try what other suggests, what the point of posting the question? A-Level Student's answer solves the problem in that way.
Comment: Please share your thoughts on this limit problem here. Posting questions which are just problem statements is discouraged here.
Comment: See for example https://math.stackexchange.com/q/55468/42969.
Comment: The example was helpful tank you
Comment: FWIW, $n^{1296}=6^n$ at $n\approx 1.0013854 \text{ & } 6331.3374$
Comment: @TeresaLisbon, there is an alternative way, by taking the power of 1296 out common from the whole brakett........then apply l's hopital only once (as I cannot post it as an answer, hence this comment)
Answer: Let $$L=\lim_{n\to\infty}\frac{n^{1296}}{6^n}$$
Applying L' Hopital's rule once, we see that
$$L=\lim_{n\to\infty}\frac{1296n^{1295}}{6^n\ln6}$$
We can keep on applying L' Hopital's rule (as we always will have a indeterminate form), until we get
$$L=\lim_{n\to\infty}\frac{1296!~n}{6^n(\ln6)^{1295}}$$
Applying this once more we are left with
$$L=\lim_{n\to\infty}\frac{1296!}{6^n(\ln6)^{1296}}=0$$
So we see that $L=0$.
I hope that was helpful. If you have any questions please don't hesitate to ask :)


SQL: Mark which WHERE condition matched

Question: This is a theoretical question, I was wondering if there is a good way of finding out which condition in the WHERE statements matched.
Say I have a query like this:
SELECT * FROM table WHERE
    COND1 OR
    (COND2 AND COND3) OR
    COND4

Is there any way of knowing which of the conditions made a given row match (or unmatch)?

One solution i thought of was adding a CASE clause, to the SELECT, and rerunning all the WHERE conditions for that row:
SELECT *, which_cond = CASE .... END CASE ...

Answer: CASE is a possibility. But shorter to write would be IF() (at least with MySQL):
SELECT *, IF(COND2, 1, 0) AS cond2, IF(COND3, 1, 0) as cond3 ...

and every cond* matched if its value is 1.
Of course it does not make sense to check whether COND1 matches or not. For all results you get back, COND1 was true. So IF(COND1, 1, 0) will always return 1 (in your example).
Update:
Again at least for MySQL, I discovered, that the following is sufficient if you only want to get either 1 or 0 as result:
SELECT *, COND2 AS cond2, COND3 as cond3 ...

and with respect to Mark's answer, you can avoid writing the conditions twice, if you use HAVING instead of WHERE (HAVING as access to aliases):
SELECT *, COND2 AS cond2, COND3 as cond3
FROM table
HAVING COND1 AND (cond2 OR cond3)

(note: uppercase means the actual condition expression and lowercase is the alias name)
Update 2:
Well it changes not that much: you only have to check conditions that are connected via OR in your updated version it would be sufficient to check whether COND2 is true or not. If so, then COND3 is also true and vice versa.
SELECT *, COND1 AS cond1, COND2 as cond2, COND4 as cond4
FROM table
HAVING cond1 OR (cond2 AND COND3) OR cond4

I think the point is clear.
Comment: that's an interesting solution
Comment: +1: "it does not make sense to check whether COND1 matches or not"  Reasoning about the query is more helpful than hacking around.  Run two separate queries for COND1 AND COND2 as well as COND1 and COND3 and you'll learn a lot.
Answer: Your method works but it requires you to type out all the conditions twice, and if they are complicated expressions that could be annoying to do. Duplication of code also leads to bugs when the conditions need to be changed and you forget to update both places. I'd suggest instead using a subselect to evaluate the conditions and than using aliases from there on:
SELECT *,
       CASE WHEN Cond1 AND Cond2 THEN 'Foo'
            ELSE 'Bar'
       END AS WhichCondition
FROM (SELECT *,
           (...SQL FOR COND1...) AS Cond1,
           (...SQL FOR COND2...) AS Cond2,
           (...SQL FOR COND3...) AS Cond3
           FROM table) AS T1
WHERE Cond1 AND (Cond2 OR Cond3)

On SQL Server and Oracle you could use a CTE instead of a subquery. I didn't do this because you also used the MySql tag.
Comment: @Mark Can you pls add the CTE solution, the mysql tag is there cause because i was wondering if different engines had some built-in solution for this

SQL: Mark which WHERE condition matched


Is this a valid mathematical model (MILP)?

Question: Is it ok to calculate values in one set of constraint and than using it for another in MILP model. Here Z and Y are binary variable.
Comment: It would help to add context to your question, i.e. what the variables $Z_{j,q}$ and $Y_{j,k,q}$ are supposed to represent.
Answer: No, in a mathematical programming model the limits of summation cannot be variables. (In a constraint programming formulation, you can sum a variable number of variables.) One workaround (assuming the $Z_{j,q}$ are nonnegative integers) is the following:

introduce binary variables $x_{1,q},\dots, x_{K_q,q}$, where $K_q$ is the maximum possible value of $\sum_{j=1}^M Z_{j,q}$;
constrain the new variables so that $x_{k,q}=1 \iff \sum_{j=1}^M Z_{j,q}\ge k$;
change your second constraint to $\sum_{k=1}^{K_q} Y_{j,k,q}x_{k,q} = 1$; and
linearize the product in that constraint (which is fairly straightforward if the $Y$ variables are bounded).


Finding the sum of a convergent series

Question: I am trying to find find the value of $\sum_{n=2}^{\infty}n{\frac1{2^{n-1}}}$
I started by substituting m=n-1 to get $\sum_{m=1}^{\infty}(m+1){\frac1{2^{m}}}$ but I am not sure where to go from here.
Answer: Hint:
$$S:=\frac22+\frac34+\frac48+\frac5{16}+\cdots$$
and
$$S=\frac{1+1}2+\frac{2+1}4+\frac{3+1}8+\frac{4+1}{16}+\cdots\\
=\frac12+\frac12\left(\frac22+\frac34+\frac48+\frac5{16}+\cdots\right)+\left(\frac12+\frac14+\frac18+\frac1{16}+\cdots\right)$$
Comment: I like this answer the best out of the two. It helped me see the convergent series then I can use the formula for convergent geometric series to find the values of the infinite sums. Thanks!

Finding the sum of a convergent series


Telerik-grid paging and sorting when using an external data source

Question: I am experimenting with using an external data source with a Telerik Grid using their Twitter search sample as my guide
http://demos.telerik.com/aspnet-mvc/razor/grid/externalservicetwitter
I have got their sample running but cannot get paging and sorting to work.
In the sample they set-up the grid server side using the code
<code>@(Html.Telerik().Grid<TwitterItem>()
    .Name("Grid")
    .Columns(columns =>
    {
        columns.Template(o => { }).Title("Author").Width(100);
        columns.Template(o => { }).Title("Avatar").Width(80);
        columns.Bound(o => o.text).Title("Post");
    })
    .ClientEvents(events => events
        .OnDataBinding("onDataBinding")
        .OnRowDataBound("onRowDataBound")
    )
    .Scrollable(scrolling=>scrolling.Height(400)))
</code>
So I added .Pageable and .Sortable to the construct like in the other samples but this seems to make no difference
<code>@(Html.Telerik().Grid<TwitterItem>()
    .Name("Grid")
    .Columns(columns =>
    {
        columns.Template(o => { }).Title("Author").Width(100);
        columns.Template(o => { }).Title("Avatar").Width(80);
        columns.Bound(o => o.text).Title("Post");
    })
    .ClientEvents(events => events
        .OnDataBinding("onDataBinding")
        .OnRowDataBound("onRowDataBound")
    )
    .Scrollable(scrolling=>scrolling.Height(400))
    .Pageable()
    .Sortable()
</code>
)
Should this be working?  Is there something else I should be doing?
Comment: When I try this with .Pageable added, I get the paging status bar at the bottom, but the animated gif in the bottom left corner keeps spinning like the data has not finished loading. And the paging status text says, "Displaying items 0 - 0 of 0". When I try with .Sortable added, the Post column acts like it is sorting, but doesn't actually sort. The Author and Avatar columns don't sort because they are Template columns. It seems that because of the way the data loads, there is a problem with paging and sorting.
Answer: I am having the same problem.
My challenge is that the users want to retreive repeatedly for different criteria and they expect the results to accumulate in the grid until they clear the grid.  I am building this capability.  I got the accumulation to work, but along the way something is causing the "Displaying items 0 - 0 of 0".
This question has been sitting out here for a long time.  It makes me feel discouraged.
My theory is that the custom binding messes up the other settings.
Joe


Having duplicate entry error with Panelizer module

Question: I installed the Panelizer module and enabled it for a specific content type. When trying to add new content, I get a duplicate entry error as follows :

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry 'node-196-197-page_manager' for key 'PRIMARY': INSERT
  INTO {panelizer_entity} (entity_type, entity_id, revision_id,
  no_blocks, css_id, pipeline, did, view_mode, css_class, title_element,
  link_to_entity) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4,
  :db_insert_placeholder_5, :db_insert_placeholder_6,
  :db_insert_placeholder_7, :db_insert_placeholder_8,
  :db_insert_placeholder_9, :db_insert_placeholder_10); Array (
  [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 196
  [:db_insert_placeholder_2] => 197 [:db_insert_placeholder_3] => 0
  [:db_insert_placeholder_4] => [:db_insert_placeholder_5] => standard
  [:db_insert_placeholder_6] => 0 [:db_insert_placeholder_7] =>
  page_manager [:db_insert_placeholder_8] => [:db_insert_placeholder_9]
  => H2 [:db_insert_placeholder_10] => 1 ) in drupal_write_record() (line 6888 of
  /Library/WebServer/Documents/www/jkl/includes/common.inc).

Any insight?
Answer: Looks like a known bug:  unable to edit nodes with default panelizer state.
Try the patches in the above issue.  Looks like it might be useful to chip in there with your issue also!
Answer: Thanks Chapabu. I've been through those, and tried merlinofchaos's #7 patch and get this in my apache error log : Fatal error: Declaration of PanelizerEntityNode::get_default_display() must be compatible with that of PanelizerEntityInterface::get_default_display() in /Library/WebServer/Documents/www/jkl/sites/all/modules/contrib/panelizer/plugins/entity/PanelizerEntityNode.class.php on line 12 The other patches there don't work at all. :/


Difference between two multi-variable datasets

Question: I have multiple activities that a person performs, and the corresponding multidimensional values [$x$, $y$, $z$ - coordinates] for two devices and their readings.
I need to find the difference between the readings from the two devices to tell which particular activity has the highest difference in reading between the devices.
Dataset1: The readings corresponding to one device https://i.stack.imgur.com/FtBUl.png

Dataset2: The readings corresponding to the other device https://i.stack.imgur.com/0WLmk.png

I am looking for a systematic way to approach this problem. I could find references to statistical differences such as KL divergence etc and also tests such as ANOVA. Could someone let me know how to methodologically approach such a problem?
Comment: Reading your first comment to my answer below, and reexamining your data, there are several things that are not clear to me:  (1)  Is the information in Dataset1 from Device 1 and the information in Dataset2 from Device 2?  (2)  do row numbers from Dataset1 correspond to the row numbers from Dataset2?  In other words, is there a matching up of the row 0 in Dataset1 with row0 in Datset2 for example (e.g. does, say, row 3 in both datasets correspond to unique subject number 3 that was measured on both devices and that, row 4 is a different subject also measured on both devices)?
Comment: (continued) (3) is the timestamp relevant in your analysis?  In other words, is it possible that the time the experiment was conducted could have some bearing on the results/measurements you made or is this irrelevant or unlikely?
Comment: @StatsStudent Yes, the two datasets are information from the two devices. No there is no correspondence between the rows, we have a set of rows that belong to a subject but no matching between individual rows. No, the timestamp is irrelevant.

I am looking to comment on the difference between the two readings from the two datasets as whole, i.e all the rows in the 1st data set correspond to a multi dimensional distribution of points (3-d cluster) and how different it is from 2nd dataset. (some metric)
Comment: OK. Thanks for the clarification.  Given the updated information that you told, me I think you're best best is, in fact, to pursue the independent samples Hotelling's $T^2$ multivariate test.  I've updated my answer below with additional details for you.
Comment: @StatsStudent Thank you for your answer.

I also want to know if doing a KS test on each axis and then taking a mean of the KS value at each of the axes is the right approach or not?
Comment: You don't really want to do that as you'll be doing multiple testing which will suffer from Type I error inflation.  Also, if you found my answer acceptable, please accept it by clicking the green check mark, rather than upvoting.  This helps encourage other users on the site to answer questions. Thanks!
Comment: @StatsStudent have accepted the answer! I, however, do not fully follow the reasoning behind Type1 error inflation. Say I am to calculate the Wasserstein distance for each axis and take a mean for the distance obtained on each axis.
Comment: Thanks.  I'm not sure I's clear what you are proposing.  What might be a good idea is to open another question with your proposed procedure for using the Wassterstein distance.  I was under the impression you were proposing computing means on each axis and testing each of them individually.  By doing so, you will have increased the chances of finding a significant result above whatever you set your initial $\alpha$ level to.
Answer: Are you looking for a way to test if there is a difference in the mean readings between the two devices readings en masse?  If so, I'd recommend using a simple multivariate test called the Multivariate Paired Hotelling's $T$-test.  You can see how this test works here: https://online.stat.psu.edu/stat505/lesson/7/7.1/7.1.8.
Alternatively, assuming your data meets the necessary assumptions, you could simply analyze this data using a simple linear mixed effects model where each subject is treated as a random effect and the device is a fixed effect (this is essentially a special case of a mixed effects ANOVA, so your intuition was pointing you in the right direction).  Additional information about this approach can be found here:  https://web.stanford.edu/class/psych252/section/Mixed_models_tutorial.html
Another approach that might be appropriate in this case is to fit a Generalized Estimating Equations model, which is similar to a linear mixed effects model, but the interpretation is slightly different.  You can find more information about this approach here:  https://online.stat.psu.edu/stat504/node/180/.  See my previous answer in this question to understand the difference between this method and the linear mixed effects model:  Conditional vs. Marginal models
Best of luck to you!
Update Based on Additional Information from Comments
Thanks for providing some clarifying details in the comments.  Based on what you've now told me, I think your best bet is to simply carry out a Two-Sample Hotelling $T^2$-Test.  Basically what you want to do is obtain averages of each of your $x$, $y$, and $z$ variables in each dataset separately.  The means for dataset1 and dataset2 will be in vectors $X_1$ and $X_1$ respectively.  Then you'll carry out Hotelling's $T^2$-Test.  In R, this can simply be done with the following:
#Install the package if you dont' have it already installed
#install.packages("rrcov")
library(rrcov)
x1<-c(-0.364761, -0.879730, 2.001495, 0.450623, -2.164352)
y1<-c(8.793503, 9.768784, 11.109070, 12.651642, 13.928436)
z1<-c(1.055084, 1.016998, 2.619156, 0.184555, -4.422485)
x2<-c(7.091625, 4.972757, 3.253720, 2.801216, 3.770868)
y2<-c(-0.591667, -0.158317, -0.191835, -0.155922, -1.051354)
z2<-c(8.195502, 6.696732, 6.107758, 5.997625, 7.731027)

#Create the two datasets
X_1<-data.frame(x1,y1, z1)
X_2<-data.frame(x2,y2,z2)

#Carry out Hotellings T^2 test
T2.test(x=X_1, y=X_2)

Which returns the results:
    Two-sample Hotelling test

data:  X_1 and X_2
T2 = 305.627, F = 76.407, df1 = 3, df2 = 6, p-value = 3.596e-05
alternative hypothesis: true difference in mean vectors is not equal to (0,0,0)
sample estimates:
                     x1        y1        z1
mean x-vector -0.191345 11.250287 0.0906616
mean y-vector  4.378037 -0.429819 6.9457288

Since the $p$-value of this test is quite small (p-value = 3.596e-05), there is sufficient evidence to reject the null hypothesis of: \begin{eqnarray*}
H_{0}:\boldsymbol{\mu_{1}} & = & \boldsymbol{\mu_{2}}
\end{eqnarray*}
or equivalently, if we denote the means of $x$, $y$, and $z$ from the $i$th dataset as $\mu_{ix}$, $\mu_{iy}$, and $\mu_{iz}$ respectively, for $i=1,2$, the null hypothsis:
\begin{eqnarray*}
H_{0}=\begin{pmatrix}\mu_{1x}\\
\mu_{1y}\\
\mu_{1z}
\end{pmatrix} & = & \begin{pmatrix}\mu_{2x}\\
\mu_{2y}\\
\mu_{2z}
\end{pmatrix}
\end{eqnarray*}
and conclude there is sufficient evidence, based on this data, that the two measuring devices are measuring differently.
I hope this help!
Comment: Thank you for your answer! The intent of the question is to identify for which particular activity are the two devices giving completely different readings, and give a relative ordering among these activities.

How about taking the centroid of each device on x,y,z axis and just calculating the euclidean distance between the two centroids for each device?

I am fairly new to the same, and would love to understand a systematic approach to the same.