Git checkout pathspec error. Command to get the correct path

Question: What am I trying to do:
Replace a single local file (app.py) with the previously committed remote file.
What have I tried:
I can git add a file as follows:
git add app.py
git commit -m "added x "
git push -u sec_aggregator

But when I want to replace the local app.py on my pc with the remote one I tried this:
git fetch
git checkout sec_aggregator/feed/app.py

and got this error:
error: pathspec 'sec_aggregator/feed/app.py' did not match any file(s) known to git

How do you get the correct path please?
Update:
When I do the command git branch
I get this output:
  list
* master

Answer: Let me start with a question.  You ran:
git add app.py

and apparently this worked (you show no error and the subsequent git commit seems to have succeeded as well).  So, should you now run:
git checkout sec_aggregator/feed/app.py

?  Or would it make more sense to run:
git checkout app.py

?  That is, why do you expect to use the full file name sec_aggregator/feed/app.py in git checkout, and the partial (relative to current directory) file name app.py in git add?  Have you navigated to a different directory / folder within your work-tree?
What you probably want here is:
git checkout <some-commit-specifier> -- app.py

since git checkout will use your current folder/directory within your work-tree to resolve the file's full name, the same way that git add does.  The some-commit-specifier part here may be as simple as HEAD~1.
This might be all you need to make progress; if so, feel free to ignore the rest of this answer. :-)  But this is not the only unusual thing in your question.  As Julian noted, you seem to be using the string sec_aggregator as the name of a remote.  This is a pretty unusual remote-name; most people have a repository with only one remote, named origin, and some have a repository in which they have added a second remote, typically called upstream.  It is possible to use pretty much any alphanumeric name as a remote, so sec_aggregator is OK here, but I suspect it's not what you mean to use.  (What was the exact output of this git push anyway?)
Long: about Git repositories, and working with them
So, let's take a look at what a Git repository is, and how different Git repositories talk to each other, because this all relates to your ultimate goal, which I'll repeat here:

[I want to r]eplace a single local file (app.py) with the previously committed remote file.

Although there is a lot of extra machinery to make this all work, at its heart, a Git repository is a collection of commits.1  That is, Git doesn't store files but rather commits.  This collection is a sort of key-value database, with the keys being commit hash IDs (which we will get to in a moment).  Each commit itself stores files—a full, complete snapshot of each file as of its state at the time you (or whoever) made the commit—so if you go down one level, into the commits, you do get files; but the storage-unit, as it were, is the commit.
The files stored in a commit are frozen for all time.  They can never be changed: not by you, nor by Git.  As you can imagine, re-freezing every file for every commit could use up a lot of storage space.  So Git doesn't actually do that.  Instead, each frozen file is in a special, read-only, Git-only, compressed form.  I like to call this the freeze-dried format, although that's not a formal Git term.  That means they take less space, and sometimes a Git repository database is smaller than the files it stores.  But there's an even more useful trick here.  If the previous version of a file is frozen, and we need to make a new commit that has the same version, why not just re-use the freeze-dried copy of the file?  And that's exactly what Git does.  Commits keep re-using existing freeze-dried file copies, so that the growth of the .git directory holding the internal database is controlled.
So, each commit stores files—i.e., data—but that's not all.  A commit also stores some metadata, some information about the commit itself.  For instance, each commit has an author and a committer, usually the same person.  When you make a commit, you become the author-and-committer.  Each commit has a date-and-time-stamp too, or perhaps I should say two, as there's one for the author line and one for the committer line.  You also get to supply a log message giving a reason for the commit.  But there is one more key item in every commit, which Git calls the parent, or for merge commits, parents, plural.
Now, every commit acquires—at the point it comes into existence—a new and unique hash ID.  The hash ID is a big ugly string of letters and numbers that, technically, is the hexadecimal representation of a cryptographic checksum of the contents of that commit.  One reason we can't know what the hash ID of a new commit will be until we've made it is that date-and-time-stamp part: if you make a commit, then remove it,2 then make it again, the second one will have a different time in it and will actually be a different commit, with a different hash ID, even if it stores all the same file contents.
The hash ID is, in effect, the true name of a commit.  Crucially, every Git in the universe will agree that that hash ID—whatever it is—is the one and only correct hash ID for that particular commit: the one with that snapshot of those files, made by you, with your log message, on the date-and-time at which you made it.  So Git can use this hash ID as a unique key, in a key-value database, to store and retrieve this commit, and—importantly—your Git can call up another Git and ask it: Do you have this hash ID?  If they—the other Git—do have that hash ID, they have your commit.  If not, they don't.
In addition to all of this, your Git stores the hash ID of the previous commit—the one that goes before this commit—in the metadata for this commit.  So, given a commit, Git can look at its parent and get the hash ID of the previous commit.  Your Git can then retrieve that commit from its database of commits.  That commit has a snapshot of all of the files as of the time you (or whoever) made that commit, and it, too, has a parent hash ID, which locates yet another earlier commit, and so on.
This means that Git can start with the most recent or last commit, at the end of a long backwards-looking chain, and work back to the very first commit you (or whoever) made.  This very-first commit does not have any parent hash ID, simply because it can't: there was no earlier commit to connect back to.  Except for cases where your string of commits branches or merges—which I won't cover properly here—this means your Git repository structure is really simple:
... <-F <-G <-H

Here, the uppercase letters stand in for the actual hash IDs of each commit.  We draw them as pointing to their parent commits.  Now Git just needs some way to remember the actual hash ID of the last commit, H, and that's where a branch name comes in:
...--F--G--H   <-- master

The branch name master holds the raw hash ID of commit H, so that H is the last commit on master.  To make a new commit, you modify some file, git add it, and run git commit.  The git commit gathers your log message—in this case, from your -m argument—and uses your name and email address and the current date-and-time to set up most of the metadata.  It uses hash ID of the current commit H—which is stored in the name master—as the parent for the new commit.  It freezes all the files into the new commit, which we'll call I.  Let's draw it in:
...--F--G--H   <-- master
            \
             I

Now that commit I exists, and has frozen-for-all-time copies of all of the files—a new snapshot—Git simply changes the hash ID stored in the name master, so that master now points to commit I instead of commit H:
...--F--G--H
            \
             I   <-- master

Like each stored file's contents, the commit's contents can never be changed.3  All commits are permanent (mostly—see footnote 2) and read-only (totally).

1This extra machinery is deliberately exposed, in Git, so it's possible to (ab)use Git to store files directly, e.g., through the use of tags.  But that's not how it's designed to work.
2It's a little bit tricky to remove a commit, but it is possible.  Essentially, you have to make the commit un-find-able first.  This gets into the notion of reachability in a graph, which again we won't go into here, but see Think Like (a) Git for more about this.
3The reason for this is that the hash IDs are cryptographic checksums of the contents.  Make any change, and what you have is a new and different internal object, with a new and different checksum.  The old object is still there in the database.  You didn't change a file, or a commit: you just made a new file, or a new commit.

Quick recap of the above

