Can't spawn an copy of the rect but just rotated on top

Question: I need to have a pipe spawning system in pygame for my "Flappy Bird". I have coded it so that I can spawn one pipe, but I need to have a pipe on top rotaded 180 with a little space beetween so that my bird can fly between. Right now I only get an error. (I will add collisions and a list of the pipes so they remain on the screen).
Here is my code:
import pygame
import os
import random
from sys import exit
pygame.init()
os.system("cls")

WIDTH = 288
HEIGHT = 512
FPS = 60

JUMP_POWER = 60
GRAVITY = 0.15
GAME_ACTIVE = 1
VOLUME = 0.15

OBSTACLE_INTERVAL = 500
OBSTACLE_SPACE = 100
AWAY_FROM_BIRD = 150

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("assets/images/player/bird.png").convert_alpha()
        self.rect = self.image.get_rect(center = (WIDTH/4, HEIGHT/2))
        self.gravity_store = 0

        self.jump_sfx = pygame.mixer.Sound("assets/audio/jump.wav")
        self.jump_sfx.set_volume(VOLUME)

        self.hit_sfx = pygame.mixer.Sound("assets/audio/hit.wav")
        self.hit_sfx.set_volume(VOLUME)

    def player_input(self):
        for event in event_list:
            if event.type == pygame.KEYDOWN:
                if self.rect.bottom <= 0:
                    pass
                else:
                    if event.key == pygame.K_SPACE:
                        self.gravity_store = 0
                        self.rect.y -= JUMP_POWER
                        self.jump_sfx.play()

    def gravity(self):
        self.gravity_store += GRAVITY
        self.rect.y += self.gravity_store

    def collision(self):
        global GAME_ACTIVE
        if self.rect.colliderect(ground_rect):
            self.hit_sfx.play()
            GAME_ACTIVE = 0

    def update(self):
        self.player_input()
        self.gravity()
        self.collision()

class Obstacles(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("assets/images/obstacles/pipe-green.png")

    def obstacle_spawn(self):
        player_x = player.sprite.rect.x
        obstacle_height1 = random.randint((HEIGHT/2)-150, HEIGHT-150)
        self.rect = self.image.get_rect(midtop = (player_x+AWAY_FROM_BIRD, obstacle_height1))

        obstacle.draw(SCREEN)

        self.image = pygame.image.load("assets/images/obstacles/pipe-green.png")
        obstacle_height2 = self.rect.midtop
        heightlist = list(obstacle_height2)
        y = heightlist[1]
        y = y - OBSTACLE_SPACE
        del heightlist[1]
        heightlist.append(y)
        obstacle_height2 = tuple(heightlist)
        self.image = pygame.transform.rotate(self.image, 180)
        self.rect = self.image.get_rect(bottom = (player_x+AWAY_FROM_BIRD, obstacle_height2))

        obstacle.draw(SCREEN)

    def update(self):
        self.obstacle_spawn()

SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Mama Bird")
clock = pygame.time.Clock()

background_surf = pygame.image.load("assets/images/background/background-day.png")
background_rect = background_surf.get_rect()
ground_surf = pygame.image.load("assets/images/background/base.png")
ground_rect = ground_surf.get_rect(topleft = (0, HEIGHT-112))

player = pygame.sprite.GroupSingle()
player.add(Player())

obstacle = pygame.sprite.Group()
obstacle.add(Obstacles())

OBSTACLESPAWN = pygame.USEREVENT + 1
pygame.time.set_timer(OBSTACLESPAWN, OBSTACLE_INTERVAL)

while True:
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    if GAME_ACTIVE == 1:
        SCREEN.blit(background_surf, background_rect)

        player.draw(SCREEN)
        player.update()

        for event in event_list:
            if event.type == OBSTACLESPAWN and GAME_ACTIVE == 1:
                obstacle.update()
                #obstacle.draw(SCREEN)

        SCREEN.blit(ground_surf, ground_rect)

    pygame.display.update()
    clock.tick(FPS)

Here is the error:
Traceback (most recent call last):
  File "C:\Users\46722\Documents\Programmering\Python\yesman\Pygame\Mama Bird\main.py", line 121, in <module>
    obstacle.update()
  File "C:\Users\46722\AppData\Local\Programs\Python\Python310\lib\site-packages\pygame\sprite.py", line 539, in update
    sprite.update(*args, **kwargs)
  File "C:\Users\46722\Documents\Programmering\Python\yesman\Pygame\Mama Bird\main.py", line 86, in update
    self.obstacle_spawn()
  File "C:\Users\46722\Documents\Programmering\Python\yesman\Pygame\Mama Bird\main.py", line 81, in obstacle_spawn
    self.rect = self.image.get_rect(bottom = (player_x+AWAY_FROM_BIRD, obstacle_height2))
TypeError: invalid rect assignment
PS C:\Users\46722\Documents\Programmering\Python\yesman\Pygame\Mama Bird>

Answer: The bottom argument only affects the y-coordinate of the rectangle. Therefore you can only assign a single value, but not a tuple. If you want to set the x and y coordinate, you must use bottomleft, midbottom, or bottomright (see pygame.Rect). Also obstacle_height2 needs to be s single value not a list. e.g. self.rect.top
obstacle_height2 = self.rect.top
self.image = pygame.transform.rotate(self.image, 180)
self.rect = self.image.get_rect(midbottom = (player_x+AWAY_FROM_BIRD, obstacle_height2))

Additionally you need to flip the pipe image along the y axis with pygame.transform.flip:
self.image = pygame.image.load("assets/images/obstacles/pipe-green.png")
self.image = pygame.transform.flip(self.image, False, True)


Find ray between an angle in the same plane as the angle

Question: If I have an angle $\angle{ABC}$, I want to know how to find a ray $\overrightarrow{BD}$ such that $\overrightarrow{BD}$ is in the same plane as $\angle{ABC}$, and the measure of $\angle{ABD}$ is some desired value.
As an example, if I have an angle $\angle{ABC}$ that measures 50 degrees, I want to find a point $D$ such that $\angle{ABD}$ measures 30 degrees, and that $\angle{ABD}$ and $\angle{ABC}$ are on the same plane.
Is there a general formula for this kind of problem?
Answer: It seems like you're asking for two separate things at once:

An angle that has one ray common with another angle, and whose measure is some fraction of the other angle
A point on the new angle that is the same fractional distance between the defining points on the original angle

You can do this if:

Point $B$ is the center of a circle on which $A$ and $C$ lie, and
Point $D$ also lies on this circle.

In this case, point $D$ will be the same fraction of the way from $B$ to $C$ as the ratio of $\angle ABD$ to $\angle ABC$.  In other words, the ratio of the arc lengths is the same as the ratio of the angles.
However, if $B, C, D$ aren't so nicely constrained, in general you won't get both conditions met at once.  Absent a circle, the most intuitive way to interpret the distance from $B$ to $C$ would be a straight line, and if $D$ doesn't lie on the line defined by $B$ and $C$, what does "three-fifths of the way from $B$ to $C$" really mean, anyway?
Even constraining $B,C,D$ to be collinear won't get you both conditions at once, because $\angle ABD$ doesn't change proportionally with the distance along $AC$.
Comment: I agree, my question was ambiguous. I removed that ambiguous part, to make clear that I am asking for your first bullet point, not the second one.


A set $S \subset \mathbb{R}$ has no cluster points iff $S \cap [-n,n]$ is a finite set for each $n \geq 1$

Question: A set $S \subset \mathbb{R}$ has no cluster points iff $S \cap [-n,n]$ is a finite set for each $n \geq 1$
Possible useful definitions:
Defn: A set $A$ is compact $\Leftrightarrow$ the set is closed and bounded.
Defn: A set is closed if it contains all of its limit points
Defn: A point $x$ is a cluster point of a subset $A$ of $\mathbb{R}^n$ if there is a sequence$(a_n)_{n = 1}$ with $a_n \in A\setminus \{x\}$ such that $x = \lim_{n\to\infty}a_n$
Attempt: I don't really have an idea of how to formally prove this, but I will write out what I think would be the way to go about this.
$\Longrightarrow$ If I assume that the set $S$ has no cluster points, then that would mean that the set is not closed. This means it is not compact. Now I feel that from this there must be some way to create a one to one function with $\mathbb{N}$ that may possibly show finiteness, but I am struggling to do such.
$\Longleftarrow$ I am not really sure how to start. The question I am asking myself is, what would the set $S \cap [-n,n]$ look like? and if the set is finite how can I show it is not closed since I beleive not having cluster points would imply.
Comment: Defn: A set is closed iff it contains all of its limit points. If every finite subset of R is closed then how can we say that finite subset of R has no limit points? I m confused regarding these two statements.
Answer: One way:
suppose $S$
has a cluster point.
Then there is an
$a$, $c>0$,
integer $m$
and sequence $(x_j)$
such that
$|x_j-a| < c$
for $j > m$.
Then,
if $n > |a|+c$,
$S \cup [-n, n]$
has an infinite number of points
(the elements
$(x_j|j > m$).
I'll leave the other way for you.
Comment: did you use the conrapositive method to write your proof? Because wouldn't it have to be Not B $\Rightarrow$ Not A?
Answer: $\Longrightarrow$ By contraposition. Suppose that it exists $n \ge 1$ such that $S \cap [-n,n]$ is infinite. Therefore, it exists a sequence $(s_m)$ of distinct points all belonging to $S \cap [-n,n]$. As $[-n,n]$ is compact, $(s_m)$ has a limit point which is a cluster point of $S$.
$\Longleftarrow$ Again by contraposition. Suppose that $s$ is a cluster point of $S$. There is a sequence $(s_n)$ of points of $S \setminus \{x\}$ converging to $s$. The sequence is bounded, let's say by $M>1$ integer. The sequence has an infinite number of points as it converges to a limit which is not in its range. As $s_n \in [-M,M]$ for all $n \in \mathbb N$, $S \cap [-M,M]$ is infinite.
Comment: Quick questions: for 1) could I have also used $[-n, n]$ itself as my compact set instead of the explicit $[-1,1]$?
Comment: @dc3rd There was a typo in my response that you noticed! I changed $[-1,1]$ with $[-n,n]$.


Vue + jest debug

Question: i'm trying to debug in vs code my vue project which uses jest for testing.
jest.config.js:
module.exports = {
  moduleFileExtensions: [
    'js',
    'jsx',
    'json',
    'vue'
  ],
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^.+\\.jsx?$': 'babel-jest'
  },
  transformIgnorePatterns: [
    '/node_modules/',
    '/node_modules/(?!@babel)'
  ],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  snapshotSerializers: [
    'jest-serializer-vue'
  ],
  testMatch: [
    '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
  ],
  testURL: 'http://localhost/',
  watchPlugins: [
    'jest-watch-typeahead/filename',
    'jest-watch-typeahead/testname'
  ]
}

