Psychology Of Key Preferences

Question: I'm a layperson with regards to all things music.  I have some experience with the guitar and took a semester long music theory class in high school, but aside from that and some stuff I've heard from watching Adam Neely and Rick Beato I know nothing, I do however have perfect pitch.
I know different keys tend to take on different sounds and moods depending on the instruments used and the structure of the song, but there are certain keys that will make me feel certain ways no matter the facts about the song, performance, etc.
For instance F major always makes me feel incredibly overwhelmed and upset, to the point where it can be a trigger for depressive and intrusive thoughts no matter how I was feeling before. E minor and F minor tend to calm me down no matter what state I'm in, C minor (in classical music mostly) makes me irritated, like having an itch I can't reach etc.
Is there any psychological and/or music-theory based explanation for why this happens?  A lot of my friends who are much more musically developed than I am tend to have likes and dislikes when it comes to certain keys and progressions but so far as I know I'm the only person I've met who overreacts like this.  It's to the point where I'm trying to write a script that will automatically comb through the songs in my library and automatically transpose everything to keys I can stand.
Comment: Frank Zappa: "You have to like D minor a lot to play in our band". Spinal Tap: "D minor is the saddest of all keys".
Comment: I'm intrigued--how would your script handle music that changes keys? For example, the first movement of Beethoven's Appassionata Sonata is in F minor overall, which would be fine, except a significant portion of it later is in F major, which I'm fairly sure you are programming your script to transpose away from.
Comment: There might be some psychology to this but there's no music theory related to it. That's not part of what music theory is about.
Comment: There were feelings or moods assigned to keys before equal temperament became common, because the nature of each was detectable to a trained ear, even without perfect pitch. But equal temperament makes each key indistinguishable for a listener who only has relative pitch. Since you have perfect pitch, you might be describing a synesthetic phenomenon. That's psychological; not musical.
Comment: Avoid to play F major and C, prefer playing e- and f- minor.
Comment: Did you listen to traumatically bad music in F major before? Otherwise, I can't explain why F major would make you so upset. I personally find F major to be noticeably calm compared to other major keys. (I also have perfect pitch.)
Comment: Had a fleeting thought that there may be some connection with resonance of body parts.
Comment: @Dekkadeci that's a good point, sometimes if I'm playing a song and manually transposing it to a different key but that results in another key change I don't like I'll just fudge that part.  That or in the case your describing I think I'd try to transpose it to a key where I really like both the minor and its parallel major, so for the first movement of that sonata I might try to have it in A minor and A major.
Comment: Also @Dekkadeci I'm not sure if there are experience that could explain the F major dislike.  I remember feeling that way about it since I was a small child, even if I didn't recognize which key it was back then.  Although it could be because of the music they play in stores?  The kind of stuff that's really maudlin and arrhythmic that gets people upset so they buy more stuff supposedly.  That and I tend to hate stores/areas with large amounts of people in general so given your idea I think that might fit.
Comment: @LeeRoyce-Jenkins - You might need to try another transposition if your result's use of C major and C minor irritates you too much. (The original 1st movement of Beethoven's Appassionata Sonata starts in F minor, then goes to A flat major into A flat minor, then arguably goes to E major, E minor, C minor, A flat major again, D flat major, B flat minor, G flat major,  and a chromatic slide in rapid sequence, then back to F minor, F major, F minor, D flat major, and F minor.
Comment: @Dekkadeci good point, depending on the context the offending key can be less irritating so a script probably would be tough since it might just end up being on a case by case basis.  Can't win 'em all I suppose.
Comment: Two related questions:
(1) [Why do I hear characters to keys in equal temperament?](https://music.stackexchange.com/questions/93292/why-do-i-hear-characters-to-keys-in-equal-temperament)
(2) [Is there any objective evidence that different keys "feel different" or have different moods?](https://music.stackexchange.com/questions/93535/is-there-any-objective-evidence-that-different-keys-feel-different-or-have-dif)
Answer: The term you have too look up is:
Characteristics of Musical Keys
There has always been a great discussion about the characteristics of scale  and keys (which are the basic of chords) by different composers.f
http://biteyourownelbow.com/keychar.htm
There is objective evidence that most requiems are written in d- minor. The modi and temperature are the main factors, but also the conditioning will play a role. There's a great amount of subjectivity in this discussion.
https://www.wmich.edu/mus-theo/courses/keys.html
Ernst Kurth was one of the first who was occupied with music psychology. "This system is approached from three perspectives and three questions: a) chordal fusion, or how it is that we sense simultaneous tones as harmonious ; b) chordal tension, or why we feel tension when hearing simultaneous tones; and c) chordal movement, or what underlying principles govern our responses to the succession of chords."
(Daphne Tan Dissertation downloadable pdf)
for better understanding:
How does Music Affect your brain?
"Music psychology, which is a branch of musicology, aims to explain the understanding the effects of musical behavior. Many sound frequencies, called pitch, can form a melody. Melody is  the part of music that is memorable and music that doesn't have much of a melody often lacks direction.Corresponding harmonies can produce a variety of effects on a song. Harmonies can range from bright and uplifting to dark and depressing."
https://mass001.wordpress.com/2017/04/03/the-psychology-of-musicology-the-effects-of-classical-music-on-the-brain/
Comment: Ya know what, maybe my notion that A flat major is the most morose of all major keys comes from A flat major pieces actually being more depressing overall. (I'm an avid classical music fan, which would amplify these trends in music in certain keys I could notice.)
Comment: Maybe you're  traing perfect pitch of a' 440 as I did some years ago. Then the bells of the cows  ringing on a A flat got me crazy ...
Comment: I wonder what the music psychology is of certain intervals, progressions, and harmponies are.  Considering in a lot of classical music regardless of the key I don't feel particularly moved by any of it.  But songs in minor keys with a lot 2nd, 6th, 7th intervals and sustained chords tend to hit hard.

Psychology Of Key Preferences


Why is NTP out of sync on servers that are hosted on Digital Ocean since the daylight saving time?

Question: Since the daylight saving time the Sensu monitor indicates that the NTP of multiple servers that run on Digital Ocean (DO) are out of sync (12.345404ms-98.338222ms):
CheckNTP WARNING: NTP offset by 34.073039ms

Discussion

Perhaps the NTP configuration is incorrect?
The NTP configuration was deviating, but now the same configuration has been applied using Geerlingguy's ntp role.
What will happen if the NTP server has been restarted?
The monitor indicated that the NTP has been synced, but in a while the issue occurs again.
What will happen if the NTP server will be stopped, the time is set manually and the ntp server will be started again?
Identical to three.
Perhaps the issue is related to the DO platform?
Unknown. No solutions were found on the internet.
What will happen if the nearest location while be chosen as a timeserver?
server 0.nl.pool.ntp.org iburst
server 1.nl.pool.ntp.org iburst
server 2.nl.pool.ntp.org iburst
server 3.nl.pool.ntp.org iburst

When the NTP server was restarted, the time was synced and later on the time was out sync again.
Do the droplets sync and later on run out of sync?

Yes that seems to be the case:
Answer: NTP (and SNTP) do not provide information about timezones/daylight saving. Rather, it provides a precise UTC reference clock that need to be interpreted by the client to be shown in correct local times. This means that daylight saving should have absolutely no effects on NTP clock drift/skew.
Some suggestions:

what NTP client are you using? RHEL7 ships with chrony, which I found to be somewhat less accurate than plain old ntpd + ntpdate

remove the iburst option from your ntp config file and restart your NTP client

be sure to use NTP servers which are reachable with low RTT (ie: you can ping fast)

check for network congestion

be sure to read NTP manpage as it really has some great documentation
Answer: Note that from my experience, all VPN systems (not just DigitalOcean ones) make use of the master clock, a.k.a., the clock present on the running the host server. That server is already synchronized as expected (probably with NTP) and I have not seen a VPN which was not already synchronized even without NTP running.
The one issue I've noticed also is that running NTP is more often going to cause issues than the other way around (not running NTP). This is because the CPU clock may not be 100% reserved for your VPN and thus timers are not going to be as precised as expected. NTP needs the accuracy of those timers to know how to skew the system clock. However, I think that, at DigitalOcean, you always get CPUs that are reserved to you. Therefore, the timers work as expected. On my server at home where I run VirtualBox, I get completely skewed time with the CPU timers... because VirtualBox does not reserve a specific set of CPUs for each VPN it runs.


How to make Multi select without using bootstrap and with only pure css?

Question: Now, I am making a multi-select component that has a heading inside the select box.
I made the  tag inside the div component and every item is  tag.
This is my code.
import React, { useState, useRef, useEffect } from "react";
import "./style.css";

function Select({ title, data, changeSelect, selectedItem }) {
  const [categories, setCategories] = useState(data);
  const [selectedItems, setSelectedItems] = useState([]);

  const wrapperRef = useRef(null);
  const [isVisible, setIsVisible] = useState(false);

  const handleClickOutside = event => {
    if (wrapperRef.current && !wrapperRef.current.contains(event.target)) {
      setIsVisible(false);
    }
  };
  useEffect(() => {
    document.addEventListener("click", handleClickOutside, false);
    return () => {
      document.removeEventListener("click", handleClickOutside, false);
    };
  }, []);

  const selectItem = (item) => {
    if (selectedItems.indexOf(item) === -1) {
      if (categories.length === 1) {
      }
      setCategories((prevCategories) =>
        prevCategories.filter((value) => value !== item)
      );
      setSelectedItems((prevItems) => [...prevItems, item]);
    }
  };

  const removeItem = (item) => {
    setSelectedItems((items) => items.filter((value) => value !== item));
    setCategories((prevCategories) => [...prevCategories, item]);
  };

  return (

      {/* {title} */}

        <title>{title}</title>

          {selectedItems.length > 0 &&
            selectedItems.map((item) => (
               removeItem(item)}>{item}
            ))}

      <div className={`dropDown-wrapper ${isVisible ? "active" : ""}`}>

          {categories.length > 0 &&
            categories.map((item) => (

 selectItem(item)}>{item}

            ))}
          <li
            style={{
              display: `${categories.length === 0 ? "block" : "none"}`,
            }}
          >
            No Result

  );
}

export default Select;

When I click the select button, it shows a dropdown box.
The most important thing here is that I used react-onclickoutside npm library to get the click event outside the current element but it is not working well.
I used several libraries but all of them do not work at all.
PS: I have to use 3 multi-selects.

react: 16.14.0
react-scripts: 3.4.3
react-onclickoutside: 6.10.0
Answer: I had a solution by using another npm library and stopPropagation() function.
import React, { useState, useRef, useEffect } from "react";
import ClickOutside from "react-click-outside";
import "./style.css";

function Select({ title, data, changeSelect, selectedItem }) {
  const [categories, setCategories] = useState(data);
  const [selectedItems, setSelectedItems] = useState([]);

  const [isActive, setIsActive] = useState(false);

  // const onClickSelect = (e, active) => {
  //   setIsActive(active);
  //   console.log(e.target.value, "asdfasdfasdfs");
  // };

  const selectItem = (item) => {
    if (selectedItems.indexOf(item) === -1) {
      if (categories.length === 1) {
        setIsActive(false);
      }
      setCategories((prevCategories) =>
        prevCategories.filter((value) => value !== item)
      );
      setSelectedItems((prevItems) => [...prevItems, item]);
    }
  };

  const removeItem = (e, item) => {
    e.stopPropagation();
    setSelectedItems((items) => items.filter((value) => value !== item));
    setCategories((prevCategories) => [...prevCategories, item]);
  };

  return (
    <ClickOutside onClickOutside={() => setIsActive(false)}>

 setIsActive(!isActive)}>

          <title>{title}</title>

            {selectedItems.length > 0 &&
              selectedItems.map((item) => (
                 removeItem(e, item)}>{item}
              ))}

        <div className={`dropDown-wrapper ${isActive ? "active" : ""}`}>

            {categories.length > 0 &&
              categories.map((item) => (

 selectItem(item)}>{item}

              ))}
            <li
              style={{
                display: `${categories.length === 0 ? "block" : "none"}`,
              }}
            >
              No Result

    </ClickOutside>
  );
}