Every commit has a unique hash ID.
Each commit stores a frozen copy of all files forever (or as long as the commit itself continues to exist).
Each commit has some set of parent hash IDs, usually just the one immediate parent.  (The very first commit has no parent.  A merge commit starts with the usual parent, but then has more; we won't get into the details here.)
Nothing in any commit can ever be changed.
A branch name like master simply identifies the last commit in the chain.  From here, Git can work backwards to earlier commits.
So Git finds commits by starting with a name, like master, and working backwards.
One Git repository can talk to another.  When it does so, it talks about what it has by hash ID.  The hash IDs are the universal exchange method.
You, as a human, will generally use names like master.  But you can run git log or use other tricks to find the hash IDs, which may matter in a moment.

A brief-ish look at the index and work-tree
Commits, and their stored files, are frozen for all time.  That's great for archival, but useless for getting any new work done.  You need to be able to take all the files out of some commit, un-freezing and re-hydrating them.  Git therefore sets up a work area, which Git calls your work-tree or working tree or other variations along this line.  This folder, plus any sub-folders Git needs to create, holds the files extracted from the commit.  The files have full names, e.g., feed/app.py, such that your computer requires making the sub-folder feed.  These folders aren't stored in Git;4 the files just have full names that force Git to create folders to hold them.
In any case, checking out some branch-and-commit, as in git checkout master, tells Git: extract all the files from that commit, into my work-tree, so that I can see them and work with them.  The branch is the argument you gave to git checkout, and the commit is based on the hash ID stored in the branch name.  In our drawings above, that was first commit H, then commit I after we made the new one.
As we saw above, to make a new commit, you can just work with the work-tree file—it's an ordinary file and you can do anything to it that your computer will let you do to it—and then run git add on it.  But why do you have to git add the file every time you change it?
This is where Git's index comes in.  The index or staging area (or sometimes, rarely these days, the cache) holds a copy of each file that git checkout checked out.  This copy is in the freeze-dried format, ready to go into the next commit.5  Initially, that's just the actual copy from the previous commit.  Running git add has Git compress / freeze-dry the updated contents and put those into the index.
What this means is that, at all times, the index holds copies of the files you propose to put into the next snapshot.6  Initially, the index matches the current commit.  You then change work-tree files, but the index still matches the current commit: nothing new is staged for commit yet.  Then you git add the file to replace the index copy with a freeze-dried version of the work-tree copy.  Now something is staged for commit.
In other words, at all times, you have three active copies of each file.  Let's consider the file README.md for a nice concrete example.  Note that the syntax with the colon in it is special to Git, i.e., HEAD:README.md and :README.md won't work with most commands on your computer.  But git show, and some other Git commands, use this commit:path syntax.  (Annoyingly, the colon means something different in git fetch and git push.)

HEAD:README.md is the frozen copy in the current commit.  (Use git show HEAD:README.md to view it.)  You cannot change this one, but it's easy to access.
:README.md is the frozen-format copy in the staging area, i.e., the index.  (Use git show :README.md to view it.)  You can change this one, by replacing it.  Use git add to replace it from the third copy, which is:
README.md is an ordinary file in your work-tree.  Use ordinary commands to view it or change it or whatever.

In fact, all frozen copies in every commit are accessible at all times, but the one (or ones) in the current commit has (have) a special role.  This is in part because HEAD plays a big part in what git status says.
The git status command will tell you that some files are staged for commit and other files are not staged for commit.  To do that, git status runs two separate comparisons.  The first one is HEAD-vs-index.  The second one is index-vs-work-tree:

First, for each file in HEAD, compare it to the one in the index.  Do they match?  If so, say nothing.  If not, say that this file is staged for commit.
Next, for each file in the index, compare it to the one in the work-tree.  Do they match?  If so, say nothing.  If not, say that this file is not staged for commit.

There are some extra cases, e.g., files in your work-tree that aren't in your commit, or files that have been removed from your index and/or work-tree.  But the above is the heart of what git status tells you about the next commit you would make if you ran git commit right now—the staged for commit files—or the commit you could make if you ran more git add commands.
Crucially, your work-tree, and the index that sits between your work-tree and the Git repository, is specific to this particular Git repository.  When you have your Git call up some other Git, they will exchange commits.  Your index and your work-tree are private: they cannot see yours.  By the same token, their index, and their work-tree if they have one,7 are also private.  You cannot see theirs.

4They sort of are, and sort of aren't.  The end result is mostly "aren't" as you cannot store an empty directory in Git.
5Technically, the blob object is actually already in the Git database.  The index just refers to that object by its hash ID.  When you git add an updated file, this will create a new blob object if needed, and the index will now refer to  the new blob object.  If the contents you git add match those of some stored version, anywhere in the repository, Git will re-use the existing blob object.
6The index takes on an expanded role during a conflicted merge.  It also has some other uses.  Saying the index represents your next commit is not wrong, but not really complete—but this answer is already long enough.
7If you use GitHub or Bitbucket or any other similar web hosting service, they have bare repositories that have no work-tree.  In order to git push to some server repository, that server repository is typically also created with --bare.  This sidesteps a bunch of problems that could occur if you want to update a branch that they have checked-out.  Without a work-tree, they cannot check out any branch.

Another quick recap

The special name HEAD refers to both your current branch and your current commit.  (Git has two ways to ask about HEAD; one produces the branch name, the other produces the commit hash ID.)  While the commits themselves cannot be changed, you can select any branch name for HEAD and therefore change which commit is the current commit.  Adding a new commit automatically updates the branch name, so that the new commit you just made is the current commit now.
The index or staging area holds every file that will go into your next commit.
The work-tree is where you can see and work with your files.  Git doesn't really need this at all: Git's main concern is with the repository itself, and then with the index since that's the source of new commits.  But Git has to provide a work-tree, so that you can actually use Git.
The work-tree and index are private to this Git repository.

Reframing your original problem
Note that as humans, we tend to be concerned with our work-tree files.  But Git isn't, not very much anyway.  This all comes back to the key problem with your desire:

... I want to replace the local app.py on my pc with the remote one ...

There isn't a remote one, as far as Git itself is concerned.  Your Git is going to call up another Git.  That other Git has commits.  Your Git either already has all of their commits, or will get any new ones from them if needed.  That's what git fetch does: your Git calls up their Git, asks their Git about their branches and tags and so on, and collects from them any new commits they have that you don't.  Once it has all their commits added to your database, git fetch is done and the two Gits stop talking to each other.
You may well already have all of their commits.  If so, there's no need to git fetch here at all.  That's probably the case above: you started with all of their commits, then you made one new commit and gave them that one via git push.  You still have all of their commits (and they now have all of yours too).
In any case, now that you have all of their commits, you can select any of those commits—which are all in your repository now—and either check out that entire commit, or selectively extract individual files from individual commits.  This is where git checkout gets quite messy.  Git 2.23 adds new commands that you can use instead of git checkout, to help keep this stuff straighter, but we'll just talk about git checkout and git show here.
Using git checkout, you can tell your Git:

Extract one specific file from one specific commit.  Copy this file into the index, then copy it from the index to the work-tree.

Using git show, you can tell your Git:

Find one specific file in one specific commit.  Show this file to the standard output: the terminal window, or wherever I have redirected it.

Note that this git checkout will overwrite your current index copy.  (You can fix or change this later if you want, using, e.g., git reset.)  The git show won't do this.
To achieve the first one, you must pick a commit.  The easiest way is often to use git log to find the hash ID, then cut-and-paste that ID with your mouse:
git checkout <hash-id> -- path/to/file

To achieve the second one, pick a commit again, and run:
git show <hash-id>:path/to/file

There's a bit of weirdness here.  With git checkout, the path to the file is relative to where you are in the work-tree, just as it is with git add.  If you're in the sub-folder feed and the file is named feed/app.py, you just use app.py here.  But with git show, you must use the full name of the file, or write git show hash-id:./app.py.  (Internally, this has to do with the fact that git add and git checkout take arguments that Git calls pathspecs, while git show doesn't.  But in practice it's just Git being messy and a bit hard to use.)
There are a lot of ways to name commits
As shown above, you can name a commit by its hash ID.  You can use git log, perhaps with --all --decorate --online --graph—one of my favorite Git commands—to find lots of hash IDs, which you can then cut and paste.  You can use a branch name like master to mean the commit that the name points to.  For instance, if your graph looks kind of like this (though git log --graph will draw it vertically instead of horizontally):
...--F--G--H   <-- master
         \
          K--L   <-- test

you can use the name test to mean commit L, just as the name master means commit H.  And, when you have a remote like origin and run git fetch, your Git sets up all your remote-tracking names, like origin/master, to remember what your Git got from their Git when your Git called them up and said: Hey, what commits do you have, under what branch names?
So, if you had:
...--F--G--H   <-- master, origin/master

and then you added a new commit I to the end of your master, you now have:
...--F--G--H   <-- origin/master
            \
             I   <-- master

So now instead of finding the actual hash ID for commit H, you can use the name origin/master to identify it.  Hence:
git show origin/master:feed/app.py

will let you see the version that is still in commit H, which is still identified by your origin/master.
Your origin/master will be automatically updated on each git fetch to origin: your Git calls up their Git, asks it what branches they have, and they say "I have master and it's commit big-ugly-hash-ID".  Your Git gets that commit if you don't have it yet—along with all the earlier commits you need too—and now you have it.  Then your Git sets your origin/master to remember that big ugly hash ID.
So, this gets us to the final, and maybe best, way to view or extract that file from their commit: run git fetch if needed, then use git show or git checkout with the name origin/master—assuming you call that other Git origin, as most people do—and the appropriate path name.  For git checkout, the appropriate path name depends where you are in your work-tree.  For git show, the appropriate path name is the full path or starts with ./.  The syntax for git checkout is:
git checkout <commit> -- <path>

and the syntax for git show is:
git show <commit>:<path>

and you just have to remember that they're different like this.
Answer: I think your are looking for
git checkout sec_aggregator/feed app.py

This will checkout app.py from branch feed defined on remote
sec_aggregator
Comment: Hi.  git branch is "* master"
Answer: To replace a file with the previously committed version you can do:
git checkout add.py

or
git reset --hard add.py

Please make sure that you don't have unsaved changes for the add.py in the working directory before running any of them. Those operations are not working-directory safe, so your local changes for that file will be lost.


Finding complex roots for $x^3 - x^2 +x -1$ (hard edition)

Question: Does someone know how i can find the complex roots to the equation: $x^3 - x^2 + x - 1$
I know that I can set it up like $(x-1)(x^2+1)$, and easy see it. But if I find that $x = 1$, is that a method to find the other two roots with math. Think that is possible to do some tricks with the numbers with polar forms, but i dont remember how.
Comment: You just need to solve $x^2=-1$. There are two complex numbers that satisfy this.
Comment: Are you asking how to get to $(x-1)(x^2+1)$ when you know that $x=1$ is a root?
Answer: Alternative approach:
Let $f(x) = (x^3 - x^2 + x - 1).$
$(x^3 - x^2 + x - 1) \times (x + 1) = x^4 - 1.$
Therefore, $\displaystyle (x^3 - x^2 + x - 1) = \frac{x^4 - 1}{x+1}.$
Therefore the $3$ roots of $f(x) = 0$ must coincide with the $4$ roots of $(x^4 - 1 = 0)$, except for the elimination of the root represented by $(x + 1) = 0.$
The roots of $(x^n - 1 = 0)$ are $e^{i2k\pi/n} ~: ~n \in \Bbb{Z^+}, ~k \in \{0,1,\cdots,[n-1]\}.$
Answer: We have
$$x^3-x^2+x-1=(x-1)(x^2+1)=(x-1)(x+i)(x-i)$$
where $ i =\sqrt{-1}$ it the imaginary unit.
Comment: Yes, that's good advice.     For any y (other than y= 0) there are two values of x such the x^2= y. The POSITIVE one is written $\sqrt{y}$ and the other is $-\sqrt{y}$.  The complex numbers are not an "ordered field" so there is no way to distinguish "positive" and "negative" complex numbers.    There is no way to distiguish the roots of $x^2= 1$ as $\sqrt{-1}$ or $-\sqrt{-1}$.
Comment: My school book says we must write this fact as $i^2=-1$ not $i=\sqrt {-1}$.
Comment: Yes, it's the solution to the quadratic equation $x^2+1=0$ as the link says, and it's better to write it that way, but I wrote it in terms of radicals for the OP.
Answer: The equation $ \ z^3 - z^2 + z - 1 \ = \ 0 \ $ manages to stay within reach of a trigonometric calculation, if we take it that all of the roots have the same (unit) modulus.  (Since we can see readily that $ \ z = 1 \ $ is a root, this is at least reasonable to try.)
If we use $ \ z \ = \ e^{i·\theta} \ = \ \cos \theta \ + \ i·\sin \theta \ \ , $ then we are looking for
$$ \ e^{i·3\theta} \ - \ e^{i·2\theta} \ + \ e^{i·\theta} \ - \ 1 $$ $$ = \ \ [ \ \cos(3·\theta) \ - \ \cos(2·\theta) \ + \ \cos\theta \ - \ 1 \ ] \ + \ i·[ \ \sin(3·\theta) \ - \ \sin(2·\theta) \ + \ \sin\theta \  ] \ \ = \ \ 0 \ \ . $$
We will work with the imaginary part first, applying "multiple-angle" identities for sine:
$$ \sin(3·\theta) \ - \ \sin(2·\theta) \ + \ \sin\theta \ \ = \ \ (3·\sin \theta \ - \ 4·\sin^3 \theta) \ - \ (2·\sin \theta·\cos \theta) \ + \ \sin \theta $$
$$ = \ \ \sin \theta \ · \ ( 3 \ - \ 4·\sin^2 \theta \ - \ 2·\cos \theta \ + \ 1 ) \ \ = \ \ \sin \theta \ · \ ( 4 \ - \ 4·[1 - \cos^2 \theta] \ - \ 2·\cos \theta  )  $$
$$ = \ \ \sin \theta \ · \ ( 4· \cos^2 \theta \ - \ 2·\cos \theta  ) \ \ = \ \  2·\sin \theta · \cos \theta \ · \ ( 2· \cos \theta \ - \ 1  ) \ \ = \ \ 0 \ \ . $$
The factors of this last product offer six candidate solutions:  $ \ \sin \theta \ = \ 0 \ \Rightarrow \ \theta \ = \ 0 \ , \ \pi \ \ ; $ $ \ \cos \theta \ = \ 0 \ \Rightarrow \ \theta \ = \ \pm \frac{\pi}{2} \ \ ; $ $ \ 2· \cos \theta \ - \ 1    \  =  \ 0 \ \Rightarrow \ \theta \ = \ \pm \frac{\pi}{3} \ \ . $
We then apply analogous identities for cosine to the real part:
$$ \cos(3·\theta) \ - \ \cos(2·\theta) \ + \ \cos\theta  \ - \ 1 $$ $$ = \ \ (-3·\cos  \theta \ + \ 4·\cos^3 \theta) \ - \ (-1 \ + \ 2·\cos^2 \theta) \ + \ \cos \theta \ - \ 1 $$
$$ = \ \  4·\cos^3 \theta \ - \ 2·\cos^2 \theta \ - \ 3·\cos  \theta \ + \ 1 \ + \ \cos \theta \ - \ 1 $$
$$ = \ \ \cos \theta \ · \ ( 4· \cos^2 \theta \ - \ 2·\cos \theta \ - \ 2 ) \ \ = \ \  2·\cos \theta \ · \ ( 2· \cos \theta \ + \ 1  ) \ · \ ( \cos \theta \ - \ 1  ) \ \ = \ \ 0 \ \ . $$
The factors for the real part yield  $ \ \cos \theta \ = \ 0 \ \Rightarrow \ \theta \ = \ \pm \frac{\pi}{2} \ \ ;  $ $ \ 2· \cos \theta \ + \ 1  \  =  \ 0 \ \Rightarrow \ \theta \ = \ \pm \frac{2·\pi}{3} \ \ $ $ \ \cos \theta \ - \ 1  \  =  \ 0 \ \Rightarrow \ \theta \ = \ 0  \ \ . $
The three values of $ \ \theta \ $ that cause both the real and imaginary parts to equal zero are $ \ 0 \ , \ \pm \frac{\pi}{2} \ \ . $  Hence the three zeroes of the cubic equation are
$$ \ z \ = \ e^{i·0} \ = \ 1 \ \ , \ \  e^{i·\pi/2 } \ = \ i \ \ , \ \  e^{i·(-\pi/2)} \ = \ -i \ \ .  $$
Admittedly, we  got a bit "lucky" with this polynomial in that it has suitable properties (low degree, resemblance to the cyclotomic polynomials) for attempting such a method of solution.  One shouldn't expect this to work well as a general approach, though there are special cases (this famous one, for instance) where it has been used successfully.


Sum over greatest integer

Question: Evaluate ${\lim_{n \to \infty} \frac{1}{n}\sum_{k=1}^{[\frac{n}{2}]} \cos \left(\frac{ kπ}{n}\right)}$
I think it is Riemann sum of some integral like $\int_{0}^{1} \cos (πx) \,dx ,$
but how to approach for the upper limit of summation?
Comment: The answer should be $\frac{1}{\pi}$. You can get an explicit value for the summation through [Wolfram Alpha](https://www.wolframalpha.com/input/?i=sum+1%2Fn+cos%28kpi%2Fn%29+from+k%3D1+to+k%3DRound%28n%2F2%29) and taking the limit (or plotting the graph on [Desmos](https://www.desmos.com/calculator/lpwblklwly)) gives the answer above.
Answer: This limit can be changed to an Integral$$L=\lim_{n \rightarrow \infty} \sum_{k=1}^{[n/2]}  \cos \left(\frac{k \pi}{n}\right)= \int_{0}^{1/2} cos (\pi x) dx=
\frac{1}{\pi}. $$
Comment: Won't greatest integer make any change here?
Comment: When $n \rightarrow \infty$, it the integer and integer-part do not make adifference.

Sum over greatest integer


how to measure the correlation between non-normally distributed numeric variable and nominal variable?

Question: I have two nominal variables and some numeric variables.

The first nominal variable is a binary one. I want to measure the correlation between this binary variable and the other numeric variables.
The second nominal variable has 37 categories. Again, I should measure the correlation between this nominal variable and the other numeric variables.

Based on this, I am not allowed to use one-way Anova because my data is not normally distributed. According to the answer to this post, Eta is associated with one-way Anova, so due to the non-normality of my data, it is not possible to use Eta. Therefore, I decided to use Kruskal-Wallis for my second nominal variable with 37 categories based on this post.Should I use Mann–Whitney U-test for my first binary nominal variable? Is it true to do so?
It should be noted that my data set includes 2200 observations. Besides, I want to do it as a Exploratory Data Analysis step.
Comment: Your title contradicts to your two points. You actually are asking about binary - nominal and nominal - nominal associations. I don't see any "numeric"/continuous variable in the points asked.
Comment: You use the words "non-normal" but I think you mean "nominal". i.e., non-normal is a term usually reserved for variables that are numeric but that do not follow a normal distribution.
Comment: @JeromyAnglim Thanks. My data is not normally distributed, so I used the term non-normal. Besides, I need to measure the association between nominal and continuous variables, which are non-normal.
Comment: @JeromyAnglim Thanks a lot. Sorry, I need to measure the association between a nominal and some continuous variables. I already used Cramer's V to measure the association between two nominal variables.
Comment: @JeromyAnglim As a matter of fact, I already used `one-way Anova` but as I understood that my data is not normally distributed, I doubt it would be right to use `one-way Anova`. However, I am not sure about using `kruskal-Wallis` and `Mann-Whitney U-test`.
Comment: @JeromyAnglim Sorry, Eta is not affected by the fact that my data is not normally distributed? According to the provided link: "The most classic "correlation" measure between a nominal and an interval ("numeric") variable is Eta, also called correlation ratio, and equal to the root R-square of the one-way ANOVA (with p-value = that of the ANOVA)." Therefore, if one-way Anova is not suitable for non-normal data, maybe this would be true about Eta.
Comment: Eta does not request normally distributed groups to measure the strength of association; it however needs more or less symmetric distribution; It needs normality for p-value, though.
Comment: @ttnphns Thanks a lot. Sorry, I modified my post. Could you please let me know what test should be used if we want to rely on p-value?
Comment: I agree with @ttnphns, I think you still need to edit your post title to make it match your body.
Comment: @Silverfish Thanks a lot. I revised my title again. I would greatly appreciate if you could answer it.
Comment: I don't think I'd have anything to add to @JeromyAnglim's answer unfortunately
Answer: Nominal with nominal:
There are a few measures of association designed for two or more nominal variables (i.e., 3 or more unordered categories for one variable; and two or more unordered categories for the other variable).
Here are two that come to mind.

Goodman &  Kruskal's lambda: https://en.wikipedia.org/wiki/Goodman_and_Kruskal%27s_lambda
Cramér's V: https://en.wikipedia.org/wiki/Cram%C3%A9r%27s_V

Nominal with numeric:
I agree that eta-squared or ICC are two common approaches to quantifying the association between a nominal and numeric variable.
Comment: (+1) Aside on notation: As I recall, Cramér originally used the symbol $\nu$ (lower case Greek letter  nu). The widespread but not universal present convention to use roman letters for sample statistics would lead to transliterating this as $n$, not a good idea. I suppose $V$ may be customary for the good reason of using a roman letter and/or as a misreading of $\nu$. There lies a very small historical question which may be of interest to some.
Comment: Just an addition: Cramer's V is exactly related to the averaged canonical correlations squared (https://stats.stackexchange.com/a/140057/3277) which puts Cramer V into the context of linear model (performed on the dummy sets).
Comment: @JeromyAnglim  Thanks a lot. I upvote your answer but still I am not sure about the p-value of Eta.


Can you use the Any Signer feature in a (REST API) embedded process?

Question: I'd like to use the Any Signer functionality, but our signing application uses embedded signing only.  Can you use Any Signers in an embedded process?
The problem I run up against is that I can only get Any Signer working for non-embedded signers.  That is, it only works for signers with no clientUserID.  But with no clientUserID, I can't use embedded signing.
Has anyone got embedded Any Signers working or have a workaround?
Some further details:

Our process is automated and embedded-only so that we can use our own email content and provide the option of signing via email or in-application frame to our end users.
I've been able to get the Any Signer option working according to the DocuSign Quick Start Guide:
https://www.docusign.com/sites/default/files/Quick%20Start%20-%20Using%20the%20Any%20Signer%20Option.pdf
The problem is that this works only for non-embedded users.
I'm able to create an envelope via the REST API, with Any Signer as follows:
<code>POST https://demo.docusign.net/restapi/v2/accounts/<account>/envelopes

{
    "emailBlurb" : "Test Email Blurb",
    "emailSubject" : "Test Email Subject",
    "status" : "sent",
    "documents" : [{
            "documentId" : "1",
            "name" : "TestDoc.pdf",
        }
    ],
    "recipients" : {
        "signers" : [{
                "recipientId" : 1,
                "email" : "firstname.lastname@example.com",
                "name" : "Any Signer",
                "tabs" : {
                    "signHereTabs" : [{
                            "documentId" : "1",
                            "recipientId" : 1,
                            "name" : "SignHere_3",
                            "pageNumber" : 1,
                            "xPosition" : 81,
                            "yPosition" : 447,
                            "tabName" : "SignHere_3"
                        }
                    ],
                },
                "routingOrder" : 1,
            }
        ]
    }
}
</code>
I've tried switching recipients as an alternative to Any Signer, with no luck.  Please see this (unanswered) question:
Switch signers on an In Process shared document
Comment: No, that is not possible. You must have a clientUserId.
Comment: Thanks Andrew.  I thought that might be the case.  Gah!  Another dead-end.
Comment: Why do you want any signer? Do you have a requirement that the signer has access to the envelope in a specific account? Or is there other requirements?
Comment: I want to delay the choice of which specific employee signs.    I'm currently forced to specify all signers at the time of envelope creation.  This causes problems because the employee is normally the last to sign and the initial employee may not be available after the other signers have signed.  Any Signer would solve this problem, because another employee could sign instead.
Comment: Most people create a "blank" recipient that just sits there waiting to be removed so the last person can be added when needed. Add the final recipient, delete the "blank" one.
Comment: I tried that, but whenever I add the final recipient, DocuSign won't include the tabs.  The final recipient is stuck in a draft-like 'created' state.  Nothing I do moves the signer to the necessary 'sent' state.  The details are in the related question I listed in further details 4.
Comment: Posted an answer over there.
Comment: possible duplicate of [Switch signers on an In Process shared document](http://stackoverflow.com/questions/24916310/switch-signers-on-an-in-process-shared-document)
Answer: The "any signer" feature is similar to a Distribution Group in your mail. It sends the email to all these people and any one of them can sign. When you use embedded signing, you have to specific who is the signer before you can generate the URL for the embedded signing session. This means you cannot use a signing group, but you have to have a specific signer (email and name) that would be used in that session.


document.getElementsByTagName('select') - select only from particular form

Question: I'm trying to select drop-downs and check them, so I'm using this code to do so -  document.getElementsByTagName('select'); but the problem I'm facing is that I've got several forms on one page and I want to choose only drop-downs from form called myform3 for example!
I found one example it looks like this - myform3.document.getElementsByTagName('select'); but it only works in IE
Could you tell me how to do that in every browser?
Answer: Try:
document.forms['myform3'].getElementsByTagName('select')

Answer: It should be
document.myForm3.getElementsByTagName('select');

Not
myForm3.document.getElementsByTagName('select');

Works in other browsers too.
Answer: It's working fine..
   document.forms["form_name"].getElementsByTagName("select");

Answer:
I found one example it looks like this - myform3.document.getElementsByTagName('select'); but it only works in IE

myform3.getElementsByTagName would be correct – documentis out of place there.
(You can call getElementsByTagName on every node object to only get nodes that are descendants of it.)
Answer: Try this way :
document.forms["myform3"].getElementsByTagName("select");

Answer: Set the ID attribute of the form to myform3. Then you can do this:
var myForm = document.getElementById("myform3");
var selects = myForm.getElementsByTagName("select");


Exchange 2010 OWA not working

Question: So here's an interesting problem that just started happening today.  OWA is no longer working on the internal network or Externally.  I now get an error in IE saying:
"Turn on TLS 1.0, TLS 1.1, and TLS 1.2 in Advanced settings and try connecting to https://server  again. If this error persists, it is possible that this site uses an unsupported protocol or cipher suite such as RC4 (link for the details), which is not considered secure. Please contact your site administrator. "
Yet in IE, TLS is enabled and SSL 2 & 3 have been disabled.  I used IISCrypto on my Exchange 2010 server and it shows I am running with best practices.
I've also tried rebuilding my OWA Virtual Directory with no success.
I don't see any obvious errors in Event Viewer.
What could I be missing?
Another note, email is being forwarded to my exchange box from my mailmarshall server but external email is not showing in mailboxes.  Only internal emails are.
Comment: Use something like
http://www.bolet.org/TestSSLServer/
to double check whether the expected SSL/TLS versions are being used by the server. Are they as expected?
Comment: I'm voting to close this question because it's obsolete and totally not relevant anymore... but it just got bumped to the front page.
Answer: Exchange rarely does anything on its own - so if it has only happened today - what has changed? Something will be logged.
Is this a single server of multiple? How did you rebuild the virtual directory? Can you browse to the root of the site? If not, then the issue is probably with IIS rather than Exchange. Check the correct bindings are in place on the default web site.
Comment: I've found errors in Symantec Mail Security.  As soon as I started an uninstall of that, outside emails came in.  Still no OWA access yet though.

Other than that, nothing has changed config wise on the server.

Exchange 2010 OWA not working


Two definitions of topological mixing

Question: I have seen two definitions of topological mixing, and wanted to check that they are equivalent:
1) We call a continuous map $f:X \rightarrow X$ mixing if for every pair of non-empty open sets, $U,V \subset X$, there is some $n_0 \in \mathbb{N}$ such that for all $n> n_0$, $f^{-n}(U) \cap V \neq \emptyset$.
2) We call a continuous map $f:X \rightarrow X$ mixing if for every pair of non-empty open sets, $U,V \subset X$, there is some $n_1 \in \mathbb{N}$ such that for all $n> n_1$, $f^{n}(U) \cap V \neq \emptyset$.
Writing out the sets, it looks like we just interchange the roles of $U$ and $V$, so the definitions should be equivalent, but I wanted to check I wasn't being silly.
Answer: Correct: if $x\in f^{-n}(U)\cap V$ then $f^n(x) \in U\cap f^n(V) $.
For the other direction, if $y\in U\cap f^n(V) $ then there is an $x\in V$ such that $y=f^n(x) $ so $x\in f^{- n}(U) \cap V$.

Two definitions of topological mixing


Seeking a correct relationship between the number of zeros of an entire function and it's derivative.

Question: As far as polynomials are concerned, we know by virtue of fundamental theorem of algebra that a polynomial of degree $n$ has exactly $n$ roots in $\mathbb{C}$ and its derivative then will have $n-1$ roots.  Thus we can say that the number of roots of a polynomial of degree $n$ is greater than the number of roots of its derivative.
However, my concern is that can I get similar conclusion  for transcendental entire functions ?
Note that for the entire function $e^z$ has no zeros in $\mathbb{C}$.
Comment: Little remark : "it's" isn't the same as "its"
Answer: That conclusion does not hold for transcendental entire functions. As an example, if $h$ is an entire function then $f(z) = e^{h(z)}$ has no zeros, but $f'(z) = h'(z)e^{h(z)}$ can have finitely many (take $h$ as a polynomial) or infinitely many  (e.g. $h(z) = \sin(z)$) zeros.
There is also no general estimate in the other direction: $g(z) = 1 + e^z$ has infinitely many zeros, but $g'(z) = e^z$ has none.
Comment: @Nik: No. $g(z) = 1+(z-1)e^z$ has infinitely many zeros, but $g'(z) = ze^z$ only one.
Comment: @Nik: That's what the examples demonstrate. – There are some results in special cases. E.g. if $f$ is an entire function of finite non-integral order then both $f$ and $f'$ have infinitely many zeros, and $N(r, 0, f)$ and $N(r, 0, f')$ have the same order of growth. But that goes beyond the scope of this question.
Comment: @Nik: Does this answer your question now? Let me know if something is still unclear.
Comment: From this counter example, can I conclude that the number of zeros ( if they exist ) of derivative of a transcendental enitre function is greater than or equal to that of itself ?
Comment: Then am I right to say that no relation can be drawn between number of zeros of a transcendental entire function and its derivative ?
Comment: Yes sir, it's clear now. Also, you have mentioned that if order of $f$ is finite non-integral, then $N(r, 0, f)$ and $N(r, 0, f')$ have same order of growth. Since I am a beginner in Nevanlinna theory, I would like to see how and why this phenomenon happen, although it is beyond the scope of this question.


Cannot fetch partial content from URL

Question: This is the URL: http://mirrors.standaloneinstaller.com/video-sample/Panasonic_HDC_TM_700_P_50i.m4v
the response from this URL has the Accept-Ranges header set to bytes but when i try to fetch a subset(bytes=1-2) of the response, it sends me the whole video with status code 200
Here is the python code i used
import requests

url = 'http://mirrors.standaloneinstaller.com/video-sample/Panasonic_HDC_TM_700_P_50i.m4v'

headers = {'Range': 'bytes=1-2'}
response = requests.get(url, headers=headers)
print(len(response.content))
print(response.headers)
print(response.status_code)

Answer: It seems that requests in default operating mode (e.g. using only .get()) sends some additional HTTP headers - and the server then responds with whole content.
So to send only this specific header Range, see following example:
import requests

url = (
    "http://mirrors.standaloneinstaller.com/video-sample/Panasonic_HDC_TM_700_P_50i.m4v"
)

headers = {
    "Range": "bytes=1-2",
}

with requests.session() as s:
    req = requests.Request("GET", url, headers=headers)
    prepped = req.prepare()
    resp = s.send(prepped)

    print(len(resp.content))
    print(resp.headers)
    print(resp.status_code)

Prints:
2

{
    "Date": "Mon, 14 Aug 2023 18:18:18 GMT",
    "Server": "Apache",
    "Upgrade": "h2",
    "Connection": "Upgrade, close",
    "Last-Modified": "Thu, 23 Mar 2017 21:44:11 GMT",
    "ETag": '"193100d-54b6cc707b215"',
    "Accept-Ranges": "bytes",
    "Content-Length": "2",
    "Vary": "Accept-Encoding",
    "Content-Range": "bytes 1-2/26415117",
    "Content-Type": "video/x-m4v",
}

206

Cannot fetch partial content from URL


How should I determine what imputation method to use?

Question: I am attempting to learn various methods of imputation to deal with missing values in a dataset. I have a dataset storing marathon segment splits (5K, 10K, ...) in seconds and identifiers (age, gender, country) as columns and individuals as rows. Each cell for a marathon segment split column may contain either a float (specifying the number of seconds required to reach the segment) or "NaN". I am attempting to predict marathon performances based on the first few splits. Below is some sample data:
      Age M/F Country      5K     10K     15K     20K    Half  Official Time
2323   38   M     CHI  1300.0  2568.0  3834.0  5107.0  5383.0        10727.0
2324   23   M     USA  1286.0  2503.0  3729.0  4937.0  5194.0        10727.0
2325   36   M     USA  1268.0  2519.0  3775.0  5036.0  5310.0        10727.0
2326   37   M     POL  1234.0  2484.0  3723.0  4972.0  5244.0        10727.0
2327   32   M     DEN     NaN  2520.0  3782.0  5046.0  5319.0        10728.0

What imputation method should I use here and, more generally, how should I determine what imputation method to use for a given data set?
I've referenced this answer but I'm not sure what to do from it.
Answer: You have to think about why the data might be missing.  There are generally 3 types of missing data:
Missing completely at random (MCAR):  This sort of missingness happens when someone drops a test tube in a lab or something.  "The data are missing for reasons that are unrelated to any characteristics or responses for the subject, including the value of the missing value, were it to be known" writes Frank Harrell in chapter 3 of his book *Regression Modelling Strategies".  Your missing data might be MCAR if there is a malfunction in the instruments recording the splits.
Missing at random (MAR):  This sort of missingness occurs when the probability he data are missing has something to do with variables which were actually measured. In your example, perhaps Danish runners were given faulty instrumentation.
Informative Missing:  Again, from Frank Harrell: "The tendency for a variable to be missing is a function of data that are not available, including the case when data tend to be missing if their true values are systematically higher or lower".  So if your Danish runner ran a 5K split which was just too fast or too slow, and the instrumentation for some reason was sensitive to that, then the missingness would be informative missing.
If the missingness is MCAR or MAR then multiple imputation are helpful.  You can use something like MICE or predictive mean matching (side note: Frank implements this in his companion R package rms) to use the information that is available -- including the outcome -- to impute the missing values.  If the data are informative missing, then we risk biasing any estimates we make.
Often, you will see people impute the missing data with the column mean.  That is an attractive approach because it is simple, and it is something you can do if you need to do something.  But, there are many problems associated with this approach.  I would encourage you to read chapter 3.4 of Frank's book to learn more about the downside to imputing with the column mean.
EDIT:
Without knowing more about how data are collected, there isn't really much you can do.  You can assume the data are MAR and just do predictive mean matching, but you're risking bias.  Maybe that is important, maybe not.
Another approach might be to build a model. I suspected that times to run certain distances are, mostly, linear.  Here is a plot I made using some of the data you linked me to.
[![enter image description here][1]][1]
Because the data are linear, we can probably fit a mixed effects model, adjusting for things like age, sex, and adding a random slope for each person (additionally, I know country of origin might be an important predictor). We can then use the model to predict for the missing times.
Here is some R code to get you started in that direction.

library(tidyverse)
library(lubridate)
library(lme4)

# Read in the data from...wherever
d = read_csv("~/Desktop/marathon_results_2015.csv") %>%
    select(-X1)

# Clean up the data so that we have 5 columns:
# bib (serves as ID), age, sex, distance, and time (time is the outcome here)
# Scale distance and age to have mean 0 and standard deviation 1 so model can converge
# Also, convert the time into seconds
raw_data = d %>%
  select(Bib, Age, sex=`M/F`, `5K`:`40K`) %>%
  janitor::clean_names() %>%
  mutate_at(vars(matches('k')), ~period_to_seconds(hms(.x))) %>%
  gather(distance,time, -bib, -sex, -age) %>%
  mutate(distance = as.numeric(str_extract(distance, "(\\d)+"))) %>%
  mutate(distance = distance/max(distance, na.rm=T), age = age/10)

missingness = raw_data %>% filter(if_any(everything(), is.na))

model_data = raw_data %>%
             anti_join(missingness, by = c('bib','distance'))

# Run a mixed effects model.
# Remove the intercept because we know that at time=0 distance=0
model = lmer(time ~  distance:age + distance:sex +(distance-1|bib)-1, data = model_data)

preds = predict(model, newdata = model_data, allow.new.levels = T)
# Save predictions to compare with training data.
model_data$preds = preds

# Now predict the missing data
predict(model, newdata=missingness, allow.new.levels=T)

I've been a bit sloppy with my data cleaning so you might want to do a better job in that respect, but this should be a good start.
[1]: https://i.stack.imgur.com/mjzdp.png
Comment: Thank you for your response! I got my data through Kaggle, which in turn was scraped through an official marathon website. Is there any way of determining if the missing data is MCAR, MAR, or Informative Missing? I'm also not sure if the data can be Informative Missing because the Danish runner was not the fastest nor the slowest of the dataset, yet values faster and slower have been recorded by presumably the same instrumentation.
Comment: As a follow-up question, is missing data that is not MAR nor Informative Missing necessarily MCAR?
Comment: @StackOverflow Short answer is you can't know without knowledge of the data generating mechanism.  As to your follow up, the answer is "possibly" but you can't tell if data is MAR, MCAR or IM just by looking at it.  Can you link me to the data just out of cnuriosity?
Comment: Thank you so much! Here is the data: https://www.kaggle.com/rojour/boston-results?select=marathon_results_2015.csv


C: How to update file with new information in inserted into a structure

Question: I have a program below that acts like a library manager to help organize my books collection but somehow when I update the file with new information when I exist the program, the information in the file is is deleted and nothing is saved into the file.
What this program does is add new books into a structure and then when the user types in 8 to exit the program the information from the structure is saved into file and when the program is run the next time, the information from the file is initialized back into the structure. Somehow my implementations is not working right or somewhere I am doing wrong that needs another pair of eyes to see.
#define MAX 100
#define OUT 1
#define IN  0
#define RETURNTIME 30

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

struct date
{
    int nYear, nMonth, nDay;
};

struct BOOK {
    int     nID;
    char    chTitle[50];
    char    chType[50];
    char    chPublisher[50];
    int     nPages;
    float   nPrice;
    int     nPubYear;
    int     nStatus; //0=available, 1=checked-out
    char    userName;
    struct  date issued, due;
}BOOK[100];

FILE *fp;
FILE *fpin;

//Function calls
void addBookFunction();
void checkOutBookFunction();
void checkInBookFunction();
void displayAllBookFunction();
void displayAllAvailableBookFunction();
void displayAllCheckedOutBookFunction();

int checkID(int t);

int count;

int main(int argc, const char * argv[])
{
    int nInput;
    char buffer[100];
    char *token;

    fpin = fopen("books.txt", "r");
    if (fpin == NULL)
    {
        printf("Unable to open the file");
        exit(0);
    }
    while (!feof(fpin))
    {
        fgets(buffer, sizeof(buffer), fpin);
        int i = 1;
        token = strtok(buffer, ",-");
        while (token != NULL)
        {
            if (i == 1)
            {
                BOOK->nID = atoi(token);
            }
            if (i == 2)
            {
                strcpy(BOOK->chTitle, token);
            }
            if (i == 3)
            {
                strcpy(BOOK->chType, token);
            }
            if (i == 4)
            {
                strcpy(BOOK->chPublisher, token);
            }
            if (i == 5)
            {
                BOOK->nPages = atoi(token);
            }
            if (i == 6)
            {
                BOOK->nPages = atoi(token);
            }
            if (i == 7)
            {
                BOOK->nPubYear = atoi(token);
            }
            if (i == 8)
            {
                BOOK->nStatus = atoi(token);
            }
            if (i == 9)
            {
                BOOK->due.nYear = atoi(token);
            }
            if (i == 10)
            {
                BOOK->due.nDay = atoi(token);
            }
            if (i == 11)
            {
                BOOK->due.nMonth = atoi(token);
            }
            token = strtok(NULL, ",-");
            i++;
        }
    }

    while (1)
    {
        printf("\n\t\t~~MENU~~\n");
        printf("1. Add a new book\n");
        printf("2. Remove a book (input ISBN)\n");
        printf("3. Check out a book (input ISBN)\n");
        printf("4. Check in a book (input ISBN)\n");
        printf("5. Display all book details\n");
        printf("6. Display all available book details\n");
        printf("7. Display all checked out books\n");
        printf("8. Exit program\n");
        printf("Make your selection: ");
        scanf("%d", &nInput);

        switch (nInput)
        {
            case 1:
                addBookFunction();
                getchar();
                break;
            case 2:
                break;
            case 3:
                checkOutBookFunction();
                break;
            case 4:
                checkInBookFunction();
                break;
            case 5:
                break;
            case 6:
                //Display_all_Available_Book_Details();
                break;
            case 7:
                displayAllCheckedOutBookFunction();
                break;
            case 8:
                printf("\nGoodby!!! Thanks for using The Libray Manager\n");
                fp = fopen("books.txt", "ab+");
                fseek(fp, 0, SEEK_END);
                for (int j = 0; j<count; j++)
                {
                    fprintf(fp, "%d, %s, %s, %s, %d, %0.2f, %d, %d, %d-%d-%d\n", BOOK[j].nID, BOOK[j].chTitle, BOOK[j].chType, BOOK[j].chPublisher, BOOK[j].nPages, BOOK[j].nPrice, BOOK[j].nPubYear, BOOK[j].nStatus, BOOK[j].due.nYear,BOOK[j].due.nDay,BOOK[j].due.nMonth);
                }
                fclose(fp);
                exit(1);
                break;
            default:
                printf("\n\t\t~~Invalid Input~~\n");
                break;
        }
    }
    return 0;
}

void addBookFunction()
{
    int bookId;
    if (count == 9)
    {
        printf("\n no more spaces\n");
        return;
    }
    printf("\n Enter Book Details\n");
    printf("Enter book ISBN: ");
    scanf("%d", &bookId);
    if (BOOK[count].nID == bookId)
    {
        printf("\nSorry another book with that id: Try again!\n");
        addBookFunction();
    }
    else
    {
        BOOK[count].nID = bookId;
        printf("Enter book title: ");
        scanf("%s", BOOK[count].chTitle);
        printf("Enter book type (eg. magazine, novel): ");
        scanf("%s", BOOK[count].chType);
        printf("Enter book publisher (eg. UTA): ");
        scanf("%s", BOOK[count].chPublisher);
        printf("Enter book's number of pages: ");
        scanf("%d", &BOOK[count].nPages);
        printf("Enter book's price: ");
        scanf("%f", &BOOK[count].nPrice);
        printf("Enter year published: ");
        scanf("%d", &BOOK[count].nPubYear);
        BOOK[count].nStatus = IN;
        count++;
    }
}

void checkOutBookFunction()
{
    int nInput, i = 0;
    char buffer[5];

    printf("Enter the ISBN: ");
    scanf("%d", &nInput);
    if (checkID(nInput) == 0)
    {
        time_t now;

        if ( time(&now) != (time_t)(-1) )
        {
            struct tm *d = localtime(&now);
            if ( strftime(buffer, sizeof(buffer), "%Y", d) )
            {
                BOOK->issued.nYear = atoi(buffer);
                BOOK->issued.nMonth = d->tm_mon;
                BOOK->issued.nDay = d->tm_mday;
            }
        }
        BOOK->due.nDay = BOOK[i].issued.nDay+RETURNTIME;
        BOOK->due.nMonth = BOOK[i].issued.nMonth;
        BOOK->due.nYear = BOOK[i].issued.nYear;

        if (BOOK->due.nDay > 30)
        {
            BOOK->due.nMonth += BOOK->due.nDay/30;
            BOOK->due.nDay -= 30;
        }
        if (BOOK->due.nMonth > 12)
        {
            BOOK->due.nYear += BOOK->due.nMonth/12;
            BOOK->due.nMonth -=12;
        }

        printf("Issued date = %d-%d-%d\n", BOOK->issued.nYear,BOOK->issued.nMonth, BOOK->issued.nMonth);
        printf("Return date = %d-%d-%d", BOOK->due.nYear, BOOK->due.nMonth, BOOK->due.nDay);

        BOOK[i].nStatus += OUT;
    }
    else{
        printf("No book with that id");
    }
}

void checkInBookFunction()
{
    int nInput, i;
    printf("Enter the ISBN: ");
    scanf("%d", &nInput);
    if (checkID(nInput) == 0)
    {
        printf("Book Found");
        BOOK[i].nStatus = IN;
    }
}

void displayAllBookFunction()
{
}

void displayAllAvailableBookFunction()
{
}

void displayAllCheckedOutBookFunction()
{

    if (BOOK->nStatus == OUT)
    {
        printf("%d, %s", BOOK->nID, BOOK->chTitle);
    }else{
        printf("\n\t\t~~NO BOOKS HAS BEEN CHECKED OUT~~\n");
    }
}

int checkID(int t)
{
    int i;
    while (i < MAX)
        if (BOOK[i].nID == t)
            return 0;
    return 1;
}

Comment: There are a lot of error in your code, please compile it with `-Wall` `-Wextra` and `-Werror`, if you are using gcc. For example, `i` in the `checkID()` is uninitialized, and `fpin` is not closed with `fclose()`.
Comment: Note that all capitals is normally reserved for macros and enumeration constants.  It is unusual (not technically wrong, just unusual) to see `struct BOOK { … } BOOK[100];`.  It would be better to use `struct Book { … } book[100];` or thereabouts.  (Yes, the standard C `FILE` structure is an exception to the all caps rule.  There are historical reasons for the deviance.)
Answer: To reiterate what @SSC has already indicated, you need to initialize variables in C to remove undefined behavior. Using the code you wrote I found two cases where variables were not initialized -
void checkInBookFunction()
{
    int nInput = 0, i = 0; // Changed both variables to initialize to zero.
    // Rest of function code.
}

AND
int checkID(int t)
{
    int i = 0; // Changed this variable as well to initialize to zero.
    // Rest of function code here
}

I was able to write to the file using your code as it is although you might want to look over how to handle string inputs.
You are reading several strings into your structure, although C has the capacity to read strings you are using scanf which is not always the best for these situations. Please refer to C - scanf() vs gets() vs fgets() for more information on how to handle user input.
Answer: In addition to uninitialised variables as pointed above, few observations:

No check to restrict user input string lengths that can be accommodated within the structure without memory overrun. E.g., chTitle, user can enter string longer than 50 bytes allocated for it.
The file, books.txt can contain lines longer than 100 bytes (depending on the data entered by the user). But the buffer used to read each line is 100 bytes, and not checking if you have read complete line. In such case, further token parsing will have unexpected results.


Matrix multiplication from the data frame in R

Question: I'm studying matrix multiplication in R. I want to do matrix multiplication from the data frame.
Let's say I have df and beta as follows:
df <- data.frame(one = c(1,1,1,1,1),
                 x1=c(21,34,24,35,42),
                 x2=c(32,24,13,21,35))
beta<-c(1,2,2)

df is a 5 by 3 matrix and beta is 3 by 1 matrix. I want to multiply beta to df to get a 5 by 1 column matrix. Usually, using the standard multiplication, the code should be
df%*%beta

I want to do this multiplication and also give it a column name df_beta.
But since there are variable names on each column, this matrix multiplication doesn't work. How to do this?
Answer: "%*%" has no "data.frame" method. This is reasonable because there is no guarantee that all columns in a data frame are numeric.
To get a result, you need as.matrix(df) %*% beta. But you take full responsibility to ensure the type conversion gives correct result (watch out for potential character matrix, for which I had a discussion here: Matrix multiplication in R: requires numeric/complex matrix/vector arguments).
Once it executes correctly, to store the result in a new column, use
df$df_beta <- c(as.matrix(df) %*% beta)


How to modify ds_bootstrap_layouts templates to add more layouts?

Question: I'm using the Display Suite Bootstrap Layouts module in Drupal 7, and I want to create additional layouts.
For example, I want the 4-4-4 stacked turned into a double 4-4-4 stacked. I know how to access the files and modify them, but it causes errors and it doesn't show up in the backend.

How do I add more layouts?
Answer:
Implement the following hook

function MODULENAME_ctools_plugin_directory($module, $plugin) {
  return 'plugins/' . $plugin;
}

You can change the name of the 'plugins' directory, but cannot change the following.

Next you create a folder inside the 'plugins' directory and call it 'layouts' <--don't change. Then place your custom layouts in that directory.
Your .inc file will look something like this

$plugin = array(
    'title' => t('LAYOUT TITLE'),
    'icon' => 'ICON.png',
    'css' => 'CSS_FILE.css',
    'theme' => 'NAME OF TEMPLATE FILE W/O .tpl.php'
    'panels' => array(
      'top' => t('Top'),
      'top_left' => t('Top Left Column'),
      'top_right' => t('Top Right Column'),
      'middle' => t('Middle'),
      'bottom' => t('Bottom')
  ),
);

Panels will automatically scan your layouts folder for new layouts. DONT FORGET TO CLEAR THE CACHE. Your new layout will appear in the 'Miscellaneous' section when selecting a layout for your panel.


Problem with images not displaying because domain is incorrect

Question: I have recently installed a Drupal site on our web server and this is the default host (replaced an old website with static files). This server also hosts another virtual host for another domain name and that installation is WordPress.
On blog posts on the Drupal site (regular pages are fine), images will eventually show broken icons and when you check the URL of the image, it's replacing the domain name for the Drupal site with the domain name for the WordPress site.
Clearing the cache within Drupal immediately fixes everything, and the images reappear and with the correct URL.
An additional oddity is that the images are broken inside our network, but from the outside they will show up even though using the incorrect URL. On the inside, it resolves to the internal IP address and on the outside to the public.
I'm using Apache 2.2.22 with Drupal 7.28.
I realize it could be an Apache issue or DNS issue, but I'm checking all avenues... is there a configuration for the Drupal cache that I should be taking a look at that could be causing this problem?
Comment: I assume you have cleared your Drupal cache? I need some more details on your Drupal ENV to help you, if it multi-language? Do you have a hardcoded Drupal path in your settings.php? And other commonly asked questions.
Comment: Yes... clearing the cache fixes the problem. The images will appear again and have the correct URL. After a few hours to a few days, it crops up again.

We are not using multi-language, just English.

No hardcoded path in the settings.
Comment: The quick and dirty fix might be the CDN module. Use it to point to the correct domain for images. Fixing the root cause would be ideal
Answer: The first thing you need to do is stare at your Apache access logs for a while and see if you have inbound requests to the wrong URL.  You may need to configure per virtual host logfiles to see which vhost is handling which.
You may also want to disable Drupal caching (both page and block) to see if the problem persists.
My guess is that everything with your Drupal configuration is correct, but that you have inbound requests that Drupal is handling because it is the default site, and these are getting cached.
If the Apache logs indicate that Drupal is getting the wrong URL, then I would do the following:

Configure both virtual hosts to respond to the canonical URL, and the redirections.  Something like
ServerName www.example.com
ServerAlias example.com *.example.com

This will make sure the proper vhost is responding to the proper domain (which is guess is the root cause of your problem, ie you need a ServerAlias).

Configure httpd.conf or .htaccess to set up canonical URL redirection for both the Wordpress and Drupal sites.  Something like
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com$1 [L,R=301]

These help ensure that Drupal and Wordpress only ever see requests for a single hostname.
These two things make good sense on most live sites, too.
If you still have the wrong URLs and you are 100% positive about the traffic, then my next guess would be that you have a misconfigured settings.php somewhere in your organization, and you have two sites / servers running out of the same database (eg, DEV and LIVE are actually using the same database).  To fix this, you would need to find the offending site.
Comment: Thanks for the suggestion. The problem hasn't resurfaced yet, so I haven't checked the log files (it sometimes takes a few days before it will show itself) but I indeed did NOT have the ServerName and ServerAlias configured on the default virtual host, so perhaps that is the problem. It was configured on the WordPress site, though. We'll see if this fixes the problem.
Comment: @paulmanac You will likely need to combine that with the canonical URL rewrites to be effective.
Comment: Thanks, I'll do that as well. Didn't want to mess with it over the holiday weekend (and it's been fine since last week) but I'll do as you suggest with that and report back.
Comment: Haven't had the problem creep back up in over a week, so I'm thinking this has fixed it.


How to convert recorded Piano music to midi?

Question: I have recorded the output of an in-built track on my keyboard. It has a few instruments playing in the background, but I am interested in just the piano. How should I convert the recorded .mp3 file to a .midi file?
I have tried using Intelliscore for doing so, but I have not been able to adjust the thresholds and other settings to get anything meaningful out of it. Are there any other methods?
Comment: This is somewhat akin to handwriting recognition - i.e. a very hard problem to solve. It'd be much easier to use a keyboard that can record the keys you play directly into MIDI format.
Comment: I assume you're limiting the answers to software solutions. You could always sit down and try to transcribe the music by ear. When you first start out, it is very time-consuming, but it gets faster and easier over time.
Answer: audio to midi apps never work well beyond a melody on a single instrument.  Add instruments or chords and they go downhill fast.
so you'll always be checking the results.  and how do you check em?  you're back to "by ear".
Comment: While I strongly encourage the "by-ear" method, it should be noted that there is indeed some software that is able to decompose audio tracks to single notes. It's called [melodyne](http://www.celemony.com) and seems to work quite well for single instrument tracks, judging from the press releases. I've never tried it myself, though...
Answer:
I have recorded the output of an in-built track on my keyboard.

"In-built tracks" more often than not are already stored as MIDI since that's the principle way to be able to play them at various speeds without incurring relevant artifacts.
If your keyboard can output them in MIDI in some manner, forget about recording the audio.  Recording this with a MIDI sequencer will give you much better material to work with.  Of course, if you can get the keyboard to somehow write a MIDI file on some internal device (USB stick or similar), you are likely to get an even better starting point with more information than the sequencing of a realtime MIDI string would deliver.
Answer: Read below if interested in a much more powerful new software tool available
(Only available circa the past ~5 years due to advances in the fields of machine learning [esp. "deep learning"] in computer science software)

For a a full example of extracting an mp3 sound file from a youtube video (in this case a piano concerto, so, not only piano, but a large ensemble orchestral accompaniments layered on top as well! - Rachmaninoff's famous Variation from his Paganini Variations Rhapsody piece, feat. the mesmerizing, practically divinely talented pianist...)
Yuja Wang Rachmaninoff rhapsody on a theme of paganini 18th variation# 2017 → to a fully automated solo piano reduction in just five minutes

Huge advances have/are recently being made in regards to software that addresses tasks precisely like this one (and many others, such as image classification, "deep fake" video generation, natural language processing summarization, speech recognition, etc.), due principally to the arrival of new techniques I'm sure we've all (or mostly have) heard of -- that is, Deep Learning. By far the best software for this I am aware of yet is called "AnthemScore". It's pretty incredible what it can do.
https://www.lunaverus.com/

So here is an example (same one as can be found in my other answer: )... This took less than 5 minutes including the downloading of the mp3 from youtube.
https://music.stackexchange.com/a/118388/74688

And here's what it looked like in AnthemScore (notice the detection of notes clearly being based off of visualizing the fundamental frequencies of the various harmonics present - ultimately this is actually visual machine learning, just like Google's famous image recognition deep learning methods)
Comment: Does this software also capture dynamics (specifically, attack volume) of each note detected, as part of the midi data?
Comment: You ARE aware that, although the conversion has detected a lot of the right notes, the transcription is unreadable and sounds terrible in playback?   Could be a useful reference basis for a manual transcription though.
Comment: @LaurencePayne Respectfully I disagree that the playback sounds terrible! But yes, absolutely, I think you are correct in saying that this is primarily a[n extraordinarily powerful/state-of-the-art] tool for creating an automatically created score from which you would then use it as a basis for manually creating a human-edited score as perfectly as you can/wish. It simply gives you a tremendous head-start; and, in addition, beyond the scope and time (and char limit) imposed within this comment context here, I would also add that the tool provides many fascinating new insights into the music..
Comment: @BruceS Update: I just checked and the short answer is YES the software does capture the attack volume ("velocity") IF you choose MIDI [See: https://www.lunaverus.com/documentation#saveOptions ] "Additional MIDI Options
Constant note volume (velocity): [...] the volume for each note will be automatically detected from the audio."
Answer: You can't do that if you are work on live recording, such records your live play using "piano/keyboard" into a Digital Audio Workstation(e.g. Nuendo) which it saves the wave sounds into it.
The possible way to do its try to records your music using a "midi-controller" keyboard like behringer umx, or plug your keyboards with a usb midi cable and connect it to your recording stuff and have recording.
Answer: https://piano2notes.com should help you but it's not free you have to pay for the full midi file but you can translate the first 30 seconds of your playing to midi for free. If you want to you could just open a midi editor and a mp3 editor and convert every 30 seconds of the edited mp3 to midi with the site and combine the midi in a midi editor, or you could just pay for the full midi it's only about 2 dollars


How to read character from file c++

Question: Is there something like fgetc in c++? File contains 3 words "send more money" and I need to solve a task where each letter represents a number(money is the answer(:D) and I add send+more), thats why I want to read each string as char array, but now I'm struggling to do so, the only info that I got is how to read everything between spaces. So, is there something like fgetc was in c or should I rethink how to do this task?
(sorry if I will be slow to respond have to go to sleep)
Comment: you mean other than `fgetc`????
Comment: go get your sleep man
Comment: File I/O questions and answers are abundant on SO, I'm sure there are plenty which already answer your question.
Comment: Do you mean `istream::get()`?
Comment: You want iostreams and cstdio and stdio.h
Comment: Wait, does fgetc work in c++, cause while looking for it I noticed that the only examples of it are written in c and this really got me mixed up http://www.cplusplus.com/reference/cstdio/fgetc/
Comment: An often quoted reason for c++'s success is that you can use c libraries with it. This of course includes the C standard library.
Comment: You could use `std::istream::read` function to read one character at a time or `std::getline` to read a line at a time, which is usually more efficient.
Comment: http://www.cplusplus.com/reference/iolibrary/ <- VERY USEFUL.
Answer: There's always std::istream::get(), which works exactly like
fgetc.  More idiomatic in C++ might be to use
std::istream::get(char&), which stores the results directly
into a char (rather than returning an int, which must be
checked for EOF before converting it to a char), and
signals end of file or an error in the usual way.
Answer: istream/fstream have a get function that will return characters
Comment: No it doesn't.  There are several `std::istream::get` functions, but none return a `char`.

How to read character from file c++


Is this a superior measure of the size of sets, to cardinality?

Question:
Is this a superior measure of the size of sets, to cardinality?

If we use points on the real line as an example of the number of elements in a set, we know that any segment has uncountably many points and any set of discrete points is countable.
Surely therefore, we can create a measure of the number of points in any subset of $\mathbb{R}$ as follows:
Sum the length of any segments into one measure; a real number (or uncountable infinity) $r$.
Sum the number of discrete points (including any endpoints of closed segments) into another measure; a natural number or countable infinity $n$.
Then we will have a measure $\lvert X\rvert_m=\{n,r\}$ with $n$ a natural number or countable infinity, and $r$ a real number or uncountable infinity.
This measure has the advantage over cardinality that it can order the sizes of some sets which are in-between some uncountably infinite sets and others.  For example, by this measure the open and closed line segments from $0$ to $1$ have measures:
$\lvert[0,1]\rvert_m=\{2,\infty\}$, and
$\lvert(0,1)\rvert_m=\{0,\infty\}$
respectively.  Whereas by cardinality, the larger set has the same measure as the smaller.
Do measures of this nature exist, and can this be translated to set theory?  It would seem that this measure, to some degree, sidesteps the problem of the continuum hypothesis, which limits the power of cardinality.
Comment: @Lovsovs you're still using cardinalities. You haven't grasped the fact that a proper superset is larger than its proper subset, even though by the measure of cardinality it might be the same.  Even though they can be put into bijection with each other, one contains all that the other set does, and more.
Comment: The nice thing about cardinality is that it shows us that, for instance the two intervals you're looking at, are actually the same size (they contain the same number of elements)! This is the case if you can create a bijection from one set to the other.
Comment: @Lovsovs I agree but it's also true there are more whole numbers than there are even numbers, because the even numbers are a proper subset of the whole numbers and when you remove them all, you have something left over.
Comment: @Lovsovs it's like if on one table you have infinitely many apples and on the other you have infinitely many apples and infinitely many oranges.  The table with apples and oranges on has more on it, because you can take infinitely many apples away from both tables, and only one will have infinitely many oranges left over.
Comment: That is actually not true (which is baffling, for sure!), when you define the size of a set in terms of bijections (which seems to be the best way). Even weirder than just the even/whole numbers having the same size, is that the number of rational numbers is the same as the number of whole numbers (even though there is an infinite amount of rational numbers in between each whole number). Moreover $\mathbb{R}^n$ has the same cardinality as $\mathbb{R}.$ ... Infinities are weird. :)
Comment: @Lovsovs perhaps it is helpful to think on the fact that the diagonal argument **follows from** an argument that $A\subsetneq B$. To then say diagonal argument is a stronger argument than $A\subsetneq B$ is false.
Comment: You write "You haven't grasped the fact that a proper superset is larger than its proper subset",  but what do you mean by "larger"? In the cases I mentioned, the set and its subset literally are [equinumerous](https://en.wikipedia.org/wiki/Cardinality_of_the_continuum) (see the introduction).
Comment: @Lovsovs do you agree equality is a stronger relation than bijection?
Comment: Not when it comes to counting. :) But I'm by no means an authority on this subject, so I will keep the discussion at that. But good luck with your question, I hope it gets an answer!
Comment: @Lovsovs I agree. When it comes to counting, equality has no greater power than bijection, because counting abstracts away the identities of the things being counted. But when we retain the identities of the things being counted, we retain the power to lean upon the notion of $A\subsetneq B$ to get a measure of size superior to cardinality.
Answer:
Sum the number of discrete points (including any endpoints of closed segments) into another measure; a natural number or countable infinity $n$.

If by "discrete point" you mean "point not contained in an interval" (note that usually "discrete point" would generally be taken to mean "isolated point") then there can be uncountably many discrete points! E.g. if we take $X$ to be the set of irrationals, then every point in $X$ is discrete in this sense, but there are continuum-many irrationals. So you need to allow $n$ to be an arbitrary cardinality $\le$ the continuum.
And this means you don't sidestep CH at all. Note, in particular, that if $X$ is an uncountable set of reals of size less than continuum then every element of $X$ is discrete in your sense, since each nontrivial interval has cardinality continuum. (This is related to your previous questions about intervals and CH; I suspect that ultimately you're conflating "point not contained in any interval in $X$" with "isolated point of $X$".) At the end of the day, for "interesting" sets of reals (that is, sets relevant to CH) counting the discrete points is exactly the same as counting the cardinality.
Finally, note that even if we expand your definition to allow $n$ to appropriately count the number of discrete points, your definition is actually less expressive than cardinality in some circumstances. E.g. consider a fat Cantor set of measure $1$ versus an interval of length $2$. Your size notion would give the first set $(0, 2^{\aleph_0})$ and the second set $(2, 0)$, so it wouldn't see that the interval is bigger than the fat Cantor set.
Comment: Re: taking precedence, ok, what if the interval has length ${1\over 2}$? Then you've declared it bigger than the fat Cantor set, but that clashes wildly with measure, which is mathematically very important. Just making more distinctions isn't inherently valuable - they have to be *mathematically meaningful*.
Comment: Thanks; interesting. I think you have transposed $n,r$ compared with me in your last para?  Anyhow... agreed $n$ can be uncountable. If $r$ takes precedence over $n$ in size, the Cantor set made up of isolated points would sit in $n$ and therefore is smaller in measure than the interval which is measured in $r$, so unless I'm mistaken I don't think it is less expressive? I'm not grasping what you mean by "every element of X is discrete in your sense". Only elements not in a segment would be discrete.
Comment: @RobertFrost Whoops, I left out the "of size $<$ continuum" there; fixed.
Comment: Ok thanks very much for your help. It's definitely meaningful, and more powerful, to capture the size of sets of points within segments and the size of sets of isolated points, separately. But I also see that we have other measures such as Lebesque measure with which this could clash, and which may have more desirable properties.


Retrieving a list of tuples with the Scala anorm stream API

Question: When I read in the Play! docs I find a way to parse the result to a List[(String, String)]
Like this:
// Create an SQL query
val selectCountries = SQL("Select * from Country")

// Transform the resulting Stream[Row] as a List[(String,String)]
val countries = selectCountries().map(row =>
row[String]("code") -> row[String]("name")
).toList

I want to do this, but my tuple will contain more data.
I'm doing like this:
val getObjects = SQL("SELECT a, b, c, d, e, f, g FROM table")
  val objects = getObjects().map(row =>
    row[Long]("a") -> row[Long]("b") -> row[Long]("c") -> row[String]("d") -> row[Long]("e") -> row[Long]("f") -> row[String]("g")).toList

Each tuple I get will be in this format, ofcourse, thats what I'm asking for in the code above:
((((((Long, Long), Long), String), Long), Long), String)

But I want this:
(Long, Long, Long, String, Long, Long, String)

What I'm asking is how should I parse the result to generate a tuple like the last one above. I want to do like they do in the documentation to List[(String, String)] but with more data.
Thanks
Answer: You are getting ((((((Long, Long), Long), String), Long), Long), String) because of ->, each call to this wraps two elements into a pair. So with each -> you got a tuple, then you took this tuple and made a new one, etc. You need to change arrow with a comma and wrap into ():
val objects = getObjects().map(row =>
    (row[Long]("a"), row[Long]("b"), ..., row[String]("g")).toList

But remember that currently tuples can have no more then 22 elements in it.
Comment: I know that the `->` is what makes like that and I tried with the `,` instead without luck. But I see now that you've added `(` and `)` and I didnt. Will try that out right away!
Comment: Thanks @Alexlv, I had missed the `(` and `)`. Feels silly to miss such a small thing.


Calculating interior angles of quadrilateral

Question: stupid question... but:
I've a polygon which has the points $(a_x,a_y),(b_x,b_y),(c_x,c_y), (d_x,d_y)$
How can I calculate each interior angle of this quadrilateral? I know that in sum, it has to be $360^\circ$.
Thanks
Answer: If you know about vectors, the dot product can help you out here.
Recall $\textbf{a.b}=a b \cos(\theta)$. Rearrange this to get your desired result.
Comment: cos^-1(a.b/ab) = alpha - like this?
Comment: Yes. So now just find the vectors which "make up" the quadrilateral and then the appropriate dot products and magnitudes
Comment: Got it! Thanks a lot ;)
Comment: No problem at all
Answer: You can use the law of cosines.  Let $p=|a-b|, q=|a-c|, r=|b-c|$ so you have drawn the diagonal from $b$ to $c$ and have a triangle with side lengths $p,q,r$.  Then if $\theta$ is the angle at $a$, you have $r^2=p^2+q^2-2pq \cos \theta$
Comment: Sorry, this looks very strange to me. Is there no "easier" solution to calculate all interior angles? I don't need to know the position of my angles. All i need to know is: "87, 93, 70,110". I know the exact positions, I know the length and I know the  area and perimeter
Comment: @Dalanie91:  the dot product that john mentions is another way to get $\cos \theta$.  Whether it is easier or not, I'm not sure.  I don't know any way that doesn't involve an inverse trig function.


Removing all 'stable' theme's CSS from a Drupal 8 custom theme

Question:
I would like to remove all CSSs automatically included from stable theme:
/core/themes/stable/css/system/components/*

I can remove them one by one inside the .info.yml file:
stylesheets-remove:
  - 'core/themes/stable/css/system/components/ajax-progress.module.css'
  - 'core/themes/stable/css/system/components/autocomplete-loading.module.css'
  - ...

Is there a way to remove all of them at once?
Something like:
stylesheets-remove:
  - 'core/themes/stable/css/system/components/*'

Answer: There's no wildcarding for the stylesheets-remove (FYI: there's a FR out there for it). However, you can use libraries-override to remove the library associated with the all CSS components you've highlighted:
libraries-override:
  system/base: false

It won't remove all CSS files in the stable theme, but it will condense removal of libraries that contain many CSS files.


On characteristic function of multivariate normal distribution

Question:
I cant make sense of (4.2), putting $Z=1$ should only establish one point not the whole function right, hence I dont see how Thm 4.1 is "proved"? Second RHS is not even a funtion of $t$. Anyone have any idea what Im missing?
Comment: Substitute m and $\sigma$ (that do depend on t) in the rhs
Comment: @Ant the $\varphi_{Z}(1)$ still puzzles me, $Z$ is the scalar product right?
Comment: Scalar product of t and X, yes. What confuses you?
Comment: @Ant that we have the first equality
Comment: Well but $\varphi_X(t) = e^{iZ}= \varphi_Z(1)$
Answer: Substitute $m$ and $σ$ (that do depend on t) in the RHS.


PayPal API: The token passed in was not found in the system

Question: I am trying to integrate Paypal with PHP, but right now I am getting the following message:
"The token passed in was not found in the system"
Here is my code. Where I am wrong?
Here is my code for getting the token, which I am getting successfully.
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.sandbox.paypal.com/v1/oauth2/token",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_USERPWD => $PAYPAL_CLIENT_ID.":".$PAYPAL_SECRET,
    CURLOPT_POSTFIELDS => "grant_type=client_credentials",
    CURLOPT_HTTPHEADER => array(
    "Accept: application/json",
    "Accept-Language: en_US"
    ),
));
$result= curl_exec($curl);
$array=json_decode($result, true);
$token=$array['access_token'];

And here I am trying to integrate v1/payments API:
$ch = curl_init();
$data = '{
"intent": "sale",
    "payer": {
    "payment_method": "credit_card",
    "payer_info": {
    "email": "'.$email.'",
    "shipping_address": {
    "recipient_name": "'.$fname.' '.$lname.'",
    "line1": "'.$address.'",
    "city": "'.$city.'",
    "country_code": "'.$country.'",
    "postal_code": "'.$zip.'",
    "state": "'.$state.'",
    "phone": "'.$phone.'"
},
"billing_address": {
"line1": "'.$address.'",
"city": "'.$city.'",
"state": "'.$state.'",
"postal_code": "'.$zip.'",
"country_code": "'.$country.'",
"phone": "'.$phone.'"
}
},
"funding_instruments": [{
"credit_card": {
"number": "'. $ccnum.'",
"type": "'.$credit_card_type.'",
"expire_month": "'.$ccmo.'",
"expire_year": "'.$ccyr.'",
"cvv2": "'.$cvv2_number.'",
"first_name": "'.$first_name.'",
"last_name": "'.$last_name.'",
"billing_address": {
"line1": "'.$address.'",
"city": "'.$city.'",
"country_code": "'.$country.'",
"postal_code": "'.$zip.'",
"state": "'.$state.'",
"phone": "'.$phone.'"
            }
        }
    }]
},
"transactions": [{
"amount": {
"total": "'.$cost.'",
"currency": "GBP"
},
"description": "This is member subscription payment at Thecodehelpers.",
"item_list": {
"shipping_address": {
"recipient_name": "'.$fname.' '.$lname.'",
"line1": "'.$address.'",
"city": "'.$city.'",
"country_code": "'.$country.'",
"postal_code": "'.$zip.'",
"state": "'.$state.'",
"phone": "'.$phone.'"
}
}
}]
}';

//curl_setopt($ch, CURLOPT_URL, $PAYPAL_API_URL."v1/payments/payment");
curl_setopt($ch, CURLOPT_URL, "https://api.paypal.com/v1/payments/payment");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: Bearer ".$token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
//curl_close($ch);
$json = json_decode($result);

//$state=$json->state;
echo "
";
print_r($json);
exit;

Answer: You used a sandbox API client ID and secret to request an access_token in sandbox mode (https://api.sandbox.paypal.com/v1/oauth2/token)
Then you attempted to use a sandbox access token for a live/production API call (https://api.paypal.com/v1/payments/payment)
Sandbox tokens (as well as all other identifiers) only work in the sandbox environment, and live ones only work in live. The two environments are completely separated.

Moreover, v1/payments is a deprecated API, and should not be used for any new integrations. Use the current v2/checkout/orders API to create and capture an order instead.

For payer approval, use https://developer.paypal.com/demo/checkout/#/pattern/server . However, you must remove all echo and print statements from your PHP to do so; only a JSON string must be outputted when your create or capture routes are called.

Late edit: The standard integration guide and integration builder were expanded to better cover a JS SDK + server backend integration. The guide's sample backend code is given in node.js (since javascript is widely understood) but you can implement those server routes from any backend environment.
Comment: i replaced url with " https://api.sandbox.paypal.com/v1/payments/payment"

But now i am getting following message

[field] => payer.funding_instruments[0].credit_card
                    [issue] => Invalid expiration (cannot be in the past)
Comment: You're using a deprecated API and furthermore that API's support for processing cards was removed long ago, read the notice at https://developer.paypal.com/docs/api/payments/v1/ . Current supported alternatives are a full Braintree gateway integration, the simple black "Debit or Credit Card" button of a simple JS SDK integration using the orders API (see  https://developer.paypal.com/demo/checkout/#/pattern/server  and click on the black button ), or the Advanced Integration. See the options at https://developer.paypal.com/docs/checkout/
Comment: not understand your point, just tell me can we do this via api ? if yes then how can i do this ? kindly tell me code so i can check and i can implement in my side
Comment: See above for the options available to you. All of them use APIs.
Comment: not working , kindly give me exact url so i can follow
Comment: Sorry, I cannot research the best options for your use case. The above links are enough to get started.


Why can't I use `predict` inside a data.table?

Question: I'm trying to use predict.lm inside data.table, and getting a strange error. The first part, data-prep, runs perfectly.
# (1) Load data
library(data.table)
homeprice = fread('https://vincentarelbundock.github.io/Rdatasets/csv/mosaicData/SaratogaHouses.csv')

# (2) Data Prep: Convert character variables into factors.
myvars = c('heating','fuel','sewer','waterfront','newConstruction','centralAir')
for (var in myvars) {
   homeprice[, paste0(var) := as.factor(get(var))]
}

# (3) Split data into training and test sets
install.packages('caTools')
library(caTools)

homeprice[, split := sample.split(V1, SplitRatio = 0.5)]
train = homeprice[split == T,] # Creating training data
test = homeprice[split == F,] # Create test data

# Train OLS model with training data.
reg1 = lm(price ~ . - V1, train)
summary(reg1) # Displays the results from "myfirstreg"

OK, here is the part that's giving me trouble:
# In sample-prediction: Predict prices for training set
z = predict(reg1, newdata = train)
train[, price_pred := z] # Works perfectly
train[, price_pred := predict(reg1, newdata = train)] # Gives error

Please advise.
Comment: Error in eval(predvars, data, env) :
  invalid 'envir' argument of type 'logical'
Answer: I don't know what causes the error but using dplyr
train <- train %>%
  mutate(price_pred = predict(reg1, newdata = train))

seems to give the same results as your exapmle that does work.
Answer: It appear that the presence of the "split" variable, which was used to split the original dataset, was giving problems. Removing it from the regression appears to solve the issue.
reg1 = lm(price ~ . - V1 - split, train)

Comment: maybe try something like `train[, price_pred := predict(reg1, newdata=.SD), .SDcols=-"split"]`


how to append of merge two array of objects in type script

Question: i am having two array object as follows. This to be done in a loop using typescript. The both objects are dinamically generated from sql api and filtered
Array of Object 1
customers = [
              {
                id = '1',
                name = 'John',
                engg_id = '6'
              },
              {
                id = '2',
                name = 'Max',
                engg_id = '5'
              },
              {
                id = '3',
                name = 'Rob',
                engg_id = '6'
              },
              {
                id = '4',
                name = 'Rob',
                engg_id = '6'
              }
            ]

Array of Object 1
enggNames = [
              {
                engg_name = 'Surya'
              },
              {
                engg_name  = 'Syed'
              },
              {
                engg_name  = 'Surya'
              },
              {
                engg_name  = 'Surya'
              }
            ]

the above array of object to get append to the customers array of objects as below.
Required Array of Objects
customers = [
              {
                id = '1',
                name = 'John',
                engg_id = '6'
                engg_name  = 'Surya'
              },
              {
                id = '1',
                name = 'John',
                engg_id = '6'
                engg_name  = 'Syed'
              },
              {
                id = '1',
                name = 'John',
                engg_id = '6'
                engg_name  = 'Surya'
              },
              {
                id = '1',
                name = 'John',
                engg_id = '6'
                engg_name  = 'Surya'
              }
            ]

Answer: Iterate your two arrays in the same time and spread values in your results array:
const merge = []

for (let i = 0; i < customers.length; i++) {
  merge.push({
    ...customers[i],
    ...enggNames[i]
  })
}

See this working on Stackblitz.
Answer: You can try this.
customers = customers.map( (customer, index) => {
               customer.engg_name = enggNames[index].engg_name;
               return customer;
            });

Hope it helps.
Answer: You can use .map() to iterate over your data and use Object.assign() to merge properties form multiple objects.

const arr1 = [
  { id: '1', name: 'John', engg_id: '6' },
  { id: '2', name: 'Max', engg_id: '5' },
  { id: '3', name: 'Rob', engg_id: '6' },
  { id: '4', name: 'Rob', engg_id: '6' }
];

const arr2 = [
  { engg_name: 'Surya' },
  { engg_name: 'Syed' },
  { engg_name: 'Surya' },
  { engg_name: 'Surya' }
];

const merge = (a1, a2) => a1.map((o, i) => Object.assign({}, o, a2[i]));

console.log(merge(arr1, arr2));
.as-console-wrapper { max-height: 100% !important; top: 0; }


Windows cmd finding fully qualified path name

Question: Hi i was just wondering if any knew how to find the fully qualified path name for say Paint or other programs?
Answer: Where does something similar to "which". Looks to see what would be run, if you ran the application from the commandline.
H:\>where.exe mspaint.exe
C:\Windows\System32\mspaint.exe

This will only find things on the path.
A similar command in powershell does the same thing -'get-command'.
You could scour the file system using a find, eg.
C:\>dir /b /s c:\ |find "mspaint.exe"
c:\Windows\System32\mspaint.exe
c:\Windows\System32\en-GB\mspaint.exe.mui
c:\Windows\SysWOW64\mspaint.exe
c:\Windows\SysWOW64\en-GB\mspaint.exe.mui
...
...

which will locate things that are not on the path (and everything else besides)
Comment: what about for finding non windows prorams like google chrome?
Comment: the where command finds executables on your path, if Chrome is there, you should be able to find it -it is not just for Windows applications. Otherwise, you have to use "find".
Comment: no need for `find`. `dir` can do it for you: `dir /s /b c:\mspaint.exe` ( "c:\" is the start path for searching, so maybe better: `dir /s /b %systemdrive%\mspaint.exe`)