launch.json :
{
"version": "0.2.0",
"configurations": [
 {
    "type": "node",
    "request": "launch",
    "name": "Debug Unit Tests",
    "runtimeExecutable": "npm",
    "runtimeArgs": [
      "run-script",
      "test:debug",
      "${file}"
    ],
    "port": 9229
  }
]

}
I've tried almost every tutorial online like :
https://medium.com/@sarngru/debug-vuejs-jest-tests-in-vscode-63e2ed45e503
when tried to run debugging got :
node_modules\.bin\vue-cli-service:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^

SyntaxError: missing ) after argument list
    at new Script (vm.js:83:7)
    at createScript (vm.js:267:10)
    at Object.runInThisContext (vm.js:319:10)
    at Module._compile (internal/modules/cjs/loader.js:684:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)
    at executeUserCode (internal/bootstrap/node.js:342:17)
Waiting for the debugger to disconnect...

tried npm install -g @vue/cli-service-global but it doesnt work as well.. plese help! thanks!
Answer: This works for me
launch.json :
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Jest",
      "program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
      "args": ["-i"],
      "skipFiles": ["<node_internals>/**/*.js", "node_modules"]
    }
   ]
}

Vue + jest debug


Confused about the statistical test to use

Question: I am a little bit confused about the statistical test I should use. The following is my case:
I am measuring participants' personality traits (agreeableness, extraversion, conscientiousenss, openess, neuroticism) and I asked them how likely it would be that they performed five different actions on a 7-point scale (let's call them A, B, C, D, E). So the data I have are the 5 personality traits that I measure and the 5 response actions on a 7-point scale.
What I want to know is whether the likelihood that they would perform the actions can be explained by the score of each of the personality traits.
For example; someone who scores high on neuroticism is more likely to involve in action A than one of the other actions.
I was thinking of a repeated measures anova as I am measuring 5 times the response action for each participant, but how do I handle the 5 personality traits as they are also with-in subjects
Answer: The likelihood of action is surely the dependent variable.
So one way to do it would be 5 separate ordinal logistic regression models - one for each action.  If you wanted to look at all 5 actions at the same time you would need a multivariate ordinal logistic regression, which is something I have not seen done (but it ought to be possible)
Comment: Thanks for the reply. Why would a logistic regression do? Each participants gives a score on each of the personality traits. It is not that there is just one trait for one participant. For example; a participant can have agreeableness (2.3), extraversion (3.1), conscientiousenss (4.2), openess (1.2), neuroticism (2). Wouldn't this still be something like a repeated measures even though splitting up the DV's?
Comment: The dependent variable is the score on likelihood of taking an action. This goes from 1 to 7, so that's why you need ordinal logistic. The independent variables would be the personality scores, having multiple independent variables is no problem. There is no repeated measure here.
Comment: Ok, thanks for the explanation. Somehow when I add the personality as IV, it splits all the possible scores participants gave into separate variables instead of just taking the range of each personality trait. So for example, it analyzes extraversion score 1.25 separately, 1.50, 1,63 and so forth instead of taking everything as one
Comment: You have somehow made those variables categorical,


validation for greater than 10

Question: Hi i am building web application asp by using Jquery.
I am stock in validation, for example
myfirstnumber
<input type="number" value="F" class="1" id="myfirstnumber"/>

mysecondnumber
<input type="number" value="S" class="1" id="mysecondnumber"/>

mypercenttextbox
<input type="percentage" value="P" class="1" id="mypercenttextbox ">

I need to do validation if in mypercenttextbox is greater than 10.
I am using jquery for this solution
function ValidatePayAdjustmentFormFields(){

    var isValid = true;

    var FirstNumVal = $("[id$="+ ctrlFirstNumVal).val();
    var SecondNumVal =  $("[id$="+ ctrlSecondNumVal).val();
    var percentVal= (SecondNumVal - FirstNumVal ) * (100/SecondNumVal );

    if ($.trim(percentVal) >= 10)

{
        //calling handleError from other function
        handleError("mysecondnumber" ,"your mysecondnumber is more than 10% of myfirstnumber ")

        isValid = false;

    }

}
        return isValid;
}

Error: Uncaught SyntaxError: Illegal return statement
Any kind of help and tip will be appricated. Thank you
Answer: There is a closing curly bracket too much in your code, above the return line. (Which is, if you think of it, what the error message is telling you: the return statement occurs in an illegal place ;))

validation for greater than 10


How can I find an element from jquery.cache object which jquery uses for data storing

Question: I need a way to find the element of stored data on jQuery.cache object.
As you may now jQuery stores data as following syntax:
$('#idOfTheSelector').data('dataKey','dataValue);

jQuery stores this data in $.cache object as ;
$.cache[1].data.dataKey = 'dataValue';

my question is:

how jQuery associates the data with the element? and
Can I find a associated element of stored data?
Answer: Why don't you just use $('#idOfTheSelector').data('dataKey')? It will return you whatever your stored in it.
Comment: my english is not perfect. Did I write something wrong not for sure but if I did for the correction; I want to find the element of the stored data not the data itself.
Comment: You mean you have the `dataKey` and you want to find out which element this `dataKey` is associate with?
Comment: I kind of... and not just dataKey I know the exact location of the data. I mean location of the data in the $.cache object. e.g: $.cache[1].data.dataKey1 $.cache[4].data.dataKey3 ...


Is this the solution of the fourth Landau's problem correct?

Question:
First, consider that to prove that there infinitely many primes of the form $p=n^2+1$, consider that if we select a $c \in \Bbb N$, $c>0$, that if we say, for example, that $c=4$, and we want to prove there are infinitely many primes of the form $p=4n+l$, proving that, is equivalent to proving $p-l=4n$, so, consider $p, p-1, p-2, p-3$, since there are 4 numbers in here, and one is the successor of the other, one of them has to be a multiple of four, (assuming that $p$ is odd), we can say neither $p$, neither $p-2$ are multiples of four, but $p-1$ and $p-3$ can be. So, we have just proven that there are infinitely many prime numbers of the form $p=4n+1$ and also, of the form $p=4n+3$.

But using this argument, we can prove that there are infinitely many prime numbers of the form $p=cn+1$, where $c>1$, can such a thing mean, that if we say $c=n$, we'll have a proof of the fourth Landau problem?
Answer: No, you did not prove that there are infinitely many primes of the form $4n+1$ and that there are infinitely many primes of the form $4n+3$. All that you proved was that there are infinitey many numbers $n$ such that $4n+1$ is prime or $4n+3$ is prime.
Now, suppose that it is true that, for each $c\in\mathbb N$, there are infinitely many $n$'s such that $cn+1$ is prime (by the way, this is true, by a theorem due to Dirichlet). Can you jump from here to the assertion that there are infinitely many primes of the form $n^2+1$ just by taking $c=n$? No, you cannot. If you could, then you could also jump from the fact that there are, for each $c\in\mathbb N$, infinitely many primes of the form $cn-1$ (which is also true) to the conclusien that there are infinitely many primes of the form $n^2-1$. However, since $n^2-1=(n+1)(n-1)$, $n^2-1$ is never a prime number, unless $n=2$.
Comment: How do you actually know that if using the things I proposed, we **having** a proof of the fourth Landau problem is equivalent to saying that, we have a proof that there are infinitely many primes of the form $p=n^2-1$? That does not make much sense to me.
Comment: And if you could explain, or link me to the proof of the Dirichlet theorem of which you referenced, I'd be thankful.
Comment: I have added a link to Dirichlet's theorem.
Comment: Concerning your first comment, I did **not** say what you claim there. What I wrote was that if you think that we can jum from $cn+1$ to $n^2+1$ just by taking $c=n$, then you should also think that we can jump from $cn-1$ to $n^2-1$.


Find an integer n and rational, not integers, r and s such that n= r² + s². Number Theory

Question: I'm trying to apply theorems that I know, but they're all about integers. I really don't know how to solve this problem, in Number Theory, with rational.
"Find an integer $n$ and rational, not integers, $r$ and $s$ such that $n = r^2 + s^2$"
Answer: Hint:
Think about Pythagorean triples. For example, $3^2+4^2=5^2$. Now try dividing that equation by some appropriate number.


What is $E[ \sum_{n = 1}^\infty X_n]$ when $E[X_n] = 0$, $E[X_n^2] = \frac{1}{n^2}$ and $\sum_{n = 1}^\infty X_n < \infty$ a.s?

Question: Suppose $(X_n)$ is a sequence of independent real valued random variables, such that $E[X_n] = 0$, $E[X_n^2] = \frac{1}{n^2}$ and $\sum_{n = 1}^\infty X_n < \infty$ a.s. I need to compute $E[ \sum_{n = 1}^\infty X_n]$, but I do not know how to start. Help is much appreciated :)
Comment: $E[ \sum_{n = 1}^\infty X_n^2] = \frac{\pi^2}{6}$ so $E[ \sum_{n = 1}^\infty X_n]$ is finite and so will be  $\sum_{n = 1}^\infty E[  X_n]=0$
Comment: @Henry a quick question, may I ask why we must show first that $E[ \sum_{n=1}^\infty X_n^2] = \frac{\pi^2}{6}$ ? What allows us to say this immediately yet we cannot say that $E[\sum_{n=1}^\infty X_n] = 0$ immediately?
Comment: @Henry Why is $E\sum X_n$ finite and how does that justify interchange of sum and expectation? I have an example where $\sum E|X_n| =\infty$.
Answer: The series $\sum X_n$ converges in $L^{2}(\Omega, \mathcal F, P)$ because it is Cauchy: $ E(\sum\limits_{k=n}^{m} X_k)^{2}=\sum\limits_{k=n}^{m} \frac 1 {k^{2}} \to 0$ as $m>n \to \infty$. This implies convergence in $L^{1}$ also. Hence the mean of $\sum X_k$ is the limit of the means of the partial sums which is $0$.
Comment: Could we also use the dominated convergence theorem?
Comment: No. DCT is not applicable here. When $X_n$ takes the  value $\pm \frac 1 n$ with probability $\frac 1 2$ each the sereis $\sum |X_n|$ diverges with probability $1$ (even though $\sum X_n$ converges with probability $1$!). I see no scope for application of DCT here. @SiemvanBenthem
Comment: How can we conclude the last line. That the mean of the series equals the limit of the mean of the partial sums?
Comment: @SiemvanBenthem If $E|Y_n-Y|^{2} \to 0$ then $E|Y_n-Y| \to 0$ and $EY_n \to EY$. Take $Y_n$ to be the $n-$th partial sum of the series.
Comment: How does the convergence of $EY_n \rightarrow EY$ follow from the $L^1$ convergence? That is not clear to me.
Comment: @SiemvanBenthem $|EY_n-EY|=|E(Y_n-Y)| \leq E|Y_n-Y| \to 0$.
Comment: Yeah sure! Great work :) Thanks a lot
Comment: Would it not have been easier to show that the series is Cauchy in L1?
Comment: @SiemvanBenthem Somehow the fact that $EX_i X_j=EX_iEX_j=0$ has to be used in the proof and we cannot use this  in $E|Y_n-Y|$. It is natural to square $(Y_N-Y)$ and use this fact in the proof.
Comment: True, I understand