export default Select;

I hope this will help you who has same issue with me.


Regarding the calculation of $p$ values in one tailed tests

Question: In two tailed hypothesis tests, under symmetric sampling distributions, it is necessary to double the $p$-value, which makes sense from the definition of a $p$-value, given that it is equal to the conditional probability that we obtain test statistic at least as extreme as the one that represents our sample given that $H_{0}$ is true.
Now, from this definition, if we are considering a symmetric sampling distribution, shouldn't we also double the $p$-value under one tailed tests? given that there are both negative and positive test statistics as extreme or more extreme that the observed one
Perhaps this has to do with the fact that in one tailed tests, we have tails with an area of $\alpha$, meanwhile in the two tailed case, we have tails with an area of $\alpha/2$, although I am not sure this is the reason.
Comment: Consider which values of the test statistic will be more in accord with the alternative hypothesis.
Answer: No, we are picking one tail. If we double the p-value, then we are doing a two-tailed test. By picking one tail, we are choosing to focus on a particular direction of difference and increasing our power to detect a difference in that direction. The tradeoff is that we sacrifice all power to detect a difference in the other direction.


How can I verify linked libraries?

Question: I am having lots of trouble getting a specific set of drivers working, called libnifalcon.
I am pretty sure that the installation was successful, but when I try to compile the example programs I get the errors:
mars@marslab:~/Documents/libnifalcon-1.0/examples/findfalcons$ g++ findfalcons.cpp
/tmp/cc8TtfGn.o: In function `runFalconTest()':
findfalcons.cpp:(.text+0x6b): undefined reference to `libnifalcon::FalconDevice::FalconDevice()'
findfalcons.cpp:(.text+0xdd): undefined reference to `libnifalcon::FalconDevice::getDeviceCount(unsigned int&)'
findfalcons.cpp:(.text+0x1bd): undefined reference to `libnifalcon::FalconDevice::open(unsigned int)'
findfalcons.cpp:(.text+0x224): undefined reference to `libnifalcon::FalconDevice::isFirmwareLoaded()'
findfalcons.cpp:(.text+0x2ac): undefined reference to `libnifalcon::FalconFirmware::loadFirmware(bool, unsigned int const&, unsigned char*)'
findfalcons.cpp:(.text+0x33b): undefined reference to `libnifalcon::FalconDevice::isFirmwareLoaded()'
findfalcons.cpp:(.text+0x3dd): undefined reference to `libnifalcon::FalconDevice::runIOLoop(unsigned int)'
findfalcons.cpp:(.text+0x504): undefined reference to `libnifalcon::FalconDevice::runIOLoop(unsigned int)'
findfalcons.cpp:(.text+0x512): undefined reference to `libnifalcon::FalconDevice::close()'
findfalcons.cpp:(.text+0x52b): undefined reference to `libnifalcon::FalconDevice::~FalconDevice()'
findfalcons.cpp:(.text+0x53f): undefined reference to `libnifalcon::FalconDevice::~FalconDevice()'
/tmp/cc8TtfGn.o: In function `void libnifalcon::FalconDevice::setFalconFirmware<libnifalcon::FalconFirmwareNovintSDK>()':
findfalcons.cpp:(.text._ZN11libnifalcon12FalconDevice17setFalconFirmwareINS_23FalconFirmwareNovintSDKEEEvv[void libnifalcon::FalconDevice::setFalconFirmware<libnifalcon::FalconFirmwareNovintSDK>()]+0x1d): undefined reference to `libnifalcon::FalconFirmwareNovintSDK::FalconFirmwareNovintSDK()'
collect2: ld returned 1 exit status

How can I verify the libraries are linked correctly? What can I do if they aren't?
Comment: @koodawg you should re-write your comment as an answer...
Comment: You are calling functions that are not defined in such scope. Did you written the code?
Comment: no, I'm trying to run example programs.

I've verified that the namespace exists (in a separate file) and the functions are declared within it
Comment: Now I see, *out of the box*. Where did you get the source?
Comment: http://qdot.github.io/libnifalcon/
Answer: You're not linking with anything, i.e.
g++ file.cpp

does not link to any libraries other than the standard library. You need to link with other modules or libraries, probably libnifalcon
g++ findfalcons.cpp -lnifalcon

or... you probably will need to do something like
g++ -L/path/to/libnifalcon findfalcons.cpp -lnifalcon

where -I tells where to look for libraries.
Comment: `-I` is for header files, you want `-L` to set a search path for libraries, or just set the `LIBRARY_PATH` environment variable (or `LD_LIBRARY_PATH` for dynamic libraries).
Comment: it's still not working but I think we're getting closer. I thought it was a typo when you wrote -lnifalcon instead of -libnifalcon, but -lnifalcon will compile and give me the same erros I always get, but -libnifalcon gives me the "/usr/bin/ld: cannot find -libnifalcon" error. How did you know to use -lnifalcon?
Comment: That's the standard way to specify libraries, you drop the "lib" - see 'man ld'. Sounds like you don't have the correct path to libnifalcon specified with -L option (or LD_LIBRARY_PATH as mentioned by Paul Griffiths).
Comment: I've found the proper path, the -lnifalcon doesn't return an error (like it did when I had the wrong path) but I still get the undefined references. Should I look in libnifalcon.a to see if they are there?
Comment: Correct! Also, make sure your executable has the libraries you intend for it to i.e. 'ldd program' shows you all the libs linked to program. (otool on osx). Then, I'd do something like 'nm prog | grep symbol' to check the binary for the undefined you're looking for.

How can I verify linked libraries?


How to get the view fields in rows in the word document generated using Views data export module?

Question: I am using Views data export module (version 7.x-3.1) to download content in Microsoft Word Format.
I am able to download the content but the fields of the view are coming out in columns rather than rows.
Please guide.
Answer: As an alternative to using the Views data export module, you may want to use the Forena module (disclosure: I'm a co-maintainer of it) to create a "report" that includes the data that you're interesting in (i.e. the "content" as in your question). As part of the report design, indicate which export formats you want to allow for exporting the data included in it. DOC (for MS Word) is one of the typical formats that are supported (apart from CSV,  XML, HTML, etc). By using Forena, the layout of the exported table (in your MS Word doc) would not  be "coming out in columns rather than rows" (as in your question).
Have a look at the Simple Table of States example, and think of it as the equivalent of your "posts that you want to export". And note the hyperlinks in the upper right, which are:

CSV.
XLS.
HTML.
XML.

Try any of these links to get the equivalent of the extracted information, but in the format you requested (there or other supported formats such as PDF, DOC, JSON, etc).
Checkout Forena's Community Documentation for (way) more details, and/or the documentation that comes with the module.
Forena versus Views
Forena can be used together with the Views module, or as an alternative to it, more specifically:

As an alternative to Views, to create reports (and derivatives such as charts and/or exports of data) which you cannot, or not easily, create with only Views. E.g. to pivot data, where you want to create tables in the format of what in Forena is called "Render a report in FrxCrosstab format".
Integrated with Views, as explained in the Forena tutorial pages, i.e.:

Using the Forena integration with the Views module, it is possible to use Forena reports as a views row style, so that in a view you can use the Forena templating engine to do the formatting. Although this can be done through the views templating engine Forena users may find they have more control with this engine.
Comment: Can you please guide on how to use forena with view. when i chose forena reports as views rows style, the content disappears in the view.
Comment: @TulikaSharma : check my updated answer (= Forena versus Views)


When independent variables covary (not correlate) in the regression

Question: I attach r code
x1<-rnorm(999,0,1)
x2<-rnorm(999,0,1)
y <- x1+x2
iv1<-999999*x1
iv2<-999999*x2

cov(x1,x2) # nearly 0
cor(x1,x2) # nearly 0
cov(iv1,iv2) # very big,
cor(iv1,iv2) # nearly 0

summary(lm(y~x1+x2+x1*x2)) # interaction p=0.11

summary(lm(y~iv1+iv2+iv1:iv2)) #interaction significant.

Call:
lm(formula = y ~ x1 + x2 + x1 * x2)

Residuals:
       Min         1Q     Median         3Q        Max
-3.959e-14 -1.150e-16  1.400e-17  9.100e-17  4.756e-14

Coefficients:
              Estimate Std. Error    t value Pr(>|t|)
(Intercept) -7.728e-17  6.269e-17 -1.233e+00    0.218
x1           1.000e+00  6.090e-17  1.642e+16   <2e-16 ***
x2           1.000e+00  6.474e-17  1.545e+16   <2e-16 ***
x1:x2       -1.027e-16  6.630e-17 -1.550e+00    0.122
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.976e-15 on 995 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 1.631e+32 on 3 and 995 DF,  p-value: < 2.2e-16

> summary(lm(y~iv1+iv2+iv1:iv2))

Call:
lm(formula = y ~ iv1 + iv2 + iv1:iv2)

Residuals:
       Min         1Q     Median         3Q        Max
-4.137e-14 -1.010e-16  2.100e-17  1.050e-16  3.623e-14

Coefficients:
              Estimate Std. Error    t value Pr(>|t|)
(Intercept) -7.728e-17  5.581e-17 -1.385e+00   0.1665
iv1          1.000e-06  5.422e-23  1.844e+16   <2e-16 ***
iv2          1.000e-06  5.764e-23  1.735e+16   <2e-16 ***
iv1:iv2     -1.217e-28  5.902e-29 -2.062e+00   0.0395 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.759e-15 on 995 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 2.058e+32 on 3 and 995 DF,  p-value: < 2.2e-16

when I make y, I did not put interaction effect.
but why x1:x2 interaction show tendency (p=0.11)
and why iv1:iv2 interaction is significant?
Comment: You also didn't put any errors in the response *y* and you ignore a warning message about "essentially perfect fit: summary may be unreliable". So there may not much to learn from this simulation.
Comment: It's also a fallacy to interpret a p-value of ~0.1 as "showing tendency".
Comment: @dipetkov I did not put error variance, but in my real simulation work, I put error variance. this is a kind of minimum reproducible example to understand what is really happening in my real model.
Answer: I appreciate the attempt to make a reproducible example, this helps to diagnose problems. However, it's important for you to set a seed using set.seed() so we can reproduce an example exactly. Here, I cannot reproduce your example.
Let's see what happens when we set a seed and run your code:
set.seed(52)
x1<-rnorm(999,0,1)
x2<-rnorm(999,0,1)
y <- x1+x2
iv1<-999999*x1
iv2<-999999*x2

# First model
summary(lm(y~x1+x2+x1:x2))
# NOTE that I have replaced your asterisk with a colon in the formula above
# R appears to interpret both the same way so this does not really change anything meaningful

Call:
lm(formula = y ~ x1 + x2 + x1:x2)

Residuals:
       Min         1Q     Median         3Q        Max
-1.307e-15 -1.790e-16 -5.700e-17  2.500e-17  7.211e-14

Coefficients:
             Estimate Std. Error   t value Pr(>|t|)
(Intercept) 1.897e-16  7.499e-17 2.529e+00   0.0116 *
x1          1.000e+00  7.406e-17 1.350e+16   <2e-16 ***
x2          1.000e+00  7.778e-17 1.286e+16   <2e-16 ***
x1:x2       2.145e-17  7.714e-17 2.780e-01   0.7810
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.365e-15 on 995 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 1.122e+32 on 3 and 995 DF,  p-value: < 2.2e-16

summary(lm(y~iv1+iv2+iv1:iv2))

Call:
lm(formula = y ~ iv1 + iv2 + iv1:iv2)

Residuals:
       Min         1Q     Median         3Q        Max
-1.226e-15 -2.200e-16 -9.000e-17  9.000e-18  7.736e-14

Coefficients:
              Estimate Std. Error    t value Pr(>|t|)
(Intercept)  2.459e-16  9.008e-17  2.730e+00  0.00645 **
iv1          1.000e-06  8.896e-23  1.124e+16  < 2e-16 ***
iv2          1.000e-06  9.342e-23  1.070e+16  < 2e-16 ***
iv1:iv2     -7.233e-30  9.266e-29 -7.800e-02  0.93780
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.84e-15 on 995 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 7.778e+31 on 3 and 995 DF,  p-value: < 2.2e-16

# Second model:

summary(lm(y~iv1+iv2+iv1:iv2))

Call:
lm(formula = y ~ iv1 + iv2 + iv1:iv2)

Residuals:
       Min         1Q     Median         3Q        Max
-1.226e-15 -2.200e-16 -9.000e-17  9.000e-18  7.736e-14

Coefficients:
              Estimate Std. Error    t value Pr(>|t|)
(Intercept)  2.459e-16  9.008e-17  2.730e+00  0.00645 **
iv1          1.000e-06  8.896e-23  1.124e+16  < 2e-16 ***
iv2          1.000e-06  9.342e-23  1.070e+16  < 2e-16 ***
iv1:iv2     -7.233e-30  9.266e-29 -7.800e-02  0.93780
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.84e-15 on 995 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 7.778e+31 on 3 and 995 DF,  p-value: < 2.2e-16

No difference between the models. But as dipetikov points out, there could be algorithmic problems here because there's no random error - you have defined y as the exact sum of x1 and x2. This can sometimes cause that 'summary may be unreliable' error (I did not get it with this seed though). So let's retry this with some random error added.
set.seed(52)
x1<-rnorm(999,0,1)
x2<-rnorm(999,0,1)
y <- x1+x2 + rnorm(999, 0, 0.3)
iv1<-999999*x1
iv2<-999999*x2

#First model
summary(lm(y~x1+x2+x1:x2))

Call:
lm(formula = y ~ x1 + x2 + x1:x2)

Residuals:
     Min       1Q   Median       3Q      Max
-0.94731 -0.20592 -0.00382  0.19295  1.17179

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.001034   0.009457  -0.109    0.913
x1           1.000205   0.009340 107.091   <2e-16 ***
x2           0.999198   0.009808 101.873   <2e-16 ***
x1:x2        0.001398   0.009728   0.144    0.886
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.2982 on 995 degrees of freedom
Multiple R-squared:  0.9551,    Adjusted R-squared:  0.9549
F-statistic:  7050 on 3 and 995 DF,  p-value: < 2.2e-16

#Second model
summary(lm(y~iv1+iv2+iv1:iv2))

Call:
lm(formula = y ~ iv1 + iv2 + iv1:iv2)

Residuals:
     Min       1Q   Median       3Q      Max
-0.94731 -0.20592 -0.00382  0.19295  1.17179

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept) -1.034e-03  9.457e-03  -0.109    0.913
iv1          1.000e-06  9.340e-09 107.091   <2e-16 ***
iv2          9.992e-07  9.808e-09 101.873   <2e-16 ***
iv1:iv2      1.398e-15  9.728e-15   0.144    0.886
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.2982 on 995 degrees of freedom
Multiple R-squared:  0.9551,    Adjusted R-squared:  0.9549
F-statistic:  7050 on 3 and 995 DF,  p-value: < 2.2e-16