Harmonic series role in a just intonation interval ranking?

Question: In my studies, I was reflecting on this theory and just wanted your guys clarification..
A pitch in an octave is comprised of a fundamental frequency followed by its overtones. When we focus on an interval, its harmonic stability or instability is evidently stemming from the interaction of the two pitches harmonic series combined. As we add additional pitches to that interval, the relationships become furthermore complex due to additional overtones combined.
If I wanted to build a chord through selecting the intervals myself that would produce the desired level of consonance/dissonance, I would have to seek each pitches overtones in that chord and compare them to each other pitches overtones in that chord which would be rather tedious.
Is it because of this that the just intonation interval ranking was developed? Was it developed with the intention of making the stated above process easier by giving us a list of intervals and their ratios dictating the two pitches overtone relationships?
Is it also true that the manner in which the interval ranking functions in its process, is through providing a ratio for an interval with the ratio stating that in the case of the ratio 3:2 (Unison:Perfect 5th) the unison pitch has to perform 3 cycles and the perfect pitch 2 cycles for their wave crests to coincide, therefore determining their level of consonance/dissonance and this process in fact displays an accurate representation/translation of two pitches overtone interaction?
This would explain a lot for me. Thank you guys.
!!EDIT!!

Here is the math formula provided by WillRoss1, simplified. Here you go Albrecht Hügli.

"Formula for producing a chord ratio by any infinte amount of interval ratios."
In this example we will utilize the Major 7th Chord, with the intervals Major 3rd (4:5), Perfect 5th (2:3) and Major 7th (8:15). This formula below applies to infinite amount of intervals you want to combine by following the exact process below.

FORMULA

Step 1. Mutipy the first interval ratio (4:5) by the result of multiplying all the other interval ratios first numbers by each other (2 and 8). 2 x 8 = 16.
16 x 4 = 64 / 16 x 5 = 80.
Step 2. Multiply the second interval ratio (2:3) by the result of multiplying all the other ratios first numbers by each other (4 and 8). 4 x 8 = 32.
32 x 2 = 64 / 32 x 3 = 96.
Step 3. Multiply the third interval ratio (8:15) by the result of multiplying all the other ratios first numbers by each other (4 and 2). 4 x 2 = 8.
8 x 8 = 64 / 15 x 8 = 120.
Your Major 7th Chord ratio is 64:80:64:96:64:120.
Step 4. Since there are duplicate numbers (64) in the chord ratio, we can turn the ratio instead into 64:80:96:120.
Step 5. To further summarize this chord ratio, we find the common factor (a single number that can produce each of the four numbers) for 64,80,96 and 120 which would be 8.
Step 6. Divide 64, 80, 96 and 120 each by 8.
64 ÷ 8 = 8
80 ÷ 8 = 10
96 ÷ 8 = 12
120 ÷ 8 = 15.
Your Major 7th Chord ratio is now 8:10:12:15.
Comment: The set of overtones depends on the instrument and how it's played. Any note interval ranking is bound to be an approximation and a compromise. And the basic sine-vs-sine dissonance figure is an approximation as well, and what happens with a combination of sines (i.e. overtones) is just an assumption and a model. If the model is wrong, the calculated result is wrong. Whenever the model seems to be in conflict with real-life experience, the _model_ needs refining.
Comment: @ggcg Yes I am aware that the frequencies in a harmonic series are multiples of a fundamental frequency, that should be basic knowledge. The point is that timbres affect the sensory dissonance of note combinations. The OP might not have really realized this. This guy explains the theories https://sethares.engr.wisc.edu/consemi.html In that article he's trying to match timbres and tunings... weird stuff. IMO, it's so much easier to play guitar or piano, listen to what comes out and adjust the notes according to taste.
Comment: @piiperi, how does the overtone series depend on instrument?  Can you give some examples
Comment: @ggcg Every instrument has its characteristic timbre, which is basically a set of overtones and their strengths. "_Timbre is the quality that gives the listener the ability to distinguish between the sound of different instruments. The timbre of an instrument is determined by which overtones it emphasizes._" https://en.wikipedia.org/wiki/Overtone   This has implications to the total "sensory dissonance", because not only the fundamental of each note, but also all the overtones (are assumed to) create varying levels of dissonance with all other overtones of all sounding notes.
Comment: But in most cases that sequence is the same, n*f0.  You are correct in that the instrument as well as the attack will emphasize some harmonics over others, but they all fall approximately in the same sequence.
Comment: There is also an intrinsic nonlinear response in the ear that creates harmonics.   I'm not suggesting that the instrument doesn't matter but you can never turn the harmonics off in the human experience
Answer: I may be misunderstanding your question or your intent but what I read form it makes me think you are putting the cart before the horse, at least historically.
I think the ranking of just intervals in terms of perceived dissonance or consonance came before our understanding of harmonics in physics.  People observed sympathetic resonance in vibrating systems but I do not think the ancient Greeks knew that a plucked string had a specific harmonic content or that there was interference between the harmonics leading to "dissonance".  People judged these qualities based on what seemed like subjective criterion, just as one might judge warm days to be more pleasant than cold days (another subjective judgement that whole cultures or people may agree on).  Helmholtz attempted to provide a physics/math based explanation for the apparent "universal agreement" on what is consonant vs dissonant using harmonic analysis.  Basically intervals with many harmonics that line up are more likely to fall into the consonant group while those with many conflicting harmonics that produce interference are likely to by judged as dissonant.  Keep in mind that consonant is taken to mean "pleasant" or "harmonious" while dissonance is taken to mean "tense" or "unpleasant", "unharmonious".  There is a mapping between what is now thought of as a technical term with subjective descriptors and people do not always agree.
To your question about whether or not harmonics were the cause of reason that intervals were placed into categories (which is my interpretation of your question) since people were not consciously aware of this when they made the judgement I would say that that was a "reason" for labeling intervals this way.  It may be that harmonic analysis is used now to try and objectively place intervals in a ranking system but the way you stated the question makes me think you are asking about the historical assessment of intervals.  And again, even if we use what seems like an objective criterion to rank intervals it does not mean that people will agree with the subjective judgement of pleasant or unpleasant.
Comment: Great read and great answer which satisfied my query. You were accurate in answering my question. Thank you ggcg!
Answer: I am answering here knowing this is rather a comment (and I'm afraid they will delete it again but I don't mind).
I am - and have always been - very interested in the relationship of math and music and the fundamentals of acoustic and physics. I hope I'll understand one day the complexe matrix that you got the other day  but I'm afraid I won't understand your analysis of the 5th symphony of Beethoven in this system.
You're questions are very inspiring but I don't know whether this is the ideal approach to music, harmony and composition: Mind that the first experiments with intervals by Pythagoras et all (Aristoteles, Ptolemeus, Boethius, Hucbald, Glarean, Tinctoris,  were built on the monochord and they were not researching  chords but  scales and describing the modes. I have also collected many books since of Zarlino, Fux, Schönberg and Hindemith and articles about their theories since I've been active in this Stack Exchange. (They all say that the music of the antic Chinese, Egypt, Greek, Roman and Byzanthinian was not polyphonic but the longer the more I'm doubting about this assumption.
I think the confusion in your approach is:
a) you can't ignore the function of the chord in the progression with other chords or with its own inversions.
b) there is an objectif consonance/dissonance concept that isn't congruent with what we are hearing and interpreting - depending of our earlier experiencies and the actual context of a chord in a piece of music it's connection with other the voice leading.
The art of arranging is not the arranging of art.
Somehow you remind me of this guy (but this is a joke!) who is trying to make an new order in artworks by ordering the elements in a picture the correct way.

(min.5)
"We Swiss are famous for chocolate and cheese. Our trains run on time.
We are only happy when things are in order.
But to go on, here is a very good example to see.
This is a picture by Joan Miro.
And yeah, we can see the artist has drawn a few lines and shapes
and dropped them any old way onto a yellow background.
And yeah, it's the sort of thing you produce when you're doodling on the phone.
(Laughter)
And this is my --
(Laughter)
-- you can see now the whole thing takes up far less space.
It's more economical and also more efficient.
With this method Mr. Miro could have saved canvas for another picture.
But I can see in your faces that you're still a little bit skeptical.
So that you can just appreciate how serious I am about all this,
I brought along the patents, the specifications for some of these works,
because I've had my working methods patented
at the Eidgenössische Amt für Geistiges Eigentum in Bern, Switzerland.
(Laughter)
I'll just quote from the specification.
"Laut den Kunstprüfer Dr. Albrecht --"
It's not finished yet.
"Laut den Kunstprüfer Dr. Albrecht Götz von Ohlenhusen
wird die Verfahrensweise rechtlich geschützt welche die Kunst
durch spezifisch aufgeräumte Regelmässigkeiten
des allgemeinen Formenschatzes
neue Wirkungen zu erzielen möglich wird.")
Ja, well I could have translated that, but you would have been none the wiser.
I'm not sure myself what it means but it sounds good anyway.
I just realized it's important how one introduces new ideas to people,
that's why these patents are sometimes necessary.
I would like to do a short test with you.
Everyone is sitting in quite an orderly fashion here this morning.
So I would like to ask you all to raise your right hand. Yeah.
The right hand is the one we write with, apart from the left-handers.
And now, I'll count to three. I mean, it still looks very orderly to me.
Now, I'll count to three, and on the count of three
I'd like you all to shake hands with the person behind you. OK?
One, two, three.
(Laughter)
You can see now, that's a good example: even behaving in an orderly, systematic way
can sometimes lead to complete chaos!*"
*) translation:
"According to the art examiner Dr. Albrecht Götz von Ohlenhusen, the procedure is protected by law which art by specifically tidy regularities of the general vocabulary of new effects is possible to achieve."
Comment: You say the demonstration in the Ted Talk is a joke (and I'm not saying it isn't), but I see it as an absolutely incredible interpretation and representation of art. It indeed is an art form of its own. I could totally see an entire gallery of famous artwork meticulously organized and sorted like this. I would absolutely go see it and it would do wonders for my overactive left brain!
Comment: I am completely fascinated by the relationship between art and science. At the most fundamental level, science is art that we cannot control and art is science that we can control.
Comment: Hi, Will, I agree that what this comedian is doing is a very special kind of art too. I remember when I was about 14 years old we did something similar at school in our drawing lessons, we cut the elements of a picture of Paul Klee and rearranged them in a new puzzle (and at the college we did the same in our own drawings of the silhouettes of houses and roofs. And now you remind me that it is quite the same what I try to do with e.g. the inventions of Bach. (Btw you are the guy I was referring to when I spoke about the matrix of intervals and chords described by their frequencies). Great job!
Comment: Is this what you are referring to?

**|** (A1 x (A2 x A3 x A4)): 4 x (2 x 8 x 4) = 256 **|**
(B x (A2 x A3 x A4)): 5 x (2 x 8 x 4) = 320  **|**
(A2 x (A1 x A3 x A4)): 2 x (4 x 8 x 4) = 256  **|**
(C x (A1 x A3 x A4)): 3 x (4 x 8 x 4) = 384 **|**
(A3 x (A1 x A2 x A4)): 8 x (4 x 2 x 4) = 256 **|**
(D x (A1 x A2 x A4)): 15 x (4 x 2 x 4) = 480 **|**
(A4 x (A1 x A2 x A3)): 4 x (4 x 2 x 8) = 256 **|**
(E x (A1 x A2 x A3)): 9 x (4 x 2 x 8) = 576 **|**
Comment: Yes. I wish my left and right brain would be in that balance.
Comment: Example: the art of the fuge ... or Bartok! e.g. something like this: http://archiv.ub.uni-heidelberg.de/volltextserver/15224/1/Parallele_Stimmfuehrung_bei_Bartok.pdf
Comment: Yes, grace to your questions I found already a lot of interisting sites quoting also Boethius, Zarlino, Euler et all ... translating the Latin sources to English. So I can try to learn the acoustic and harmonic laws and the Latin and English language in one! If you can't post your links here please send them to my e-mail or to my facebook account
Comment: @AlbrechtHügli I just pasted the formula in my post up above where it says edit! If you need any clarification just ask.
Comment: @AlbrechtHügli "I hope I'll understand one day the complexe matrix that you got the other day" are you referring to the math formula provided by WillRoss1 explaining how to build chord ratios? If so i can paste here a simplified version of that formula. I will be approaching chord function for context once i've established some current concepts im working on. I found the video to be interesting and thank you for the captions!


How can I add a start and end date range in views exposed filter for Drupal 9 webform submission data?

Question: I have created a view which displays all the webform submission data, but when it comes to views exposed filter for the dates I'm unable to find a way to add a webform submitted date as a range, I did add the dates separately giving an offset value but this isn't working as a range. is there a way to get a single date as range?
Answer: Date data filters come with some options about how to filter them. You don't need to use two Date filters for the range, you do it on the one Date filter.
You need to choose the Is between Operator:


Get variable from object method in javascript

Question: I'm new to objects in javascript and I'm having some problems with the following code.
var Color = function(color){
   this.color = color;
   this.getCode = function(){
      var colorHex;
      var colorRBG;
      switch(color){
          case "White":
              colorHex = "#ffffff";
              colorRGB = "255,255,255";
              break;
          case "Black":
              colorHex = "#000000";
              colorRGB = "0,0,0";
              break;
          default:
              return false;
      }
      return {
          colorHex: colorHex,
          colorRGB: colorRGB
      }
   }
}

What I want to do is get the colorHex value like this but it isn't working:
var newColor = new Color("White");
alert(newColor.getCode().colorHex);

What am I doing wrong?
Comment: it **is** working, http://jsfiddle.net/JQYED/1/ in Chrome
Comment: This is a simplified version of my actual application. Maybe I've another bug somewhere because I keep getting an "undefined" value in my app.
Answer: you need to switch(this.color)
Answer: You need to use this.color instead of color in your switch statement.  Color would be undefined here and the default case would be called.
Color (the parameter) is no longer in scope, so you need to access the member variable.  Javascript does not automatically prepend this like other languages do, you have to do it manually.
Comment: I tried that but I keep getting "undefined"... I'll post the code below.
Comment: Really?? You could try: `newColor.getCode.call(newColor)` to hack it.  Changing `switch(color)` to `switch(this.color)` should work though...
Comment: I just got it! I was passing a value of "colro" instead of "color" to the function that's why. I didn't see it and this was driving me crazy. BTW, it works fine with just "color" in the switch statement.


How to calculate the Expectation of a sufficient statistic

Question: Suppose $X$ follow an exponential family of distribution with the density function $f_{\theta}(x) = a(\theta)h(x)exp\{T(x)^T \theta\}$, where $\theta \in R^k$, $a(\theta), h(x)$ are given functions. Find the mean of $T(x)$.
I don't know what I need to do next step after I write the joint density function. Any help or hint is welcome
Comment: See https://en.wikipedia.org/wiki/Exponential_family#Moments_and_cumulants_of_the_sufficient_statistic.
Comment: Still confused...
Answer: The idea, as it presented in the wiki link in the comments, is that you cannot compute it directly. Namely,
\begin{align}
E[T(X)] = \int_x a(\theta) T(x)  \exp\{T(x)\theta\} dx
\end{align}
note that $ T(x)  \exp\{T(x)\theta\} = \frac{\partial }{\partial \theta}\exp\{T(x)\theta\}$, hence, under mild regularity conditions, you can interchange between the integral and the derivative, i.e.,
\begin{align}
E[T(X)] & = \int_x a(\theta)  \frac{\partial }{\partial \theta}\exp\{T(x)\theta\} dx\\
& = a(\theta)\frac{\partial }{\partial \theta}\int_x   \exp\{T(x)\theta\} dx
\end{align}
now recall that, by definition of a proper density function, $\int_x  \exp\{T(x)\theta\} = 1 / a(\theta) $, thus
$$
E[T(X)] = a(\theta) \frac{\partial }{\partial \theta} \frac{1}{a(\theta)} = - \frac{a'(\theta)}{ a (\theta)} = - \frac{\partial }{\partial \theta} \ln ( a ( \theta))
$$


Linux won't boot after install for Dell PowerEdge 2850 in SCSI Mode

Question: I was successfully able to install CentOS 6.5 x86_64 Minimal from CD, and setup software raid during the install steps, after having set the Dell PowerEdge 2850 to SCSI Mode which enabled CentOS to see all the drives. Everything appeared to go smoothly, like previous installs I've done on other servers (perhaps not this same make/model) and desktops.
But, after rebooting the server acted like it didn't know there was anything to boot. I checked BIOS boot priorities and the LSI boot tool and made sure things looked like they were setup to boot. During the post boot up I see the drives listed as expected.
It appears to just hang, as well, no message about failing to find a bootable device. It just hangs after the IPMI step I believe.
Any ideas why the server is acting like it can't see the OS to boot?
Thanks
Comment: Drivers or firmware?  I seem to remember having the same problem with a Dell server of that vintage, which I solved by upgrading the controller firmware from the 1.00 version which wasn't supported in CentOS to... Well, the most recent one (at the time), which worked just fine.
Comment: Thanks for the suggestion. I'll see if there's anything to that.
Answer: Is it a GPT partition table? If so, you need a bios_grub aka "Reserved BIOS boot area" partition (not the same as /boot) or things don't work right, especially with software raid. Also with grub and Linux softraid, your /boot should be raid1, and ideally not metadata 1.2.


MySQL View, get result from stored procedure

Question: I would like to create a view on MySQL, and the content will be read from stored procedure, is that a way to make it?
Which mean when I exec "mystoredProcedure()" I will receive a list of result, can I use view table to exec it, so result will directly show on view table.
Please advice me if you have any other solution.
Appreciate your help.
Thank you
Comment: A view can only contain a SQL `SELECT` query, not a `CALL` statement.
Answer: I don't think it's possible. The syntax of CREATE VIEW requires a SELECT statement, but a stored procedure is executed with a CALL statement.
Comment: how about get stored procedure result from sql function? is that possible?
Comment: No, a function can only return one value, not multiple rows or columns.
Comment: ok, thank for you help, if u have others way to make it, may be u can share it to me. thank you
Comment: If I could think of anything I would have put it in the answer. I really don't think it's possible in any way.
Answer: If you have access to the stored procedure, you can do something like this inside the procedure:
CREATE OR REPLACE TEMPORARY TABLE tmpData (id int PRIMARY KEY, name varchar(50)) ENGINE=MEMORY;

then insert the data you want to return.
When you want to use the result or even join it somewhere, just call ABC, after that then you can reference the tmpData table.
Note: temporary tables are visible only in your session, it will not interfere with others, but it's a good idea to name them as unique as possible so it will not hide any real tables with the same name. I always use tmp prefix.


transformar string em array Multidimensional

Question: Eu tenho a string a baixo e já tentei transformar ela em um array Multidimensional mas não sei como se faz, outro problema que eu não consigo resolver são os espaços, mesmo usando um explode eles permanecem no array. qualquer ajuda é bem vinda.
O array multidimensional que eu quero é esse:
Array(2) ( [0] => Array ( [0] => 12/ 8/2008 [1] => 0 [2] => maria [3] =>  online) [1] => Array ([0] => 13/ 5/2013 [1] => 0 [2] => joão [3] => off));

Meu codigo.
$string = "0/ 0/0  0  maria online 0/ 0/0  0  joão off";

$ar = explode(" ", $string);

print_r($ar);

Comment: Se você conhece a função explode, e provavelmente conhece as estruturas de repetição, acho que tem que trabalhar a lógica de programação agora!
Comment: Uma dúvida a data você acrescenta como? Ou a data já vem na string?  O comando ```trim($variavel)``` remove os espaços no início e final da variável. Porque se você tem estes dados separados e agrupa, se ficar tipo ```$string = "0/0/00  maria online 0/0/00  joão off"; ``` fica melhor para depois separar certinho.
Answer: Acho que tem um jeito melhor, mas não consegui pensar direito nesse jeito. mas acho o que eu fiz serve.
<?php

$string = "0/ 0/0  0  maria online 0/ 0/0  0  joão off";
$count = 0;
$ar = explode(" ", $string);
foreach ($ar as $ar) {
    if($ar != ""){
        if ($count <= 4) {
            $dbArray[0][] = $ar;
        }else{
            $dbArray[1][] = $ar;
        }
        $count++;
    }
}

/*
versão sem loopping ou condicionais
$dbArray = [
    0 => [
        0 => $ar[0].$ar[1],
        1  => $ar[3],
        2 => $ar[5],
        3 => $ar[6]
    ],
    1 => [
        0 => $ar[7].$ar[8],
        1  => $ar[10],
        2 => $ar[12],
        3 => $ar[13]
    ]
];
*/
var_dump($dbArray);

Answer: Obrigado pela ajuda vinicius, com seu incentivo eu consegui fazer dessa forma.
 $string = "0/ 0/0  0  maria online 0/ 0/0  0  joão off";
 $explode = explode(" ", $string);
 foreach ($explode as $explode) {
 if($explode != ""){
        $dbArrayy[] = $explode;
 }
};

$result = array_chunk($dbArrayy, 5);

print_r($result);

//resultado
Array ( [0] => Array ( [0] => 0/ [1] => 0/0 [2] => 0 [3] => maria [4] => online ) [1] => Array ( [0] => 0/ [1] => 0/0 [2] => 0 [3] => joão [4] => off ) )

Comment: Blz, não conhecia `array_chunk()`


Printing JSON in HTML TABLE saved from another table using local storage so that i print my table on another page

Question: In my assignment i have to take the data from user input using and save data in local storage. I have to print this data from local storage in horizontal table format to other pages.For this i made the code for user input and saving data in local storage

   <input type="button" id="bt" value="Submit Data" onclick="submit()" />

   <input type="button" onclick="insRow()" id="addPOIbutton" value="Add values"/>

           WEEK NO
           Daily exercise
           calorie
           food
            Revision no
           Delete?

           <input size=25 type="text" id="weekbox"/>
           <input size=25 type="text" id="latbox"/>
           <input size=25 type="text" id="lngbox"/>
           <input size=25 type="text" id="lnbox"/>
           <input size=25 type="text" id="lntbox"/>
           <input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)"/>

Table is not printing when i click on button in second page . its gives me blank page . Any lead would be appreciated.
Comment: you deleted my answer in your old identical post. and you still use fuzzy vocabulary to explain your question. Why ?
Comment: i deleted the question @mister jojo . in this post i clearly mention my doubt why should i dont get my values in table . it it anything wrong in my code . logically it works . please accept my sincere apology  deleting my question . in this post i clearly mention my doubt
Comment: you should ask your questions separately for each technical difficulty you encounter instead of associating them all in a problem that you will never manage to articulate until you have mastered your subject
Comment: ok cool but my doubt is clearly mentioned that what the issue in this .. why my code is unable to populate the data
Answer: This code implements another function to create a horizontal format.
Please read the comments and also try to understand it so that it can help you in the future

    <input type="button" onclick="createHorizontal()" value="Create Table From JSON" />

It also uses CSS to make the elements appear in that format or else it would look different. I advise you to analyze and understand it.
Comment: thanks@Cypherjac for a informative solution..Is there any way to print my chart data in table aligned to chart in chartjs library . my area of concern is to render chart  and print table below it so thats chart points are aligned to table data
Comment: If you are using a bar chart or a line chart -- Since the chart is rendered on a canvas, it has a defined width for example ``. So you can use the same width for your table and divide the width of the cells according to the number of data applied to them, for example if the size of your data is 5, then the width of each cell will be `100px` each and they will align with the chart which is also evenly spaced. You can also use add `labels` property to label the data for example `{ labels: ["data1", "data2"], datasets: [{ ... }] ... }`
Comment: https://stackoverflow.com/questions/62057166/how-to-display-table-from-chart-js-data-in-canvas-js-using-java-script? i asked the question here and test my logic in this way . please help me .  this is urgent for me  please :)
Answer: So I did not find a problem with the first file that inserts the JSON data to the local storage. The problem was with getting the data from the second file

    <input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />

There are comments everywhere so make sure to read them and understand why it works that way. Because this is also a learning process. If you have a question just ask.
Comment: thanks @cypherjac i want to make the header in vertical manner so that data in each header  move row wise
Comment: Here's a tip, since you have the `col_keys` and `col_values`, you can create another array for example `final_array` then create a for loop that runs 4 times: (**the length of either of the above arrays**), then inside the final_array, (which will be an array of arrays) , for example for the **first** array - append the **first** value of the `col_keys` array then append the **first** value of the `col_values` array which is also an array ...  so in this case you will be appending the values of the array and not the array itself. Then you can append the values of the `final_array` to the table
Comment: Another option is changing the approach of displaying the data and choose for instance a `div` block with `display: flex` and `flex-direction: column` and inner `div` blocks with `display: flex` and `flex-direction: row` and you will not need a table header, just add the elements inside their own div block and they will have a horizontal direction
Comment: can u provide me fiddle for second method . first i will done by my self


Types or Methods of Testing Correlation

Question: Suppose I have two variables, which have over 500 data points per variable (though they are not continuous on timeline). what other kind of methods or test in can use in R to test the correlation? Except Pearson, Kendall and Spearman
I know how to do Pearson and Spearman and Kandall test (which is quite basic to my personal opinion).
And if I want to study further about the type of correlation, such as the causality of one to another variable or predictive power of one variable to another. What test is available in R?
P.S. I am a rookie in R. So if u can venture a example in code or package name would be perfect!
Comment: This is a very general question. For "correlation" you have to read about statistical TESTS and correlations formulas, which depend on the types of variables you have (continuous, categorical, binary). For "causality" you should read about EXPERIMENT designs, where you are sure that you spot causality and not correlation. For "predictive power" you should read about statistical MODELS which again depend on the types of variables you have.
Comment: What methods/tests do you already know? Please don't make it look like you didn't even bother gathering some information on the topic before coming here. After all, it's not an uninteresting question.
Comment: I have change the question. Thanks for correcting.
Comment: You will need to find info like this : http://www.mash.dept.shef.ac.uk/Resources/MASH-WhatStatisticalTestHandout.pdf and then try to find a way to apply the approach that suits you in R.
Answer: There are basicly three types of correlation tests
a pearsons correlation is the most common.
It assumes that the data is normally distributed.
To figure out if your variables are normally or non-normally distributed you can use a shapiro-wilk test like this: shapiro.test(variable) info here: https://stackoverflow.com/questions/15427692/perform-a-shapiro-wilk-normality-test .
If your p-value is below <= 0.05, then you would reject the NULL hypothesis that the samples came from a Normal distribution.
If not then you cannot reject the null hypothesis that the data is normally distributed, e.i above 0.05. In other words you can savely (without violating assumptions) do a correlation like this:
cor.test(variable1, variable1, method="pearson")

If the variables are non-normally distributed then you have to use a different correlation test, called "spearmans"
cor.test(variable1, variable1, method="spearman")

A spearmans test works by ranking the data, such that the lowest value is assigened to 1, secondlowest to 2 and so on.
If there are many values that are identical, it will give several tied ranks, if you have a lot of tied ranks or if you have a small data set then a method called "kendall" is more appropriate (or won't give biased estimates of the p-value).
cor.test(variable1, variable1, method="kendall")

You could if you wanted to write it in code like this:
df<-data.frame(x=rnorm(100),y=rnorm(100))
sp_Cov1 <- shapiro.test(df[,1])
sp_Cov2 <- shapiro.test(df[,2])
if(sp_Cov1[2] < 0.05 | sp_Cov2[2] < 0.05) {correlationToUse = 'kendall'
} else {correlationToUse = 'pearson'}

cortest_pvalue<-as.numeric(format((cor.test(df[,1],df[,2], method = correlationToUse)[3]),digits=5,scientific=FALSE))

in this case the correlation would be method="pearson" since it was generated from a normal distribution
There is also a boot-strap correlation for non-parametric data with a low sample size, but i know nothing about it.
I would recommend the book Discovering Statistics Using R - by Andy Fields for more info

Types or Methods of Testing Correlation


Custom internal IP instance

Question: I am trying to setup an instance (landingpage2) to use custom internal ip, after instance is up, I could not ssh to public IP, I even can't ping it.
If I don't use custom internal IP for the instance, everything is working fine.
Did I miss anything?
fwissue@gcp2017-181116:~$ gcloud compute routes list | grep dmz1

default-route-4d479ca761d23b53  dmz1     10.8.0.0/24                              1000
default-route-552ffd32014e8b04  dmz1     0.0.0.0/0      default-internet-gateway  1000

fwissue@gcp2017-181116:~$ gcloud compute instances list

NAME          ZONE        MACHINE_TYPE   PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP     STATUS
landingpage2  us-east1-b  n1-standard-1               10.8.0.2     188.8.131.52  RUNNING

fwissue@gcp2017-181116:~$ ping 18.104.22.168

PING 220.127.116.11 (184.108.40.206): 56 data bytes
--- 126.96.36.199 ping statistics ---
21 packets transmitted, 0 packets received, 100% packet loss

Comment: Seems like your routes are wrong. You tried to define two define routes which are clearly not useable. Use a tracert to see more specific information about the way the icmp packet goes.
Answer: The steps on this article worked fine for me. Here is how I tested:
1) Created a new network
gcloud compute --project=Myproject networks create testnet --mode=auto

2) Opened firewall rules to allow SSH and ICMP
gcloud compute --project=Myproject firewall-rules create allowicmpandssh --direction=INGRESS --priority=1000 --network=testnet --action=ALLOW --rules=tcp:22,icmp --source-ranges=0.0.0.0/0