Again, I don't see a problem - the results in both cases are good. To be sure it's not because you used an asterisk for one model and a colon for the other, I retried this your way (with the same seed) but still got the same (good) results.


Difference between logistic regression and logistic neuron

Question: What is the difference between a logistic neuron in a neural net and a logit regression?

They both follow the Sigmoid function plotted below

Here is the R Code for reasons of reproducibility
<code>f <- function(x) {
   1 / (1 + exp(-x))
}

curve(f, xlim = c(-6,6), ylim= c(-0.5,1.5), main = "Sigmoid function", col.main = "red")
</code>

They are both binary classifiers
Both classifiers are symmetric and give the same output for the same input.
But what is the difference between the two?
Answer: A neural network can be considered as a networked set of logistic regression units.
While a single logistic regression can perform as a classifier on it's own it's not suited for problems where input dimensions are very high and your data is not linearly separable.
By using multiple such units, a neural network attempts to approximate any given function. The more important aspect in using a neural network however is in knowing how to train each of these units.
Here's another question similar to yours: Difference between logistic regression and neural networks


How to use the same URL Schemes to open two different iOS app

Question: I have some iOS app and I want to use the same URL schemes to open them from safari or other app, how can I do it?
Answer: This is an entry that I write in this blog:
How to launch your Application from Safari
http://appleiostips.wordpress.com/2011/07/27/launch-app-from-safari/
You must open with XCode the file myapp-Info.plist . Then add a new kind of row called: URL Types,add an Item 0 inside. Inside the item add URL scheme. In this URL scheme write the name you what to register for your application. In this example we have used myapp .
Then when iOS finds a link to myapp://withsomestuff will launch the application and call the handleURL method inside your application delegate:
<code>- (BOOL)application:(UIApplication*) application handleOpenURL:(NSURL*) url
Inside this method you can parse the url to obtain aditional parameters.

    - (BOOL)application:(UIApplication*) application handleOpenURL:(NSURL*) url{
    if (!url) return NO;
    NSString* urlString=[url absoluteString];
    NSLog(@"Received URL %@",urlString);
    NSString *loginCmd=@"myapp://login?";
    //Expects to receive myapp://login?user_name&password
    if ([urlString hasPrefix:loginCmd]){
        NSRange rangeAmp=[urlString rangeOfString:@"&"];
        if (rangeAmp.location>([loginCmd length]+1)){
            NSString* password=[urlString substringFromIndex:rangeAmp.location+1];
            NSRange userRange={[loginCmd length],rangeAmp.location-[loginCm length]};
            NSString* user=[urlString substringWithRange:userRange];
        }
    }
returnYES;
}
</code>
Comment: I can open a app from safari,but I want to use the same URL Schemes to open different apps ,how can I do?
Comment: huangshouwu - just go:  '[[UIApplication sharedApplication] openUrl:url]'


how to show the number of characters left in a multiline textbox in asp.net?

Question: I have a multiline textbox which can contain only 500 characters. Now i want to show the user the number of characters left as they are typing into the textbox as is the case when we use twitter.
Kindly help
Answer: See ASP.NET Text Character Counter by Ross Hawkins.
Answer: You'll have to write some js code.
here is simple snipptet:
<form name="form1"><input type="text" name="textArea" size="400" onkeyup="document.form1.count_display.value=document.form1.textArea.value.length;">
<input type="text" name="count_display"></form>

you can change the calculation to show the characters left, or the already typed count, as you need
Comment: Thanks for the code but the textbox is asp.net control not html control.
Comment: of course. It was only for the sample. you can paste the client events, it will work the same
Answer: Let's first create a multiline textbox.
<asp:TextBox ID="textTextBox" Text='<%# Bind("Text") %>' runat="server"
CssClass="text     smsTextBox" TextMode="MultiLine" Height="100px"
MaxLength="500" >
</asp:TextBox>

   500 characters remaining
   1 message(s)

Now add this to a javascript file or add this to Javascript to the the page the item is being rendered.
Everytime the Document is loaded the script is Run

Happy coding :-D


Calculating and comparing weighted means with changing number of daily values

Question: I have daily data where the number of values changes with each day. I would like to calculate the weighted mean of this data, where days with more values are weighted higher than days with less.
Conceptualized data:
<code>  day1     day2       day3      day4
[3,1,2] [4,1,4,5] [4,5,1,7,8] [3,4,5]
</code>
What is the correct way of weighting these values, and how might I compare the means of different data-sets (like with the SEM) with a similar structure, but different number of values per day?
Comment: Do you actually have the values 3,1,2, and 4,1,4,5 etc available?
Comment: Those are just dummy values that I used for my example.
Comment: Ahem. If you observe $n_i$ values on day $i$, do you have the $n_i$ individual values available to you?
Comment: I see. Yes, I do.
Comment: Then just take a straight average of them all. The average of a day with 3 values will get 3/5 the "weight" of the average of a day with 5 values.
Comment: geez... i have been confusing myself with other details in my system, and I just wasn't processing this for some reason. That makes things easy :) Thanks.
Comment: Would you like something like that posted as an answer?
Comment: Finished. Sorry it took me a few days, I was having trouble finding a good way to put it that would be more generally useful, but I think I got there in the end.
Answer: There are two typical cases when you get multiple points per group (per day in your case) and want to weight for the number of values per group:

the individual points are not available, only their mean and the number of values. Then you weight by the number of values (in a weighted average or a weighted regression, for example).
the individual points are available. Then you simply include all the individual points - the repeated values themselves provide the 'weight' - a group with two observations will get two observations of weight, while a group with five observations will get all five providing weight.

You're in the second case, so there's nothing to do - just use all your data. If you are (for example) computing an overall mean, then a straight average of all the data gives more weight to the days with more data.


Integrating non-continuous density function

Question: How does one handle integrations where there are points that are not continuous. For example to calculate $E(X)$, where the density of X is
$f(x)=\begin{cases} 2x^{2} & 0 \leq x \leq 1 \\ 0 & otherwise \end{cases}$
Then $E(X)=\int_{-\infty}^\infty xdF(x)=\int_0^1 2x^{3} dx$, Is the last equality justified? Since the density is not continuous at x=1?
Comment: If the set of discontinuities is finite, the value of the integral is unaffected. In fact, the same is true if the set of discontinuities is countably infinite.
Answer: I am afraid there is no short answer. Modern probabilities are defined with tools from measure theory and Lebesgue integration, which allow you to define the integral of a much larger class of class of functions than just continuous functions (like Riemann integration does). (Actually, it is a bit more complicated than that, you have to verify that your function is integrable, but this is going too far here)
These functions are called measurable, and your function $f$ just happens to be measurable and integrable (in the Lebesgue meaning).
I guess you will have to study measure theory if you want to really understand these things.
Comment: Sorry about that, I guess I should have answered this more precisely. Yes, your equality is entirely true. As $f$ is $0$ on $\mathbb{R} - [0,1]$, the integral on all $\mathbb{R}$ just happens to be equal to the one on $[0,1]$.

In an intuitive way, the discontinuity at $x = 1$ does not really matter because "a point has $0$ length". So integration just "ignores" the discontinuity at $1$. Though, this is everything but a proof.
Comment: Okay fair enough..but am I fine if I use the last equality? Or did I miss something..


Speed up the deletion of duplicates