3) Reserved the static IP 10.128.0.11
gcloud compute addresses create myinternalip --region us-central1 --subnet testnet --addresses 10.128.0.11

4) I created two VMs one with dynamic IP and the second one with the reserved
gcloud compute  instances create "instance-2" --zone "us-central1-f" --machine-type "n1-standard-1" --subnet "testnet" --image "debian-9-drawfork-v20180109" --image-project "eip-images" --boot-disk-size "10" --boot-disk-type "pd-standard" --boot-disk-device-name "instance-2"

gcloud compute instances create my-instance --zone us-central1-f --image  "debian-9-drawfork-v20180109" --image-project "eip-images"  --private-network-ip myinternalip --subnet testnet

5) SSH in the instance using the dynamic internal IP and ping both addressees on the second VM
user@instance-2:~$ ping 10.128.0.11
PING 10.128.0.11 (10.128.0.11) 56(84) bytes of data.
64 bytes from 10.128.0.11: icmp_seq=1 ttl=64 time=1.08 ms
64 bytes from 10.128.0.11: icmp_seq=2 ttl=64 time=0.222 ms

I am certainly able to SSH directly in the in second VM by using its external IP.

Custom internal IP instance


Why is my cron not running as intended?

Question: crontab -e displays
*/5 * * * * /persistent/sitename/scripts/cron-curl.sh
~
~
~
"/tmp/crontab.XXXX1FOZWa" 1L, 51C