Question: I coded a VBA script in Excel which adds new data into a Datasheet with previous information. Before doing that, the new data is copied into a provisional Datasheet. To prevent duplicates, I create an additional column and do a VLOOKUP of IDs. If the ID from the new imported data is already in the Datasheet with the old data, this row is marked as duplicated and will be deleted. The "non-duplicated rows" are then copied into the final Datasheet, where all the data is stored.
Right now I use a column reference (A:A) in the VLOOKUP and I don´t know if maybe this is the reason why the VBA script needs every day more resources and time to run. When I coded for the first time, I did the test with no more than 4,000 rows in the original Datasheet and 4,000 rows in the imported data. The macro was done after 90 seconds. Right now, it needs more than 5 minutes and the Datasheet with data is just 40,000 rows large, while the new data is always around 4,000 rows.
Should I dynamically reference the range in the VLOOKUP instead of using A:A or it doesn't matter in terms of speed?
Comment: Dynamically referencing the range won't hurt, but using arrays for such large numbers of records would be my suggestion. Think about it this way, for each of the 4000 entries you have it is looking through 40,000 other entries to find a match. Are the ids numberical? Are they names? What does the data look like? There may be a much more efficient way of looking for duplicates. I would probably suggest you copy all the data and use the excel "Remove Duplicates" funciton under the "Data" ribbon, I just ran it against a dummy data set of 100,000 entries and it took 3 or 4 seconds.
Comment: If you have unique ID's then a `Scripting.Dictionary` lookup will be orders of magnitude faster.
Comment: Show your code. If you are using VLOOKUP function on a Worksheet, that would be very slow. YOu can do all this sort of operation within VBA without manipulating the worksheet. I might use a different function than VLOOKUP, though.  There are probably other ways to optimize, but we kinda need to see what you've done, first.
Comment: See my answer here for performance comparison and approaches you could use: http://stackoverflow.com/questions/19404152/excel-vba-iterate-through-columns-in-one-workbook-pasting-information-in-corre/19410285#19410285
Comment: I drastically reduced run time by deleting the VLOOKUP procedure and doing just a Remove Duplicate as  @pegicity said (.Range("A2", "AR" & lastRow).RemoveDuplicates Columns:=1, Header:=xlYes) Thx
Comment: @pegicity add your solution as an answer so it can be accepted
Comment: Agree with @TimWilliams. I'm so used to dictionaries for removing duplicates and storing key-value pairs that I'm *almost* dependent on it. The speed is just impossible to beat, though it takes some getting used to the set up.
Answer: As mentioned in my comment, there certainly is a way to accomplish this task using VBA, but sometimes the simpliest solution is best.  I would reccomend added all 40K records each time and using the "Remove Duplicates" function under the "Data" ribbon using the column that holds your unique value.
Comment: and if you still want to use a macro this line will do it (Excel 2007 and over): .Range("Firstcolumnx", "Endcolumny").RemoveDuplicates Columns:=1, Header:=xlYes

Speed up the deletion of duplicates


Excel Userform Combobox Properties Rowsource box issues?

Question: I have a userform in Excel that works as a calculator.
In this userform I have two ComboBoxs (1 & 2)
In VBA editor, with ComboBox1 selected, In Properties, under Rowsourse I have: Sheet1!a4:a5
In Sheet1, A4 = Auckland and A5 = Christchurch
This is fine and when I run the userform there is a drop down arrow with the two options (Auckland or Christchurch).
However my problem is that when you open this workbook I have a VBA command to hide it from the users sight, leaving them only the userform to work with which is what is desired.
The issue is that if you have another workbook open then open this calculator workbook (which automatically hides itself). Then the combobox list is populated by Sheet1!a4:a5 on the other workbook that was already open, not the workbook that actually contains "Auckland" & "Christchurch" from which the userform is from.
I have tried making the Rowsource for the comboboxes more specific by putting the following in the rowsource box in properties: [book1.xlsm]sheet1!a4:a5      but this comes up with a "Invalid Property Value" error message.
I have also tried making a:
Private Sub Userform1_Initialize()

ComboBox1.Additem "Auckland"
ComboBox1.Additem "Christchurch"

End Sub

And also tried this:
Private Sub Userform1_Initialize()

ComboBox1.RowSource = Workbooks("book1.xlsm").Sheets("Sheet1").Range("a4:a5").Value

End Sub

However with both codes when it opens and runs now the comboboxes are empty and there is no list.
I think the easist solution would be to somehow put the full path (including workbook name) into the rowsource box under properties. But I must be missing something as its coming up with that error for me?
All help would be greatly appreciated.
Thanks
Answer: You are missing ' in your full path row source.
It should be like this:
Me.ComboBox1.RowSource = "'[book1.xlsm]Sheet1'!$A$4:$A$5"

I have similar question that can be found HERE.
Answer: Set the row source property of the combobox as: SheetName!$Col$Row:$Col$Row, e.g.: Location!$A$1:$A$3.
Answer: You may try adding this code on userform:
Private Sub UserForm_Initialize()
ComboBox1.list = Array("Auckland","Christchurch")
End Sub
Then set Combobox propert "MatchEntry" to "1".


Guitar Playing Barre chords

Question: Why do we base a barre chord on two different shapes ?
Is the E shape more important than the A shape ?
Why can't I use the E shape all the time ?
Comment: Some of the answers to this question (https://music.stackexchange.com/q/40609/16897) about the A shaped barre chord will provide more insight into why learning different ways to play barre chords may be useful.
Comment: Who told you that you can't use the E shape all the time? If that's your preference you're certainly entitled. For that matter, you can play using only open position chords, but if you wish to grow and develop your skills as a musician, it's advisable to be open to different ways to approach your music, barre chords and movable chords of all shapes and one's ability to apply them in performance, is just the first step towards learning new voicings of chords and an introduction to harmony studies and a better understanding of music in general. It's all important stuff.
Answer: Use the E shape barre all the time if you want. It's not a problem. Until about the fourth or fifth song in, when it starts to sound boring, because it's so samey.
Your premise that barre chords are based on two shapes is flawed. They're based on many shapes, and for me at least, the 'caged' system makes sense in that respect. Reasoning is that each of the open chord shapes, C, A, G, E and D can be transferred to anywhere else up the neck, by using a barre behind, just as the nut was. So, for example, in your case, an E shape on 3rd fret barre produces a G chord. However, using the C shape, barred at the 7th fret give G; the G shape, barred at the 12th fret gives a G; and a 4/5 string barre at the 5th fret gives a G when you use a D shape. Not forgetting 10th fret barre A shape for yet another G.
With all this choice of different voicings, the sounds made are more interesting, at least.
Another problem with only using an E shape is that there's a lot of movement required at chord change times. This makes the rhythm sound amateur, with, in a lot of (self-taught) guitarists resorting to strumming a lump of open strings while they move positions. Unnecessary, and not sounding good.
Let's take a simple A/D/E song. The A could be on 5th fret, E shape, D on 5th fret, A shape, but instead of sliding that up two for the E, barre on 4th, use C shape. Or even lazier - play an open C7 shape on 5/6/7 frets. Don't knock it till you try it a good few times!
Having said all that, the E shape may be construed as more important by some, on the basis that it's a full 6 string chord in root position, thought often as the most stable. Whereas the A shape can be played with all 6 strings, giving the 2nd inversion, but often advocated to be played without the 6th string. So, only 5 strings as opposed to 6.
Comment: Great explanation of the CAGED system. Not even 20 minute long YouTube videos explain that as well as your explanation. Well done.
Comment: Great answer - plus 1.  I discovered the E7 using a C7 shape and I love that voicing.  Unlike the C7 in first position with the E7 you can strum all 6 strings if you like.
Comment: @RockinCowboy - there's nothing wrong with playing that open C7 including the open bottom string. It's the 3rd of the chord, giving a first inversion (C7/E). Works well for some places, not so well for others. Every chord *doesn't* have to be root position, despite how many times some people say it does! Yes, that E7 sounds good with open Es at top and bottom. Oh dear, it's another root position...
Comment: One of my favorite changes in standard tuning is an an E7 which is formed as a five-string D7-shape chord on the second fret plus an open E (0-2-2-4-3-4) followed by a four-string G shape on second fret plus open A (x-0-2-2-2-5).
Answer: As Tim mentioned in his excellent answer there are actually 4 commonly used shapes of Major Barre Chords not just the two you mentioned in your question.  In addition to the E shaped Barre Chord and A shaped Barre Chord there is also the C shaped and G shaped Barre chord.
Basically any chord played as an open chord can be played as a barre chord if you think of your barre finger as a capo.
The E shaped Major Barre Chord and A shaped Major Barre Chord are the most commonly used because they are the easiest to play.
I found the E shaped Barre Chord the easiest to play but quickly learned its limitations when I decided to learn to play Takin Care of Business by Bachman Turner Overdrive.  The chords are C Bb and F - all Major but it sounds more authentic to to mix in a 6th with each chord in your strum pattern.
To play the song using only the E shaped Barre Chord I had to cover from the 8th fret to the 1st fret with my fretting hand.  But by learning the A shaped Barre Chord I only had to cover from the 3rd to first fret and both the Bb and F major were on the 1st fret.  Plus it made adding the 6th easier.
I believe you too will find certain chord progressions easier to play if you learn the A shaped Major Barre Chord in addition to the E shape.  For alternative ways to play the A shaped Barre Chord read this Different Ways to play the A shaped Barre Chord
For those who may be wondering why there are not 7 shapes for Major Barre Chords let me explain.
Major chords that can be played on a 6 string guitar in "open position" (meaning some open strings are used as part of the chord) are A, C, D, E, and G (all major).  Of course some of these chords may also be played as minor or 7th chords in open position as well.

B Major is not typically played with open strings and the first position of a B major chord is actually an A shaped Barre Chord.  Similarly the F Major chord is not played with open strings and is actually an E shaped Barre Chord.  Note that an easier version of both the 1st position B and F Barre Chords can be played using only the top four (highest) strings.

Thus the only unique shapes for Major Barre Chords that can be moved up and down the neck are A, C, D, E and G or if you prefer a mnemonic device you can remember these by changing the order to make the word CAGED.
The open D Major shape can be played as a "D shaped" Barre Chord or can appear as a fragment of a C shaped Barre Chord.  So if you can't stretch across four frets to play the full C shape Barre Chord you can play just the top four (highest) strings and think of it as either a part of a C shaped Barre Chord or as a different version of a D shaped Barre chord.  As you can see in the picture below, the D shape appears in both a "D shaped" Barre Chord and a "C shaped" Barre Chord.

The C, G and D shapes are not as popular for movable Barre Chords as the E and A shapes because they require a stretch across four frets (versus 3 for the E and A shape) between your barre finger and the other fretted notes in the chord.
In summary, I would encourage you to incorporate the A shape Barre Chord into your arsenal as you advance in your guitar skills.  I believe you will find that it gives you more options to make certain chord progressions both easier and more interesting.  The link provided above may help you find the method of playing the A shaped Barre chord that works best for you.
Good luck and keep learning and expanding. Improving your guitar playing is a lifelong process.  Enjoy the journey!
Comment: @DavidBowling  Thanks for your comment.  I agree the D should be looked at as distinct.  Thus I edited my answer.  Check out the new edits with the chart showing 2 versions of D shaped Barre.
Comment: A good answer. To add: you could think of the 4-string **F** as a barre chord which relates to the **D** in the same way that **C** relates to **A** and **G** relates to **E**. You can also think of it as a fragment of the **E** barre chord form, but I actually think that it is better to think of it as its own form. But I would also try to think of the **D** form as distinct, since there are handy **dom7**, **Maj7**, **Maj6**, and **min6** voicings that come from here (off the top of my head). Of these, only the **dom7** does not incorporate a barre.
Comment: That D shape can be a 5 string version. Why the presumption that every chord has to be a root position? Never understood that.
Comment: @Tim You are absolutely correct about the D.  I often make it a 5 string version by accident when I'm trying to only play four strings.  I think the common name for the chord if you play the open A string as the first note might be D/A meaning D with A in the bass.  But it can also be considered an inversion of D Major.  I edited my answer to give the D shape more credit as a unique chord including a chart I created showing the two different versions of a D shaped movable Barre Chord.  Check it out.
Comment: Your second way is actually the C shape, and can be barred right across all 6 strings, making it a second inversion again (D/A).
Comment: @Tim There is a caption under the Version 2 picture that says "fragment of C shape".  My original answer alluded that it was actually a C shape and not a D shape.  I am going to edit again for more clarity.   You are correct is stating that you could barre all 6 strings on the C shape Barre chord but playing a D chord as a C shaped Barre and barring all 6 gives you D/F# not D/A.  It's D/A if you play it as a C Barre Chord the way I pictured it an play only 5 strings.  I personally think it sounds better to mute the low E string on a C shape chord but can't really tell you why .
Comment: The first inversion of a triad is often thought of as sounding 'weaker' than either the root or second inversion. In some places it actually can sound like the best option, but far more often, the root is used, followed in popularity by the second inversion. When there's a bassist playing the root, the overall sound is fine with an open b bottom E in a C chord, although the open string can sound too loud. Yes, the C and D shapes are similar - it's the vagaries of guitar tuning. As the D shape only works barred as 5 string, I tend to use it as an afterthought. Open D *can* have 6 st., 2nd fret.
Comment: One useful feature of E, A, and D bar chords is that parallel minor chords can be played in the same position.  If one were to play an F chord using the C shape and then needed an F minor chord, playing the first-string Ab would be rather awkward unless one switched to a different shape.
Comment: @supercat Fair statement.
Answer: To me, the E and A shapes are fundamentally the same shape, just moved across one string - they have a very similar physical pattern, and the same pattern of intervals. The only reason that the physical fingering pattern is slightly different is that is the interval between the G and B string is only a major third.
One reason not to play chords too high on the fretboard, as you might end up doing if you only know the E shape, is that the higher you fret a string, the less 'ideal' the harmonic series it produces (because as you fret higher, it gets thicker in comparison to its length). So if you play D# with the E shape barred at the 11th fret, you may get a less 'pure' sound than A shape barred at the 6th fret.
On many guitars, it's also quite difficult to play barre chords high up the neck - the action is likely to be higher towards the 12th fret, and on some instruments (such as classical guitars), the lack of a cutaway may be a hindrance.
Once your fingers get used to making the shapes, it may also be faster and less tiring to move your fingers across one string to move up an interval of a fourth than to move your wrist 5 frets down the fretboard.
In summary - in some circumstances it may be easier, and sound better, to play using the A shape.
Comment: If one uses only the E-shaped bar, about half your chords are likely to have some notes that use less than 2/3 of the string length, and an Eb chord will contain notes that use less than half.  If one uses both E and A shapes, then an Eb chord will have some notes that use only about 62% of the string length, but all of the notes in every other chord will use at least 2/3.

Guitar Playing Barre chords


How to add laravel component in DOM using javascript

Question: I am new on laravel framework.
I have created an component (lecture-content) having some files input options, and there is an button onclick which should add one more (lecture-content) component. On DOM.

    function addContent()
        {
      let newDoc = "@include('inc.lecture-content')";
      let extendContent = document.getElementById('addNew').innerHtml;
      console.log(extendContent);
      console.log(newDoc);
      extendContent+=newDoc;
      document.getElementById('addNew').innerHtml= extendContent;

    }

Curriculum

    <button class="px-2 btn my-auto py-auto add-content-btn" onclick="addContent()" id="add-content">+ content</button>

    @include('inc.lecture-content')

but this is not working at this position let newDoc = "@include('inc.lecture-content')"; it shows syntax error. can anyone help me to resolve it. What I am doing wrong here
Answer: Use clone()
Below jQuery code will fulfill your purpose.
function addContent()
        {
          var clone = $('#addNew').clone().css('display','block');
          $('#newEle').append(clone);
        }

Add one more div to your blade file.

This newly created div will be used to append cloned div.

function addContent()
    {
      var clone = $('#addNew').clone().css('display','block');
      $('#newEle').append(clone);
    }

Curriculum

    <button class="px-2 btn my-auto py-auto add-content-btn" onclick="addContent()" id="add-content">+ content</button>

    @include('inc.lecture-content')


Contact form in a facebook page/tab

Question: I need to create a contact form in a Facebook tab, that is supposed to store every entry/submission in a MySQL database. But i'm quite stuck.
Doing the HTML part, creating the form and the inputs wasn't that hard, but the main problem comes from the iFrame/HTML applications from Facebook (i used some already - popular - made apps that i found around).
I cannot include PHP into the Facebook tab, because it's only has support for html/css/js. I tried using  but failed, as they are not displaying their source inside the Facebook tabs, so how am i supposed to accomplish this task?
LE: I managed to self-sign a certificate. Now the application is starting, as i provided secured URLs, but instead of loading the index.php in that directory i pointed, it gives me a 404 of the main site.
The main site is quart.ro, the url/secured urls are: http://quart.ro/beautydistrict and https://quart.ro/beautydistrict.
Should i write an .htaccess only for that folder? Or should i change the urls to point directly to the file ex: http/s://quart.ro/beautydistrict/index.php/?
LE2: On the application's page - https://apps.facebook.com/beautydistrict/ - it displays the content correctly (this content - http://quart.ro/beautydistrict). This app is a page tab. If i install the app to a facebook page, then instead of displaying the content correctly it gives the 404 of the main website (intead of http://quart.ro/beautydistrict i get http://www.quart.ro/404).
Comment: Can you share the app that you used in creating your pagetab?AFAIK, if it allows you to create an iFrame that loads a page, then you can do anything you want inside that pagetab, just put the url of the domain where you store the form. Anyway, here is a reference, http://developers.facebook.com/docs/appsonfacebook/pagetabs/
Comment: @Darkkz Sorry for late reply, but it is true that facebook require secure connection, and it is a must, last time i ended setting up a secure connection on my server :)
Comment: but I still got this error..
Unable to make a secure connection to the server. This may be a problem with the server, or it may be requiring a client authentication certificate that you don't have.
Error code: ERR_SSL_PROTOCOL_ERROR
Comment: Aren't tabs iframes to your own server? Where is your page hosted?
Comment: @Hendyanto i used someone's else app, like an already made-app for iframes (you can find a dozen if you search for html/iframe on fb).That's when i tried using the  tags. Then i created myself an app, but facebook only imports secured urls into the pagetab, and i do not own a ssl certificate.This is the app i made, but it is not working as the secured links are not good, and without a SSL certificate, it will not display anything/get me an error.
https://apps.facebook.com/beautydistrict/
Comment: @MathieuImbert How can i host on my server the tabs that are supposed to be integrated in facebook? On my server i have a .php file, which contains a form, and all the php code to handle the inputs. I somehow must include that file into a FB tab or at least include the code.
Comment: @Hendyanto Please check the original post, i updated with infos after i got a self-signed certificate. Thanks :)
Answer: You can post your html data into external PHP file using jquery and ajax. Use this guide http://api.jquery.com/jQuery.post/

Contact form in a facebook page/tab


Different shipping $ for west coast

Question: Let me just preface this by saying I know nothing of Drupal. I am a wordpress developer but my company just inherited 2 drupal sites from a company we recently purchased. I am using Drupal 6.25.
I have 2 classes of products that I need to change shipping for. It's free for US east coast and $199 for US west coast.  There was a generic free shipping already set up and working but I need to change for the shipping increases. I tried using the flat rate and conditions but I kept getting "Invalid option selected. Recalculate shipping quotes to continue". I set up west coast fine. I did 2 groupings -  a main AND group with 2 OR groups in that - 'or' for the shipping states and 'or' for the 2 product classes. I disabled the previous free shipping and the west coast works fine. I set up a separate shipping for east coast just like the west coast but opposite states. It works fine if I disable the West Coast. So, obviously I am doing something that is conflicting when both are enabled.
Any and all advice is greatly appreciated!
Answer: This is not an answer, just advice: Drupal 6 has been unsupported since February of 2016 - close to 4 years now. I strongly suggest you spend your efforts upgrading to Drupal 7 right now, if nothing else because of all the security fixes (which are super important on an e-commerce site!).
The D6 -> D7 upgrade is relatively easy to do for most sites. I do not recommend going directly to Drupal 8 right now because that will be very long and painful process especially if you have little Drupal experience. If you want to move to D8, it would probably be easier to rebuild the site from scratch.

Different shipping $ for west coast


How do I change a label's font (and font size)

Question: Almost all of the sources I've seen while searching are outdated for such a simple question. How can I change a label's font and size in pyqt4?
Answer: Basically you need QFont (in setupUi method or anywhere):
font = QtGui.QFont()
font.setFamily(_fromUtf8("FreeMono"))
font.setBold(True)
self.someLabel.setFont(font)

You can also check QFont reference.
P.S. _fromUtf8 is QtCore.QString.fromUtf8 imported as _fromUtf8
Comment: so you're basically saying we can't change font midway when program already started? (dynamically)


What sort of singularity is this?

Question: I have the following function:
$f(z) = \frac{\cos z}{\left(z-\frac{\pi}{2}\right)^3}$
Where I have to classify the singularity $z_o=\frac{\pi}{2}$
I've taken the limit to see if it's a removable singularity since it is indeterminate when plugging in $z_o$ but the limit does not exist.
I'm conflicted here -- I know it's not removable because the limit diverges, but then what type of singularity is it? Is it just a pole of order 3?
Answer: Hint: $\cos(\pi/2) = 0$ and the order of this zero is...
Answer: It is a pole of order $2$$$\lim_{z\to\dfrac{\pi}{2}}(z-\dfrac{\pi}{2})^2f(z)=\lim_{z\to\dfrac{\pi}{2}}(z-\dfrac{\pi}{2})^2\frac{\cos z}{\left(z-\frac{\pi}{2}\right)^3}=\lim_{z\to\dfrac{\pi}{2}}\frac{\cos z}{z-\frac{\pi}{2}}=\lim_{z\to\dfrac{\pi}{2}}\frac{-\sin z}{1}=-1$$
Comment: Thanks! But what about it tells you it's a pole of order 2?
Comment: In fact a pole $x_0$ of order $m$ of function $f(x)$ is such that $$\lim_{x\to x_0}(x-x_0)^mf(x)\in\Bbb R-\{0\}$$
Answer: Note that\begin{align}\cos(z)&=\cos\left(\left(z-\frac\pi2\right)+\frac\pi2\right)\\&=-\sin\left(z-\frac\pi2\right)\\&=-\left(z-\frac\pi2\right)+\frac1{3!}\left(z-\frac\pi2\right)^3-\frac1{5!}\left(z-\frac\pi2\right)^5+\cdots\end{align}Can you take it from here?

What sort of singularity is this?


ngModel dentro de ngFor - Angular/Ionic

Question: Eu tento criar um teste com várias perguntas e cada pergunta tem 4 respostas, minha lógica é, o primeiro ngFor é o número de perguntas e o segundo é suas respostas. Meu problema é que, quando eu digito um texto na letra A, toda questão é afetada. Na imagem, eu escrevi as respostas em question_2, mas cada pergunta recebe essas respostas.