Why is it not running every 5 minutes?
Comment: To which Drupal version are you interested? There is a little difference with Drupal 7 that you need to take in consideration.
Comment: Drupal 5. Managed to solve the problem with the help of Brock Boland.
Comment: Thank you; I added the tag. If you resolved your own issue, then post an answer where you explain what you did, and accept it as answer. That would help other users with the same issue, and it will help _Drupal Answers_, which needs accepted answers.
Comment: @kiamlaluno without going into too much details, the url in cron-curl.sh must be the same url as the server. In our case, I was using a test server which has a different url to our site's url. This resulted in cron not running.
Comment: That is what Brock Boland was suggesting, then. Remember to accept his answer; without accepted answers, _Drupal Answers_ (this Q&A site) cannot pass the beta phase.
Answer: Did you modify cron-curl.sh to use the URL for your site? By default, it tries to load http://example.com/cron.php.
Comment: Hi Brock,
curl --silent --compressed http://www.edocr.com/cron.php
Comment: The formatting got messed up there, but is your site at http://www.edocr.com? The other ones appear to be commented out.
Comment: ah...long story short.. edocr.com is my site, but we have few problems due to recent AWS EC2 outage and I need to replace the url with AWS server name - let me try and get back to you quickly

Why is my cron not running as intended?


Accessing field values in node--mycustomtype.tpl.php

Question: I have a content type that contains a field called headshot. This is a file field. In my custom node template file, I need to access the value of the headshot's filename property. dpr($content) produces this for the field:
[field_headshot] => Array
                        (
                            [und] => Array
                                (
                                    [0] => Array
                                        (
                                            [fid] => 53
                                            [display] => 1
                                            [description] =>
                                            [uid] => 10
                                            [filename] => kanderson.jpg
                                            [uri] => public://headshot/kanderson.jpg
                                            [filemime] => image/jpeg
                                            [filesize] => 21669
                                            [status] => 1
                                            [timestamp] => 1337356962
                                            [type] => image
                                            [rdf_mapping] => Array
                                                (
                                                )

                                            [image_dimensions] => Array
                                                (
                                                    [width] => 180
                                                    [height] => 252
                                                )

                                        )

                                )

                        )

I've tried
<img class="speaker_headshot" src="sites/default/files/styles/large/public/headshot/<?php print render($content['field_headshot'][0]['filename']); ?>" alt="<?php print $title; ?>" />

and
<img class="speaker_headshot" src="sites/default/files/styles/large/public/headshot/<?php print render($content['field_headshot']['filename']); ?>" alt="<?php print $title; ?>" />

with no success. How do I access this property?
Answer: To get a web-accessible URL for the file you need to use file_create_url() on the field's uri property. You can also make use of theme_image() so you don't have to write the HTML yourself:
$vars = array(
  'path' => file_create_url($content['field_headshot'][LANGUAGE_NONE][0]['uri']),
  'alt' => $title,
  'attributes' => array(
    'class' => array('speaker_headshot')
  )
);

$img = theme('image', $vars);

print $img;

Since this code will clutter up your template file you might want to consider putting in a preprocess function instead, something like:
function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'headshot') {
    $items = field_get_items('node', $vars['node'], 'field_headshot');
    $image = array_shift($items);

    $image_vars = array(
      'path' => file_create_url($image['uri']),
      'alt' => $vars['title'],
      'attributes' => array(
        'class' => array('speaker_headshot')
      )
    );

    $vars['image'] = theme('image', $image_vars);
  }
}

Then in your template file you can just print $image; to get the HTML output.
Comment: Thank you, but that's more than I need to know! I just need to know how to access the VALUE of the filename attribute, and `$content['field_headshot'][LANGUAGE_NONE][0]['filename']` doesn't work either.
Comment: But just so that I could say I tried, I added your preprocess function to my template.php, and ended up with this error: `Fatal error: Cannot access empty property in /home/www/expo/modules/field/field.module on line 958`
Comment: Ah, sorry about that I get carried away :) `$content['field_headshot'][LANGUAGE_NONE][0]['filename']` is definitely the right variable if your output from `dpr($content)` is right above
Comment: I took a guess at your content type being called 'headshot' (it probably isn't), other than that I can't think of a good reason why you'd be getting that error
Comment: The output is correct; it's pasted directly from the node as rendered. But the variable you provide is NOT returning a value.
Comment: No, my content type is not called headshot. The content type is called speaker; it contains a file field called headshot.
Comment: I'm not sure what to say...you can see from the output that the value you're looking for is at `['field_headshot']['und'][0]['filename']`. If that output has come from a variable called `$content`, then logically your value has to be at `$content['field_headshot']['und'][0]['filename']`. It has nothing to do with Drupal, it's how PHP works
Comment: Yes, I can see that. But that's not what you suggested earlier - your suggestion had [LANGUAGE_NONE] instead of [und].
Comment: [`LANGUAGE_NONE`](http://api.drupal.org/api/drupal/includes%21bootstrap.inc/constant/LANGUAGE_NONE/7). As you can see, `LANGUAGE_NONE == 'und'`. It's the same thing.
Comment: I don't know what else to do here. I tried just printing out the value of the variable, and it returns nothing. If I do dpr($content['field_headshot']), I still get ridiculous nested arrays and objects. I've created [link](http://drupalbin.com/21412) to show what that returns (too long to post in the OP here) - why would printing the value of a single field include ALL of the fields?
Comment: And it's strange, because I can access the value of the job title field with `print render($content['field_job_title'][0]);` - is field_headshot different because it's a file field type, rather than just text?
Comment: It will be different yeah...try `$content['field_headshot']['#items'][0]['filename']`, I think that'll do it according to the output on drupalbin


How do I choose between binomial and Bernoulli family using brms in R

Question: My research question is: is the rate of forgetting (slope) influenced by the degree of encoding? So I have three encoding degrees and three time intervals in which I test people using different items.
Hence, what I need to know is if there is an interaction between the degree of encoding and time interval.
My items are 48 words, and I test 16 different ones at each time interval.
First, I fitted a model like this:
model1 <- brm(
  correct | trials(total) ~ 1 + time * encoding
  + ( 1 + encoding | ID ),
  data = data,
  family = binomial("logit"),
  file = "model1"
)

But then, I realised I need to consider that there will be heterogeneity between the items because some are easier to remember than others. So instead of averaging across items (that will be very much like doing an ANOVA?) I tried to use the 0s and 1s (correct and incorrect responses) to fit another model:
model2 <- brm(
  correct ~ 1 + time * encoding
  + ( 1 + time | ID )
  + (1 + time + encoding | item),
  data = databinom,
  family = bernoulli(),
  file = "model2"
)

I was happy with this, but reading a vignette in brms, I found a comment about a model like this that says: this model completely ignores the guessing probability and will thus likely come to biased estimates and predictions.
However, the words I use don't have 50% chance of being right, because it's not a recognition test. They literally have to write the word down to consider it correct.
All of the above raises the question, do I want to use the binomial family and just forget about the fact that the items are all different? Or should I use the Bernoulli one, which then will tell me the probabilities of getting each item right or wrong, but nothing about the rate of forgetting, which is the number out of 16 that the subjects get correct at the three time intervals.
Comment: Can you explain the experimental paradigm a bit more? Is this free recall?
Answer: In this vignette the author of brms explains how to deal with guessing.
If the guess rate is 50% then
fit <- brm(
  bf(answer ~ 0.5 + 0.5 * inv_logit(time*encoding),
     time ~ (1| ID ) + (1|item),
     encoding ~ item,
     nl = TRUE),
  data = data, family = bernoulli("identity"),
  prior = c(prior(normal(0, 5), nlpar = "time"),
            prior(normal(0, 5), nlpar = "encoding"))
)

I'm not totally sure this is the way you want to specify the random effects or the priors, but the general formulation of a "mixed model" guessing mixed with should help you out.
Comment: I do not know the rate of guessing. In my study, people are not recognising responses. They have to actually remember the word, just like that. Different words have different difficulties, but I don't have the slightest idea of how likely each one is.  There's no way anyone on this planet can tell how likely it is to remember the word "block" and how likely it is to remember the word "president". With the guess rate been unknown, can I still use the bernoulli family without having to state how likely each word is to be remembered?
Comment: sorry, I misread your question! I thought you said "the words I use have a 50% chance of being right"
Comment: I used free recall and then cued recall. So first they freely try to remember, and after that, I suggest semantic categories in which the words fit. For example I say "a domestic animal" and they remember the word "cow" :)
Comment: It's a lot of work but you could generate a prior for the cued recall. Just give people who have never studied the initial word list the cue, and then you have the background rate of saying each word. E.g. if the word to remember is "hamster" and 5% of people say hamster when asked to name a domestic animal, this seems a reasonable guess rate.  For free recall, this is a bit harder, but you could use some known word frequency database.
Comment: Well, it is a lot of work and I have to do this for many experiments with different material. It would be like doing another complete experiment for each one of these just to find priors. Thank you anyway.


Call PowerShell script PS1 from another PS1 script inside Powershell ISE

Question: I want call execution for a myScript1.ps1 script inside a second myScript2.ps1 script inside Powershell ISE.
The following code inside MyScript2.ps1, works fine from Powershell Administration, but doesn't work inside PowerShell ISE:
#Call myScript1 from myScript2
invoke-expression -Command .\myScript1.ps1

I obtain the following error when I execute MyScript2.ps1 from PowerShell ISE:

The term '.\myScript1.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Answer: In order run a script in the same directory.
In PowerShell 3.0 and later you can use the automatic variable $PSScriptRoot:
$PSScriptRoot/myScript1.ps1

In PowerShell 1.0 and 2.0 you should use this specific property:
& "$(Split-Path $MyInvocation.MyCommand.Path)/myScript1.ps1"

The reason you should use that and not anything else can be illustrated with this example script.
## ScriptTest.ps1
Write-Host "InvocationName:" $MyInvocation.InvocationName
Write-Host "Path:" $MyInvocation.MyCommand.Path

Here are some results.

PS C:\Users\JasonAr> .\ScriptTest.ps1
InvocationName: .\ScriptTest.ps1
Path: C:\Users\JasonAr\ScriptTest.ps1

PS C:\Users\JasonAr> . .\ScriptTest.ps1
InvocationName: .
Path: C:\Users\JasonAr\ScriptTest.ps1

PS C:\Users\JasonAr> & ".\ScriptTest.ps1"
InvocationName: &
Path: C:\Users\JasonAr\ScriptTest.ps1

In PowerShell 3.0 and later you can use the automatic variable $PSScriptRoot:
## ScriptTest.ps1
Write-Host "Script:" $PSCommandPath
Write-Host "Path:" $PSScriptRoot

PS C:\Users\jarcher> .\ScriptTest.ps1
Script: C:\Users\jarcher\ScriptTest.ps1
Path: C:\Users\jarcher
Comment: It would be good to see an example use of Split-Path in the answer. You also need to show calling a script inside another script really.
Comment: This is in absolutely no way an answer to the question asked. You are simply explaining how to find the path of the currently executing script, while the question is how to execute a separate script within the one currently executing. It's baffling to see this has been upvoted more than 100 times...
Comment: You need to preface any variable with "& ". In this example it would be: "& $PSScriptRoot/myScript1.ps1"
Comment: A late addition: If you're worried abot variance (or, actually, just want "solid" code) you probably want to use "Write-Output" rather than "Write-Host".
Comment: It absolutely does answer the question.  The piece the questioner was missing was how to find the location of a sibling script in order to run it.  The questioner accepted my answer since it helped them solve their problem.
Answer: I am calling myScript1.ps1 from myScript2.ps1 .
Assuming both of the script are at the same location, first get the location of the script by using this command :
$PSScriptRoot

And, then, append the script name you want to call like this :
& "$PSScriptRoot\myScript1.ps1"

This should work.
Comment: `& "$PSScriptRoot\myScript1.ps1"` is enough
Comment: @GregorSimončič Only if the variable doesn't include whitespace characters. If the variable contains whitespace, the unquoted command would probably introduce a syntax error due to "splitting" the command into two pieces. Keeping the quotes is the safest way to go.
Comment: `& $PSScriptRoot\myScript1.ps1` IS enough (without quotes)
Answer: The current path of MyScript1.ps1 is not the same as myScript2.ps1. You can get the folder path of  MyScript2.ps1 and concatenate it to MyScript1.ps1 and then execute it. Both scripts must be in the same location.
## MyScript2.ps1 ##
$ScriptPath = Split-Path $MyInvocation.InvocationName
& "$ScriptPath\MyScript1.ps1"

Comment: You don't, it's an automatic variable.
Comment: How I have to initialize $MyInvocation variable?
Comment: It works, but obtain the following error before really execution of called script:

Split-Path : Cannot bind argument to parameter 'Path' because it is an empty string.
At line:4 char:25
+ $ScriptPath = Split-Path <<<<  $MyInvocation.InvocationName
    + CategoryInfo          : InvalidData: (:) [Split-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.SplitPathCommand
Comment: create a new script put: $MyInvocation.InvocationName in it and run the script. Do you get the path of the script?
Comment: @JasonMArcher - Why instead? As far as I know both give the same output?
Comment: Added an answer to explain things.
Answer: One line solution:
& ((Split-Path $MyInvocation.InvocationName) + "\MyScript1.ps1")

Comment: That's using current directory not script directory. Sure they're often the same ... but not always!
Comment: This is nice, but why not just `& '.\MyScript1.ps'` if the script resides in the same directory?
Comment: I question the same line - if you run a "Set-Location" command to move to that folder before you call it, that should achieve both by setting the location and making it current at the same time.
Comment: Firstly, that's not one-line any more :). But also, it's only applicable if you don't mind changing the working directory, which is quite the assumption and not good practice.
Answer: This is just additional info to answers
in order to pass argument into the another file
Where you expect argument
PrintName.ps1
Param(
    [Parameter( Mandatory = $true)]
    $printName = "Joe"
)

Write-Host $printName

How to call the file
Param(
    [Parameter( Mandatory = $false)]
    $name = "Joe"
)

& ((Split-Path $MyInvocation.InvocationName) + "\PrintName.ps1") -printName $name

If you do not do not provide any input it will default to "Joe" and this will be passed as argument into printName argument in PrintName.ps1 file
which will in turn print out the "Joe" string
Answer: To execute easily a script file in the same folder (or subfolder of) as the caller you can use this:
# Get full path to the script:
$ScriptRoute = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, "Scriptname.ps1"))

# Execute script at location:
&"$ScriptRoute"

Answer: You may have found the answer for it already, but here is what I do.
I usually place this line at the beginning of my installation scripts:
if(!$PSScriptRoot){ $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent } #In case if $PSScriptRoot is empty (version of powershell V.2).

Then I can use $PSScriptRoot variable as a location of the current script(path), like in the example bellow:
if(!$PSScriptRoot){ $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent } #In case if $PSScriptRoot is empty (version of powershell V.2).

Try {
If (Test-Path 'C:\Program Files (x86)') {
    $ChromeInstallArgs= "/i", "$PSScriptRoot\googlechromestandaloneenterprise64_v.57.0.2987.110.msi", "/q", "/norestart", "/L*v `"C:\Windows\Logs\Google_Chrome_57.0.2987.110_Install_x64.log`""
    Start-Process -FilePath msiexec -ArgumentList $ChromeInstallArgs -Wait -ErrorAction Stop
    $Result= [System.Environment]::ExitCode
} Else {
    $ChromeInstallArgs= "/i", "$PSScriptRoot\googlechromestandaloneenterprise_v.57.0.2987.110.msi", "/q", "/norestart", "/L*v `"C:\Windows\Logs\Google_Chrome_57.0.2987.110_Install_x86.log`""
    Start-Process -FilePath msiexec -ArgumentList $ChromeInstallArgs -Wait -ErrorAction Stop
    $Result= [System.Environment]::ExitCode
    }

} ### End Try block

Catch  {
    $Result = [System.Environment]::Exitcode
    [System.Environment]::Exit($Result)
   }
[System.Environment]::Exit($Result)

In your case, you can replace
Start-process...     line with
Invoke-Expression $PSScriptRoot\ScriptName.ps1
You can read more about $MYINVOCATION and $PSScriptRoot automatic variables on the Microsoft site: https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_automatic_variables
Answer: I submit my example for consideration. This is how I call some code from a controller script in the tools I make. The scripts that do the work also need to accept parameters as well, so this example shows how to pass them. It does assume the script being called is in the same directory as the controller script (script making the call).
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string[]]
$Computername,