Meu código html:
<ion-slide *ngFor="let question of listQuestions; let indexQuestion = index ;">

{{question.numberQuestion}}

  <ion-item>
    <ion-textarea rows="3" [(ngModel)]="questionClosed.statement"></ion-textarea>
  </ion-item>

  <ion-row *ngFor="let letter of listLetters; let index = index ;">
    <ion-col col-1 (click)="selectAnswer(letter)">
      {{letter}}
    </ion-col>
    <ion-col>
      <ion-item>
        <ion-textarea rows="2" [(ngModel)]='responses["question_" + (question.numberQuestion).toString()][letter]'></ion-textarea>
      </ion-item>
    </ion-col>
  </ion-row>

</ion-slide>

Meu código ts:
public questionClosed: { statement?: string; A?: string; B?: string; C?: string; D?: string; } = {
  statement: null,
  A: null,
  B: null,
  C: null,
  D: null
};
public responses: any = {};

populatedListQuestions(numberQuestions) {
 for (let i = 0; i < numberQuestions; i++) {
  const data = {
    numberQuestion: i + 1,
    description: this.questionClosed
  };
  this.listQuestions.push(data);
  let name = 'question_' + (i+1).toString();
  this.responses[name] = this.questionClosed;
 }
}

Answer: Pelo que entendi você possui uma lista de questões, que possuem uma lista de respostas, correto?
Se sim, recomendo trabalhar seu model com classes mais bem definidas, uma Entidade e um conjunto de Objeto de Valor, como essas:
class Question {
  id: number;
  description: string;
  answers: Array<Answer>;

  constructor(id: number, description: string, answers: Array<Answer>) {
    this.id = id;
    this.description = description;
    this.answers = answers;
  }

  isValid() {
    return !!this.id &&
      !!this.description &&
      !!this.answers &&
      !!this.answers.find(answer => !answer.isValid())
  }
}

class Answer {
  letter: string;
  description: string;

  constructor(letter: string, description: string) {
    this.letter = letter;
    this.description = description;
  }

  isValid() {
    return this.letter.length === 1 && !!this.description;
  }
}

Seu arquivo page.ts poderia ficar assim:
  public questions: Array<Question> = [];

  createQuestions(questionsNumber) {
    for (let i = 0; i < questionsNumber; i++) {
      const answers = [
        new Answer('A', ''),
        new Answer('B', ''),
        new Answer('C', ''),
        new Answer('D', ''),
      ];
      const question = new Question(i + 1, '', answers);
      this.questions.push(question);
    }
  }

  ngOnInit() {
    this.createQuestions(5);
  }

  submitAnswers() {
    console.log(this.questions);
  }

E seu .html assim:
<ion-slide *ngFor="let question of questions;">

{{question.id}}

    <ion-row *ngFor="let answer of question.answers;">
      <ion-col col-1>
        {{answer.letter}}
      </ion-col>
      <ion-col>
        <ion-item>
          <ion-textarea rows="2" [(ngModel)]='answer.description'>
          </ion-textarea>
        </ion-item>
      </ion-col>
    </ion-row>

  <button (click)="submitAnswers()">Submit</button>
</ion-slide>

Simulando aqui funcionou bem, sem dar problemas:
Obs.: Usando o app criado a partir do ionic cli
Comment: Perfeito, já estava a quase uma semana nisso, muito obrigado!!!!!

ngModel dentro de ngFor - Angular/Ionic


How can I use fixed << setprecision(2) only ONCE? Or at least restore to default behaviour?

Question: This is inside of a display function.  I want to print the weight using 2 decimal points.  Outside of this code block, I don't want setprecision to be in effect.  For example, 777.555 and 444.2222 should display correctly.
// Detect if train has cargo:
if (cargo_unit)
{
    // If cargo exists, print output:
    cout << **fixed << setprecision(2);**
    cout << "   Cargo: " << cargo_unit->getDesc() <<
    endl << "  Weight: " << cargo_unit->getWeight() << endl;
}

Problem is, once I used fixed << setprecision, I can only reset it to a number like 5 or 6 and then get this:
777.555000
444.222200

Answer: You can save the previous flags and precision, and then restore them afterwards, eg:
// Detect if train has cargo:
if (cargo_unit)
{
    // If cargo exists, print output:

    std::ios_base::fmtflags old_flags = cout.flags();
    std::streamsize old_prec = cout.precision();
    std::cout << std::fixed << std::setprecision(2);

    /* alternatively:
    std::ios_base::fmtflags old_flags = cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
    std::streamsize old_prec = cout.precision(2);
    */

    std::cout << "   Cargo: " << cargo_unit->getDesc() <<
    std::endl << "  Weight: " << cargo_unit->getWeight() << std::endl;

    cout.precision(old_prec);
    cout.flags(old_flags);
}

Comment: ios_base::fmtflags not std::fmtflags

Otherwise this works.  Thanks.
Comment: @DanielPaulGrechPereira fixed
Answer: Use std::defaultfloat to reset std::fixed.
Visit this link for more information.
Answer: Here is an alternative approach using std::cout.precision() to save default precision before changing it to 2, and then restoring it back to the default once as and when desired.
...
// save current precision
std::streamsize ss = std::cout.precision();

// Detect if train has cargo:
if (cargo_unit)
{
    // If cargo exists, print output:
    cout << **fixed << setprecision(2);**
    cout << "   Cargo: " << cargo_unit->getDesc() <<
    endl << "  Weight: " << cargo_unit->getWeight() << endl;
}

// Restore saved precision
std::cout << std::setprecision(ss);
...


Batch multiple plots in R

Question: Good evening,
I am trying to make an R script which generates one different plot from every .txt file, which has been previously generated in batch by an instrument, and located in the same folder of the script.
I am very inexpert in R and programming in general (1-2 months of practise so far).
The .txt files have two columns each, V1 and V2, with no header.
Here is the code that I have generated:
```
library(tidyverse)
library(ggsci)

fileNames <- list.files(getwd(), full.names = T, pattern="txt")
#print(fileNames)

Speed_selection <- grep('speed', fileNames, value=TRUE)

length <- length(Speed_selection)

i <- 1

if(i<=length){
  #print(Speed_selection[i])
  Speed <- read.table((Speed_selection[i]), header=F, sep="")

  p <- ggplot(Speed)+geom_line(aes(V1,V2))
  ggsave("plot.pdf", p)

  i=i+1
  i
} else {
  print("Finished")
}
```

My thoughts before generating the code were the following:

I obtain the list of all txt files in a folder. I check the list, and it prints only the txt files.
I select only the .txt files that have "speed" in the name.
I assign the value of 1 to i
The if loop: if i is <= than the number of the selected files

read the i^th file in the file selection (with i = 1, first file)
I make the plot I save it the directory
I increase i by 1.

So the next round will start with i = 2
The problem is, I only get one plot (corresponding to the first file), as the loop is not going through all the length of the "Speed_selection".
What am I doing wrong?
Thank you for the help,
best regards.
Comment: If you had a loop it would overwrite "plot.pdf" every single time, so you're only going to get a single output.  You would need to have a `for` at the start to implement the loop. Also, what is the `p <- plot(V2~V1, Speed, "l")` after the `ggsave` accomplishing?
Comment: Thank you for the reply. I thought so, but it is only plotting the first file of the selection list, not the second ( as it would occur as a consequence of the overwrite)... Thank you also for the correction on the plot after ggsave. I was trying to see if the normal plot function would have solve the problem. I correct it in the original post
Answer: It seems like you are over-complicating this. Wouldn't the following accomplish the same thing?
for( x in list.files(getwd(), full.names = T, pattern="\\.txt"))
{
  Speed <- read.table(x, header=F, sep="")

  p <- ggplot(Speed) +
    geom_line(aes(V1,V2))

  ggsave(p,filename=paste0(gsub("\\..*","",x),"_plot.pdf"))
}

Comment: Sorry, this gave me the following error: "Error: `device` must be NULL, a string or a function."
Comment: I didn't explicitly state which was the `ggplot2` object and which was the filename. What about now?
Comment: Yes, thank you. Now it works. Had an issue with a file name (had 0.5 in the name), but you couldn't know it in advance. Again, thanks for the help!
Comment: Of course. I'm curious how this differs from the other solution?
Answer: Here's an approach using a helper function and purrr since you're already using tidyverse.
library(tidyverse)
library(ggsci)

print_plots <- function(x) {

  data <- read.table(x, header=F, sep="")

  file_name <- sprintf("%s plot.pdf", basename(x))

   p <- ggplot(data) +
         geom_line(aes(V1,V2))

  ggsave(file_name, p)

}

fileNames <- list.files(getwd(), full.names = T, pattern="txt")

Speed_selection <- grep('speed', fileNames, value = TRUE)

walk(Speed_selection, ~print_plots(.x))

Or in a pipe:
list.files(getwd(), full.names = T, pattern="txt") %>%
       grep('speed', ., value = TRUE) %>%
       walk(Speed_selection, ~print_plots(.x))

Comment: This worked perfectly, and I have no idea why. Back to the textbooks... Thank you for the help!
Comment: Under the hood, `purrr` is using the `apply` family of functions.  These functions will apply another function to each element of a list/vector.  The `walk` function uses `sapply` but produces no output to the environment.  Essentially it walks the function through the list of files, and the side-effects of the `print_plots` helper function write you plots to pdf files.

Batch multiple plots in R


Integral of $x' \mapsto e^{-\frac{1}{\alpha}\|x'-x\|_p}$ over an $\ell_p$-ball around $x$ in $\mathbb R^n$

Question: Let $n \in \mathbb N^*$, $p \in [1,\infty]$, $\alpha > 0$, $\beta \ge 1$, and $r \ge 0$. For $x \in \mathbb R^n$, let $B_{n,p}(x;r) := \{x' \in \mathbb R^n \mid \|x'-x\|_p \le r\}$ be the $\ell_p$-ball around $x$ of radius $r \ge 0$ in $\mathbb R^n$.