[Parameter(Mandatory = $true)]
[DateTime]
$StartTime,

[Parameter(Mandatory = $true)]
[DateTime]
$EndTime
)

$ZAEventLogDataSplat = @{
    "Computername" = $Computername
    "StartTime"    = $StartTime
    "EndTime"      = $EndTime
}

& "$PSScriptRoot\Get-ZAEventLogData.ps1" @ZAEventLogDataSplat

The above is a controller script that accepts 3 parameters. These are defined in the param block. The controller script then calls the script named Get-ZAEventLogData.ps1. For the sake of example, this script also accepts the same 3 parameters. When the controller script calls to the script that does the work, it needs to call it and pass the parameters. The above shows how I do it by splatting.
Answer: I had a similar problem and solved it this way.
My working directory is a general script folder and serveral particular script folder in same root, i need to call particular script folder (which call general script with the parameter of the particular problem).
So working directory is like this
\Nico\Scripts\Script1.ps1
             \Script2.ps1
      \Problem1\Solution1.ps1
               \ParameterForSolution1.config
      \Problem2\Solution2.ps1
               \ParameterForSolution2.config

Solutions1 and Solutions2 call the PS1 in Scripts folder loading the parameter stored in ParameterForSolution.
So in powershell ISE i run this command
.\Nico\Problem1\Solution1.PS1

And the code inside Solution1.PS1 is:
# This is the path where my script is running
$path = split-path -parent $MyInvocation.MyCommand.Definition

# Change to root dir
cd "$path\..\.."

$script = ".\Script\Script1.PS1"

$parametro = "Problem1\ParameterForSolution1.config"
# Another set of parameter Script1.PS1 can receive for debuggin porpuose
$parametro +=' -verbose'

Invoke-Expression "$script $parametro"

Answer: I had a problem with this.  I didn't use any clever $MyInvocation stuff to fix it though.  If you open the ISE by right clicking a script file and selecting edit then open the second script from within the ISE you can invoke one from the other by just using the normal .\script.ps1 syntax.
My guess is that the ISE has the notion of a current folder and opening it like this sets the current folder to the folder containing the scripts.
When I invoke one script from another in normal use I just use .\script.ps1, IMO it's wrong to modify the script just to make it work in the ISE properly...
Comment: Downvoted this because the issue is the failure of the script to work when not run from the folder containing it. It's not about modifying the script to work in the ISE specifically, it's about modifying the script to be portable and flexible enough to handle being run from a different directory. The behavior of the code in this case shouldn't depend on where you've invoked it from.
Answer: You can also use the following commands:
$Patch = Join-Path -Path $PSScriptRoot -ChildPath "\patch.ps1"