Question. What is the value of $u(n,p,r,\alpha,\beta) := \int_{B_{n,p}(x;r)}e^{-\frac{1}{\alpha}\|x'-x\|_p^{\beta}}dx'$ ?
Comment: Several comments not weighty enough to merit an answer: first you should have $dx'$ rather than $dx$. On the other hand you can use translation invariance of the integral to find that $$u(n,p,r,\alpha) = \int_{B(0;r)} e^{-\frac 1 \alpha \|x'\|_p} dx'$$ and replace $x'$ by $x$.
Comment: Second you can employ the change of variable $x = \alpha y$, $dx = \alpha^n dy$ to find $$\int_{B(0;r)} e^{-\frac 1\alpha \|x\|_p} \, dx = \alpha^n \int_{B(0;r/\alpha)} e^{-\|y\|_p} \, dy.$$
Comment: Third, this is now essentially the same as evaluating the integral  $$\int_{B(0;r)} e^{-\|y\|_p} \, dy.$$ Do you know how to do this when $p=2$?
Comment: It may be easier to bring the radius parameter from the domain into the integrand, (The opposite to what Umberto does), and then, while having a fixed domain, justify differentiating under the integral.
Comment: @UmbertoP. Thanks for the comments. Indeed, since $y \mapsto e^{-\|y\|_p}$ is radially symmetric about the origin, $\int_{B_{n,p}(0,r)} e^{-\|y\|_p}dy = n\omega_{n,p}\int_{0}^r e^{-t}t^{n-1}dt$, where $\omega_{n,p}$ is the volume of the $\ell_p$ unit ball in $\mathbb R^n$.
Comment: Oops. I can prove the above formula for the case $p=2$, via polar coordinates. Actualy, this is a standard result. Anyone knows whether such a result holds in the case $p \ne 2$ ?
Comment: For $large n$, $\frac{1}{ n!\alpha^n\omega_n }u(n,p,r,\alpha) =CDF(\frac{r/\alpha-n}{\sqrt{n}})$, where $\omega_n$ is the volume of the $\ell_2$ unit ball in $\mathbb R^n$. In particularly, $\int_{x' \in \mathbb R^n}e^{-\frac{1}{\alpha}\|x'-x\|_p}dx' = \lim_{r \rightarrow \infty}u(n,p,r,\alpha) = n!\alpha^n\omega_n$, for all $x \in \mathbb R^n$.
Comment: After writing out my answer, I remembered that this can be viewed through the coarea formula as well (The first application in here (integration in spherical coordinates) https://en.wikipedia.org/wiki/Coarea_formula; take the f to be the exponential you have times the indicator that you are in the ball). I think it was educational for me to  write it all up though; I still need practice with fundamentals and the proof of coarea formula is nontrivial.
Answer: I will write the justification for exchanging the differentiation and integration that @Ciaran mentioned in the comments; I think that is the best way to prove the formula you wrote in the comments, namely:
$$\int_{B_{n,p}(r)} e^{-\|x \|_p} dx = \omega_{n,p} \int_0^r ns^{n-1} e^{-s} ds$$
where $\omega_{n,p}(r)$ is the $\ell_p$-ball of radius $r$ in $\mathbb{R}^n$
We can argue that the integral above is a function of $r$, so we define
$$ f(r) = \int_{B_{n,p}(r)} e^{-\|x \|_p} dx $$.
Now, we try to compute the derivative, so we first compute an upper and a lower bound on the quotient $ f'(r,\epsilon) = \frac{f(r+\epsilon) - f(r)}{\epsilon}$ to make sure that the derivative exists. Here, we can use the monotonicity of the integrand to argue that
$$ \frac{ (\omega_{n,p}(r + \epsilon) - \omega_{n,p}(r)) e^{-r}}{\epsilon} \geq f'(r, \epsilon) \geq \frac{(\omega_{n,p}(r+\epsilon) - \omega_{n,p}(r))e^{-(r + \epsilon)}}{\epsilon}$$
Now, for both sides of the inequality, the limit as $\epsilon$ goes to $0$ is well-defined (we use the continuity of $e^{-r}$ as a funciton or $r \ge 0$, and that $\omega_{n,p}(r) = r^n \omega_{n,p}(1)$, which is also a continuous function of $r \ge 0$) , we get that the derivative $f'(s)$ is well-defined and is equal to
$$f'(s) = n\omega_{n,p}(1) s^{n-1} e^{-s} $$
and the result now follows from fundamental theorem of calculus.
(An alternate approach is to use the layer-cake decomposition; it works just fine (that is how I first did it), though it is a bit longer I think, and I had to use integration by parts to show that the two expressions were equal)
Comment: Nice answer. Thanks!
Comment: Thanks for hinting the coarea formula. I've used it to solve my problem. See below.
Answer: In the comments, the problem has been essentialized to computing the integral $\int_{B_{n,p}(0, r)}e^{-\frac{1}{\alpha}\|y\|_p^\beta}dy$. Here, I'll pursue the computations, only focusing on the case when $p \in \{1,2,\infty\}$.

Now, let $\varphi :[0, \infty) \rightarrow \mathbb R$ be a measurable function, e.g $\varphi(t) \equiv e^{-t^\beta/\alpha}$ (with $\alpha,\beta > 0$) in my problem. Define measurable functions $g,u:\mathbb R^n \rightarrow \mathbb R$ by $g(y) := \varphi(\|y\|_p)1_{B_{n,p}(0,R)}(y)$, $z(y) := \|y\|_p$. For $t \ge 0$, define the level-set $z^{-1}(t) := \{y \in \mathbb R^n \mid \|y\|_p = t\}=:S_{n,p}(0,t)$. Note that thanks to the triangle inequality for $\ell_p$-norms, $z$ is Lipschitz and $z^{-1}(t)$ is a.e smooth for all $t \ge 0$. Finally, note that $\partial_j u(y) = \dfrac{y_j|y_j|^{p-2}}{\|y\|_p^{p-1}}$ and so for every $y \in \mathbb R^n\setminus\{0\}$, we have
$$
\begin{split}
\|\nabla z(y)\|_2 &= \frac{1}{\|y\|_p^{p-1}}\sqrt{\sum_{j=1}^n y_j^2y^{2(p-2)}}=\frac{1}{\|y\|_p^{p-1}}\sqrt{\sum_{j=1}^n y^{2(p-1)}}\\
&=a_{n,p} := \begin{cases}1, &\mbox{ if }p \in \{2,\infty\},\\\sqrt{n},&\mbox{ if }p=1.\end{cases}
\end{split}
$$
For $m \in \mathbb N$, let $\mathcal L^m$ be the $m$-dimensional Lebesgue measure (aka $m$-dimensional volume) and let $\mathcal H^m$ be the $m$-dimensional Hausdorff measure (aka $m$-dimensional surface area). Then by the coarea formula, we have
$$
\begin{split}
a_{n,p}\int_{B_{n,p}(0,r)}\varphi(\|y\|_p)dy &= \int_{\mathbb R^n}g(y)\|\nabla z(y)\|_2dy\\
&= \int_{\mathbb R}\left(\int_{z^{-1}(t)}g(y)d\mathcal H^{n-1}(y)\right)dt\\
&= \int_{0}^r \varphi(t)\mathcal H^{n-1}(S_{n,p}(0,t))dt\\
&= \int_{0}^r \varphi(t)\partial_t\mathcal L^n (B_{n,p}(0,t))dt\\
&= n\omega_{n,p}(1)\int_{0}^r \varphi(t)t^{n-1}dt,
\end{split}
$$
where we've used the fact that $\mathcal L^n(B_{n,p}(0,t)) =: \omega_{n,p}(t) = t^n\omega_{n,p}(1)$. In particular, let $\varphi(t) \equiv e^{-t^\beta/\alpha}$. Define the incomplete gamma function $\gamma:[1,\infty) \times [0, \infty] \rightarrow [0, \infty)$, by $\gamma(a,x) := \int_{0}^x e^{-s}s^{a-1}ds$, and note that $\gamma(a,\infty) \equiv \Gamma(a)$, the ordinary gamma function. Then, letting $u:=u(n,p,r,\alpha,\beta)$, one computes
$$
\begin{split}
\frac{\beta a_{n,p}}{\alpha^{n/\beta}\Gamma(n/\beta)n\omega_{n,p}(1)}u &= \frac{\beta a_{n,p}}{\alpha^{n/\beta}\Gamma(n/\beta)n\omega_{n,p}(1)}\int_{\|y\|_p \le r}e^{-\frac{1}{\alpha}\|y\|_p^\beta}dy \\
&= \frac{\beta}{\alpha^{n/\beta}\Gamma(n/\beta)}\int_{0}^r e^{-t^\beta/\alpha}t^{n-1}dt\\
&=\frac{\gamma(n/\beta,r^{\beta}/\alpha)}{\Gamma(n/\beta)},
\end{split}
\tag{*}
$$
which is the CDF of the Amoroso distribution with parameters $\alpha^{1/\beta}$ (the scale), $n$, and $\beta$.

The LHS of (*) is the probability that a random vector $Y$ drawn from $\mathbb R^n$ drawn with density proportional to $e^{-\frac{1}{\alpha}\|Y\|_p^\beta}$ lies within an $\ell_p$-ball of radius $r$ around the origin. In particular, we derive from the above computations that the $k$ moment of $\|Y\|_p$ is given by
$$
\mathbb E[\|Y\|_p^k] = \frac{\alpha^{k/\beta}\Gamma((n + k)/\beta)}{\Gamma(n/\beta)} \sim \left(\frac{\alpha n}{\beta}\right)^{k/\beta},\text{ for }n \gg \beta. \tag{**}
$$

The special case $\beta=1$
In particular, if $\beta=1$, then
$$
\begin{split}
\frac{\gamma(n/\beta,(r/\alpha)^{1/\beta})}{\Gamma(n/\beta)}&=\frac{\gamma(n,r/\alpha)}{\Gamma(n)}=\mathbb P\left(\sum_{k=1}^nX_k \le r/\alpha\right)\\
&= \mathbb P\left(\sqrt{n}\left(\frac{\sum_{k=1}^n X_k}{n}-1\right)\le \frac{r/\alpha-n}{\sqrt{n}}\right)\\
&= \Phi\left(\frac{r/\alpha-n}{\sqrt{n}}\right) + \mathcal O\left(\frac{1}{\sqrt{n}}\right),
\end{split}
$$
where $X_1,\ldots,X_n$ are i.i.d unit rate exponential random variables and $\Phi$ is the CDF of the standard Gaussian distribution $\mathcal N(0, 1)$, and we have made use of the Central Limit Theorem.
Comment: Fun fact: That integral you are computing actually has a name; it is called the incomplete gamma function https://www.maths.lancs.ac.uk/~jameson/gammainc.pdf
Comment: Yes, it's indeed proportional to the lower incomplete gamma function $\gamma(n,R) := \int_{0}^R e^{-t}t^{n-1}dt$


Webform Error Occurs During Configuration Import

Question: Currently we are having some trouble handling webform module configuration on our various environments.
When running a configuration import drupal config:import --directory=$SYNC_DIR on our dev environments with a fresh database from production we receive the following error:
[ERROR] An error occurred while trying to write the config file: "Entities exist of type Webform submission and Webform Borough Newsletter. These entities need to be deleted before importing."
This particular web form (Borough Newsletter) has not been exported as config from production and has no associated yaml file, additionally it has some submissions in the database.  When we remove all submissions of this particular webform the import completes, but removes any webforms not stored as config (no surprise there).  We also tried to use the Config Ignore to prevent webforms from importing configuration, but we still got the above error.  I have three main questions:

Our webforms are created on production by non-developers.  Is the proper workflow to start exporting webform config from prod and bring it to our dev environments top down?
What exactly was the cause of the error we got during import (mentioned above)?
How come we still get an import error when we explicitly attempted to block any webform config from being imported? Was it due to a dependency on webforms from some other configuration item?

Webform Module Version: 8.x-5.3
Drupal Core Version: 8.6.17
Thank you in advance!
Answer: Ad 1)
I guess the proper workflow is never do any config changes on prod, completely disable all config UIs on prod and do only one-way forward-syncs from stage to prod. But I'm also working for small businesses, who do their work directly on the prod server, so I also can't use the "proper" workflow.
My personal workflow is

Prod always is the source of truth (no config ignore).
Before development, always pull config from prod.
drush @prod site:ssh drush_cex_and_git_push.sh "Backsync"
git_pull_and_drush_cim.sh
During development, don't change config on prod to avoid merging troubles.
After development, push to repository and pull changes on prod.
drush_cex_and_git_push.sh "New awesome feature"
drush @prod site:ssh git_pull_and_drush_cim.sh

This workflow is NOT safe for concurrent config changes, so this will not work well if you have frequent config changes on prod or long-term or multi-person development jobs!
Prerequisites:

SSH access on prod. Add dev machine's SSH key on prod's ~/.ssh/authorized_keys.
Create drush site environment entries for @dev and @prod in ~/drush/sites/self.site.yml to execute drush commands on prod environment while working on dev machine. (doc)
Use git with SSH keys for quick syncing config between environments without password prompts.
Use some bash scripts for single-command syncs between environments

git_pull_and_drush_cim.sh
#!/usr/bin/env sh
echo ""
echo "PULL and IMPORT all updates..."
echo ""

git pull
echo ""
echo "DELETING unused config files"
echo ""
git clean -fd config/sync
echo ""
./composer.phar install --no-dev
./vendor/bin/drush state:set system.maintenance_mode 1 -y
./vendor/bin/drush cache:rebuild
./vendor/bin/drush updatedb -y
./vendor/bin/drush config:import -y
./vendor/bin/drush core:cron -y
./vendor/bin/drush state:set system.maintenance_mode 0 -y
./vendor/bin/drush cache:rebuild

drush_cex_and_git_push.sh
#!/usr/bin/env sh

if [ -z "$1" ]; then
  echo "Usage: drush_cex_and_git_push.sh <commit message>"
  echo ""
  exit 1
fi

echo ""
echo "EXPORT and PUSH all updates..."
echo "Commit Message: $1"
echo ""

./vendor/bin/drush config:export -y
git add -A
git commit -m "$1"
git push

I'm also using those scripts as part of my semi-automated maintenaince script running composer updates for all my projects.

Ad 2)
drush config:import deletes all existing configs from the DB that are not present in the sync directory. Since you cannot delete an entity config while there are dependent entity instances in the database, you get this error message.
It would be the same as if deleting node.type.article.yml config while still having article nodes in the database.

There are a lot of blog posts on large enterprise projects with a strict dev --> stage --> prod workflow. I'd love to see more info on how to handle a small dev <--> prod workflow.
Comment: My workflow is documented here. https://www.jrockowitz.com/blog/managing-webform-configuration . Basically most config is pushed from dev to prod with only some config (i.e. blocks, webforms, and certain admin settings) are editable on production. Also checkout https://www.videodrupal.org/video/20181129/dcatl-2018-drupal-8-configuration-system-basics-michael-anello
Comment: Thanks for the reply :) It looks like even though we should be ignoring webform config it isn't actually being ignored, see my other post for more info.
Answer: UPDATE 2: I posted a question on Drush's GitHub concering this issue and have received an answer that clears it up.
Essentially, Config Ignore only modifies the default sync storage and when using config-import with no args it takes effect, passing the source argument changes the default sync storage and this is not affected by config-import.  More details can be found here.

UPDATE 1: It turns out that the module Webform Config Ignore (and Config Ignore) depends on, Config Filter, doesn't yet support Drupal Console so that solves the mystery of why that command didn't respect the rules for ignoring webform configuration.
Still looking into why drush config-import --source differs from drush config-import

So after some investigation and a little luck we discovered the issue, though why it occurred is something we're still trying to figure out.
In our deploy process we run a db update (drush -y updb --entity-updates) and then run drupal config:import --directory=$SYNC_DIR to start the configuration import. As I mentioned earlier even with the Config Ignore (or Webform Config Ignore) module the webform config still attempts to import and the error occurs.  An external vendor we are working with on this site had a similar deploy script, but they used the command drush -y config-import to run the config import process, when that command is used the webform config is actually ignored and the process completes.
It gets even stranger, if the command drush -y config-import --source=$SYNC_DIR is used it fails with the same error as the drupal console command.  Only when using the drush config-import command with no args (so it uses the sync dir within settings.php, which is the same as $SYNC_DIR) does the configuration import actually ignore webform configuration and complete successfully.
I'll post an update when I figure out why is this is the case.
Drush Version: 8.3.0
Drupal Console Version: 1.9.1


Como passar valores de uma lista no Ionic3

Question: Fala galera, to quebrando cabeça com uma coisa "aprentemente" simples, mais nem tanto... tenho um json simples com id e nome, com aproximadamente 25 registros, tenho que pegar somente os registros selecionados pelo usuário para gerar uma nova tela conforme os itens selecionados, estou fazendo da seguinte forma:
<ion-list>
  <ion-list-header>
    Disciplinas
  </ion-list-header>

  <ion-item *ngFor="let dsc of disciplinas">
    <ion-label>{{ dsc.disciplina }}</ion-label>
    <ion-toggle (ngModel)="slcDisc[dsc]" checked="false"></ion-toggle>
  </ion-item>
</ion-list>

No controller quando visualizo o iten slcDisc[] ele da como um undefined, minha dúvida é como pegar esses valores do lado do controller!?
Comment: pode fornecer o código do controller?
Comment: Isso que estou tentando fazer no controller e não estou conseguindo! Quando submeto o form, estou verificando os demais campos com o console.log() e estão vindo certinhos, quando exibo os itens selecionados no toogle dá como undefined!
Answer: Fiz de uma forma um pouco diferente. Nao sei se super compliquei, ou seja, se há uma forma mais simples de fazer, mas funciona. O beneficio aqui é não ser necessario passar pelo "submit" para ter as alteracoes no controller.
<ion-list>
    <ion-list-header>
      Disciplinas
    </ion-list-header>

    <ion-item *ngFor="let dsc of disciplinas">
      <ion-label>{{ dsc.disciplina }}</ion-label>
      <ion-toggle (ngModel)="slcDisc[dsc]" checked="false" (ionChange)="mudou(dsc.disciplina)"></ion-toggle>
    </ion-item>
  </ion-list>

  <button (click)="teste()"> Final</button>

import { Component } from "@angular/core";

@Component({
    selector: 'teste-tog',
    templateUrl: 'teste-tog.component.html',
  })
export class TestTogComponent {

    disciplinas: Array<{disciplina: string}> = new Array<{disciplina: string}>();
    slcDisc: Array<{disciplina: string}> = new Array<{disciplina: string}>();

    constructor(){
        this.disciplinas.push({disciplina: 'portugues'}, {disciplina: 'matematica'}, {disciplina: 'geografia'});
    }

    teste(){
        console.log(this.slcDisc);
    }

    mudou(disciplina: string){
        let indice = this.slcDisc.findIndex( (v) => {
            return v.disciplina == disciplina
        })
console.log(indice + ' ' + disciplina);
        if ( indice == -1 )
            this.slcDisc.push({disciplina: disciplina})
        else
            this.slcDisc.splice(indice, 1);

    }
}

Passei só a propriedade disciplina para o metodo mudar mas vc tb pode passar o objeto dsc inteiro. Só seria preciso alterar a assinatura do metodo.


Firestore Security Rules, Regex, how to avoid special chracters

Question: https://firebase.google.com/docs/reference/security/database/regex
I`m looking at this right now and feel kinda hard to understand and tricky
I just want to set regex "only allows lower alphabet and numbers and  - _ * # .  these five special characters.
how could I acheive that ? thanks
Comment: Are you using the Realtime Database or Cloud Firestore? (They are two different services with different security rules syntax)
Comment: @Renaud Tarnec Hi I use "Cloud Firestore"
Answer: If you use Cloud Firestore you should declare your regular expressions according to Google RE2 syntax, see the doc about the matches() method.
The link you mention in your question is about the Realtime Database Security rules. The Realtime Database and Cloud Firestore are two different NoSQL Database services with different security rules syntax.
Comment: Something like this should work: `allow write: if request.resource.data.message.matches('[a-z0-9-_\*#]+')`. If you're having a hard time making that work, edit your question to show what you tried already.
Comment: @Frank van Puffelen thanks Frank but I got error this Line 18: Missing a closing '; Line 18: mismatched input ']' expecting {'--', '++', '{', '[', '(', '-', '!', '/', 'false', 'null', 'true', PATH_SEGMENT, IDENTIFIER, NUM_INT, NUM_FLOAT, UNPAIRED_DOUBLE_QUOTE, UNPAIRED_SINGLE_QUOTE, STRING, BYTES}; Line 19: Missing a closing '; Line 19: missing ')' at '}'
Comment: Hi thanks. I just see that syntaxs that you linked but still huge confused. I just want to set regex "only allows lower alphabet and numbers and - _ * # . these five special characters. could you please help me please


VBA - Shell, Run Time Error 5 Invalid Procedure - Thunderbird Email with HTML table

Question: I have a VBA code which allows to create an email(Thunderbird) and in email body appers HTML table based on cell values. Everythings works fine, but only until table has less then 19 rows and 24 columns. Then pops up Run Time Error 5 - line with Call Shell.
Here code for HTML Table(found in Net):

Function create_table(rng As Range) As String

Dim mbody As String
Dim mbody1  As String
Dim i As Long
Dim j As Long

mbody = "

" ' configure the table

'create Header row
For i = 1 To rng.Columns.Count
    mbody = mbody & "
" & rng.Cells(1, i).Value & "
	"
Next

' add data to the table
For i = 2 To rng.Rows.Count
    mbody = mbody & "
"
    mbody1 = ""
    For j = 1 To rng.Columns.Count
    mbody1 = mbody1 & "
" & rng.Cells(i, j).Value & "	"
    Next
    mbody = mbody & mbody1 & "
"
Next

create_table = mbody
End Function

Code for email:
email = Worksheets("Sheet1").Range("B1").Value
subj = Worksheets("Sheet1").Range("B2").Value
body = "Hello" & "

" & _
create_table(ActiveSheet.Range("A1").CurrentRegion) & "

"
thund = "Thunderbird path" & _
        " -compose " & """" & _
        "to='" & email & "'," & _
        "cc='" & cc & "'," & _
        "bcc='" & bcc & "'," & _
        "subject='" & subj & "'," & _
        "body='" & body & "'" & """"

Call Shell(thund, vbNormalNoFocus)
Application.Wait (Now + TimeValue("0:00:03"))

Is there any limition? Is it possible to change it?
Comment: ? , 2 things to look at, , length of thund string and the contents of the cells, specially if they contain single or double quotes
Comment: Try using `Option Explicit` and see if it shows up any parsing errors.  https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/option-explicit-statement
Comment: That `Application.Wait` looks suspicious it could be a timing problem.
Comment: I tried Option Explicit and removed Application.Wait, but still the same error.
Comment: Seems like thund length is too long. I found that, cmd line has limitaion of 8191 characters. After deleting piece of code - Align=""Center", code worked. Now need to figure out how to adjust code to 8191 characters.
Answer: Thunderbird allows using a file for the body with the message parameter, use that instead of the body parameter
    Dim FSO As New FileSystemObject
    Set FSO = CreateObject("Scripting.FileSystemObject")
    fname = FSO.GetTempName & ".html"
    Set FileToCreate = FSO.CreateTextFile(fname)
    FileToCreate.Write body
    FileToCreate.Close

    Email = Worksheets("Sheet1").Range("B1").Value
    subj = Worksheets("Sheet1").Range("B2").Value
    body = "Hello" & "

" & _
    create_table(ActiveSheet.Range("A1").CurrentRegion) & "

"
    thund = "Thunderbird path" & _
            " -compose " & """" & _
            "to='" & Email & "'," & _
            "cc='" & cc & "'," & _
            "bcc='" & bcc & "'," & _
            "subject='" & subj & "'," & _
            "message='" & fname & "'" & """"

    Call Shell(thund, vbNormalNoFocus)
    Kill fname
    Application.Wait (Now + TimeValue("0:00:03"))

Comment: Seems like good idea. Do you have any source of information how this work? I never did it, so I need better understaing.
Comment: The answer above already does it!!!