Invoke-Expression "& `"$Patch`""

Answer: How do you run PowerShell built-in scripts inside of your scripts?
How do you use built-in scripts like
Get-Location
pwd
ls
dir
split-path
::etc...

Those are ran by your computer, automatically checking the path of the script.
Similarly, I can run my custom scripts by just putting the name of the script in the script-block
::sid.ps1 is a PS script I made to find the SID of any user
::it takes one argument, that argument would be the username
echo $(sid.ps1 jowers)

(returns something like)> S-X-X-XXXXXXXX-XXXXXXXXXX-XXX-XXXX

$(sid.ps1 jowers).Replace("S","X")

(returns same as above but with X instead of S)

Go on to the powershell command line and type
> $profile

This will return the path to a file that our PowerShell command line will execute every time you open the app.
It will look like this
C:\Users\jowers\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

Go to Documents and see if you already have a WindowsPowerShell directory. I didn't, so
> cd \Users\jowers\Documents
> mkdir WindowsPowerShell
> cd WindowsPowerShell
> type file > Microsoft.PowerShellISE_profile.ps1

We've now created the script that will launch every time we open the PowerShell App.
The reason we did that was so that we could add our own folder that holds all of our custom scripts. Let's create that folder and I'll name it "Bin" after the directories that Mac/Linux hold its scripts in.
> mkdir \Users\jowers\Bin

Now we want that directory to be added to our $env:path variable every time we open the app so go back to the WindowsPowerShell Directory and
> start Microsoft.PowerShellISE_profile.ps1

Then add this
$env:path += ";\Users\jowers\Bin"

Now the shell will automatically find your commands, as long as you save your scripts in that "Bin" directory.
Relaunch the powershell and it should be one of the first scripts that execute.
Run this on the command line after reloading to see your new directory in your path variable:
> $env:Path

Now we can call our scripts from the command line or from within another script as simply as this:
$(customScript.ps1 arg1 arg2 ...)

As you see we must call them with the .ps1 extension until we make aliases for them. If we want to get fancy.
Comment: Wow, thanks for this, there is a lot here.  But there are 9 other answers already here.  How does this differ?  What additional information is it providing?
Comment: Doing this allows us to use our custom-scripts inside of other scripts—in the same way that built-in scripts are used inside of our scripts. Do this and as long as you save your scripts in the directory that you put in your path, the computer will automatically find the path of the custom-script when you use it on the command line or in another script
Answer: If the vars above are null, you are probably using PowerShell ISE. In this case try:

if ($psISE)
{
    Split-Path -Path $psISE.CurrentFile.FullPath
}
else
{
    $global:PSScriptRoot
}

Check out this discussion.
Answer: This works for me...
start powershell {./script.ps1}

Comment: Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn't been given previously? **If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren't sufficient.** Can you kindly [edit] your answer to offer an explanation?


How can I justify Null Conclusion based on Confidence Interval ?

Question: My question is as follows:
*An ad claims people prefer S coffee over P coffee. The person randomly samples 80 coffee drinkers and finds 43 prefer S coffee.  The person concludes the claim is probably not true.  How did the person justify this?
(a) 46% is not in the 95% CI
(b) 46% is in the 95% CI
(c) 50% is not in the 95% CI
(d) 50% is in the 95% CI*
I set the Null Hypothesis as S =.5 (there is no difference in the people who like S coffee over P coffee.  Therefore Ha = S >  0.5. (more people prefer S)
I compute the Z value using the proportions formula for z and get $z = 0.53$.  I look this up in the normal z chart for a right-tailed test and find p-value to be about 30%.  I would accept the Null based on such a high p-value.  In other words I would think the ad's claim is not true.  HOWEVER, it would be based on the z value, or corresponding p-value, and not any of the items listed in the question about 43% or 50% being in or out of the 95% CI.
What am I missing here?
Comment: Please add the `self-study` tag, and read the policy on this sort of question in the [help/on-topic], plus the self-study [tag-wiki](http://stats.stackexchange.com/tags/self-study/info).
Comment: Curiously, the conclusion is not justified solely on the evidence given here, which leans (slightly) in *favor* of the claim because over half the sample preferred $S$.  That contradicts the assertion the claim is "probably not true."  One could state, with much better justification (albeit with a conceptually challenging triple negative!), that this sample of coffee drinkers was not large enough to disprove the counterclaim that people do not prefer $S$ over $P$.
Answer: You're correct that up until the point that that the answer options are offered, the question is framed as a hypothesis test, so that's the most obvious way to approach that set-up.
However, at the point you see the answer options it's clear that the question is asking you to look at the confidence interval for the proportion (to see if it contains the case specified under the null) rather than conduct the hypothesis test.
The confidence interval could be thought of as a set of values for the parameter that are (in a very particular sense) "consistent" with the data-set.
As soon as you see those options, it should be clear that if you don't think in terms of the confidence interval, you'll have trouble answering the question.
An aside that doesn't impact what you need to do here: The author(s) of the question seem to implicitly assume that the two procedures would yield the same conclusion, but in in the most commonly taught tests vs intervals for proportions it's not necessarily the case that they will yield the same conclusion. They nearly always give the same conclusion (and they do here), but it's not always so. It's quite possible to choose a different pair of procedures for this situation that will always correspond, though. In almost every other situation you'd learn in an elementary course, they always correspond. Many books and web-pages explicitly state that they always correspond (see here for one example of many; it's wrong on that point but you might find the explanations otherwise useful).
Comment: Glen, thanks, however how would you answer this question?
Comment: I'm not going to explicitly say which option to choose -- see our policy in the [help/on-topic] under *Homework* (NB it doesn't matter if this is actually homework or something else - exam practice, your own study, etc, the policy still applies to explicitly answering that question -- we don't do that). However, you should be able to figure out the answer (without even needing to actually compute the interval, in fact). All the information (not already covered by the question) is already there in my answer;
Comment: The book, which is often wrong lists (D) as the answer.  IT would seem to meth at 50% would always be in the CI. So, unfortunately, I have learned nothing here.
Comment: D is correct (and is the answer *quite directly* suggested by my words "*see if it contains the case specified under the null*" -- how much more explicit could I have been there, other than saying "choose D"?) Did you try calculating a CI for the sample proportion? I suspect you have an error in your thinking in relation to how that works.
Comment: In particular, what's your CI if it had been 49 prefer S (out of 80)?
Comment: But wouldn't 50% always be in the confidence interval of any testing where you are evaluating if one item is preferred more? I can see how it could be that the test statistic of 46% being in the CI would indicate to accept the null, but 50% isn't from any of the collected data.
Comment: This site is suggesting this move to chat.  If you have time, I'd really like to understand this in chat.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/54512/discussion-between-user163862-and-glen-b).


Alternate picking issue

Question: I'm an begginer/intermediate guitar player and I've been practicing alternate picking for a few months now. Everything's fine except for 2 things.
1)I can easily alternate pick at reasonable speeds but whenever I speed things up I can't change strings effectively as I go out of sync the moment i change the string. I've tried avoiding stuff like string hopping and my technique seems fine.
2)Whenever there are some alternate picked chugs on lower E and after that some powerchords/single notes on the following strings, my hand just can't do it, for example:

EDIT: I can actually do this sometimes but can't pull it off without hitting the lower E as long as the others.
Do you have any ideas/tips for me that perhaps worked really great for you?
Thanks in advance!
Answer: To keep alternate picking, the solution is pick slanting with upstroke escape.
After you play the last note on the E string with an upstroke, the pick should end up above the plane of the strings. Then you can hit the next note on the A string, without touching the E string.
This technique is explained by Troy Grady here:
https://troygrady.com/primer/reference/escape-motion-reference/usx-motion/
Answer: Maybe stop worrying about it? Seriously. If you can do 50 pushups in a month do you think should should be able to do 100 in 1 month and 2 days? When you are ready the world provides. It seems you are not ready. No matter what I say(or anyone else) there is something that prevents you from doing it and it is something unrelated to technique. That is, you have other problems and the universe is saying "Nope, can't pass go... pay the fee".
I had the same problems as you... I worked on it too. I got better but always had problems... then I stopped trying and just started focusing on music. Everything comes when needed. I no longer have picking problems because of time and practice.
See, there are a million techniques. Can you rasgueado? What about strum any rhythm? Can you sweep pick well? Do you know all your arps and chord shapes? What about modes?
So much to learn. If you focus only on one thing you never get anywhere. I do get the reason why you do this, it seems natural; It isn't.
Thinks take time to happen. We always want it all now(specially in the modern era where we have to constantly compete with the best of the best since everyone expects everyone to be the best or they suck).
You will improve 10 fold if you just focus on music. Maybe you were not meant to alternate pick fast.
I will tell you though that it is likely you are doing it wrong and it is very likely you neglected other techniques in your pursuit to "master" a single technique and this actually has slowed you down(again, it seems backwards because we think if we just continue to hack away we will eventually get it and we likely really want to do it and don't care too much about the other stuff). But this is now how to works.
I do not know your exact problem because you were not clear. Likely you do not know your exact problem either.
I can say from my experience that I could alternate pick too and learned relatively quickly(it is not a hard technique). I will also say that your alternate picking is probably not as good as you think(better than most but not as close as good as the best).
Sweep picking is critical technique in fast alternate picking and string skipping. Knowing some math also is necessary. You cannot alternate pick everything. All the fast alternate picking stuff done by "shredders" is highly calculated in some sense.
What you mean by going out of sync is vague.
This is how you alternate pick: Every single string set of notes has to end up on a stroke that lets you "sweep" to the next string. This technique seems very awkward but is necessary to have fast and smooth alternate picking. Hence if you never practice sweep picking this likely will cause your alternate picking to be dysfunctional when used over multiple strings. Because alternate picking is binary(up down) one has to match the number of notes played to the direction they are moving to the next string.
E.g., if you have 3 notes played and are moving to the next lower(ground) string then you have | up down up ^ down up ...| but are trying to go up while also having to move the hand down. This is easy slow. It is reckless fast and will take too much time to move which causes issues in timing.
In this case it | down up down ^ up down ... | This is better but now we are going down while changing but we have to overshoot the 2nd string to come back up. This is also easy slow(and should be practiced). I have gotten quite fast as this and I almost always use this method except at the fastest speeds. This is just straight alternate picking.
| up down up ^ up down ... | Try that, that is even more awkward. You can do it though and sometimes it is necessary to change the order to get things to work out later
| down up down ^ down up ... | This is the correct way. The down ^ down is simply a sweeping motion and is most efficient since there is no change of directions of the pick for both strings. Hence it is theoretically as fast as strumming.
You can see though that if you play 2 notes everything has to flip: | down up ^ down ... | and |down up ^ up | fails(2nd one works if you are going the opposite direction to a higher(ground) string).
But here you have to start the with an up stroke so your next note is down | up down ^ down| then continue with a down stroke. You see though this causes problems when you are string to go through multiple strings:
| up down ^ down up ^ ???? | and when we get to the 3rd string we are screwed again.
This is why all those flashy runs are specifically designed to work so one can sweep every motion between adjacent strings. This requires one to choose the correct number of notes per string so it all works out.
This is not difficult but it takes some practice to get a feel for this so you can actually do it naturally.
Again, there is no quick trick. There are many little things involved. If you simply practice music and playing it all comes naturally, is more fun(less boring practice) and you'll be well rounded.
It will happen. Learn from others and don't focus too much on the specifics(you can, even intensely, but don't focus on it for very long). Just know that "I have to pay attention to the notes or it won't come out right. I have to sweep between strings because that is obviously the fastest way. This means how many notes I play matter". If you truly understand the basic ideas that make you have to choose certain number of notes per string, what direction you start with, etc. Then OVER TIME your mind will figure it out as you practice doing similar things(e.g., if you are working on a song or lick or improvising).
You cannot learn to run before you can walk. The universe won't allow it(well, it will but it will make you fall on your face in the process).
It is a key idea in getting good. To recognize the process of learning and that there is no "single technique" that matters. All those fast players simply got fast by playing. They didn't really focus on anything specific. They focused on doing what they wanted(e.g., certain styles or sounds or feelings) and those techniques then progressed. In some sense the less you focus on the specifics the faster you will learn(again, this doesn't mean not to have any clue, it means that you don't spend all(or even most) your time trying to perfect one thing after another.
I will say that you will get better at it with general practice(which includes playing fast alternating and sweeping licks in musical contexts). In some sense, it's like some trick the universe plays on you. The more you focus on X the more it keeps it from you. (it's not like this in reality but it's the same if you try to learn steps in isolation. The reason why you can't take a step is because your trying to use it to run rather than walk like the universe wants you to do. It will let you run only when you want to run for the right reasons and have done enough walking)
Comment: @Tim it's a long incoherent ramble that's mostly unrelated to the question and explains alternate picking as the technique usually known as economy picking.
Comment: This answer needs to be heavily pared down.  You don't address the actual problem in the question until 400+ words in.  Even after that, as ojs said, you're not describing alternate picking.
Comment: Another unqualified dv. How will a newbie know how to improve an answer (which took some writing) without feedback?

Alternate picking issue