Typescript: Trying to make this dictionary of dictionaries work

Question: I'm trying to make a dictionary of other dictionaries work but just work "sometimes".
I have this dictionaries that i call "books" in each of them there are a group of objects of the same model.
So I turn this arrays of  objects of the same model into this "books"/dictionaries and then I gather the books inside a "library"/dictionary.
The idea is being able to access every book from the same place like:
"library.book[object key]"
When I console log the whole library every book is there..

Object {  }

education: Object {  }

: Object { … }

experience: Object { "L&A Construcciones": {…}, Aegis: {…}, test123: {…}, … }

matt: Object { id: 1, first_name: "Rodrigo", last_name: "Luna", … }

projects: Object { test: {…}, "this is another test": {…}, "yet another test": {…} }

skills: Object {  }

: Object { … }
app.component.ts:88:12

..but when i try to access a book(or console.log it) gives me a error that says that the book is  undefined.
Im totally missing the problem and i need some help
Edit. This is a part of the complete code.
So It works like this on init first calls a get"book" that gets the data from a spring data base. This data comes as an array. So in gatherMuseLibrary i turn this array into a dictionary object and put it inside another dictionary using the "bookName" as the key and then i access the book inside of museLibrary to make some arrays that i need for another part of the programm. This part as no trouble at all. I can actually access the books at this point and make the arrays like "codingSkills".
The problem is when i call "getSubjects". When i console.log the whole library inside of "getSubjects" there is no problem, i can see every book. But when i try to access each book to get some info the books are undefined. And I'm using the same method to access the books that in the get"Book" with "keys()".
I hope this helps :/
codingSkills: Array<SkillModel> = [];
writingSkills: Array<SkillModel> = [];
lifeSkills: Array<SkillModel> = [];

//Muse Needs
museLibrary: {[key: string]: {[key: string]: any}}= {};

ngOnInit(): void {
    this.getSkills();
    this.getSubjects();
}
getSkills(){
    this.skillService.getAllSkills().subscribe(data =>{
      this.gatherMuseLibrary("skills", data)
      if (this.museLibrary.skills !== undefined){
        for (let key of Object.keys(this.museLibrary.skills)){
          let skill = this.museLibrary.skill[key]
          switch(skill.type){
            case "Coding": this.codingSkills.push(skill); break;
            case "Writing": this.writingSkills.push(skill); break;
            case "Living": this.lifeSkills.push(skill); break;
          }
        }
      }
    })
}
gatherMuseLibrary(bookName: string, data: any){
    const book: {[key: string]: any} = {};
    for (let element of data){
        book[element.name] = element;
    }
    this.museLibrary[bookName] = book;
}
getSubjects(){
    console.log(this.museLibrary);
    console.log(this.museLibrary.skills);
    for (let bKey of Object.keys(this.museLibrary)){
        console.log(this.museLibrary[bKey])
        let book = this.museLibrary[bKey];
        console.log(book);
        for (let key of Object.entries(book)){
            let value = book.key
            console.log(`${key} -> ${value}`);
        }
    }
}```

Comment: Please provide a [mre] suitable for demonstrating your issue when pasted, as-is, into a standalone IDE, so we can work on the problem directly.  Right now `this.museLibrary` is not defined, and your type `data: []` means `data` is always an empty array, which is presumably not what you intend.  Also you should comment the code exactly where the error occurs and what the text of the error is, so we're all on the same page.  You might want to review the guidelines for [ask] and what a [mre] is.  Good luck!
Comment: `Object.entries` is likely what you want in for inner loop. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
Comment: I just added some more code and an explanation of how everything should work.
Answer: This loop doesn't work, unless you define an iterator on your book objects (which doesn't seem to be the case)
  for (let key of obj){}

Try to console.log(this.museLibrary[bKey]) to make sure the book is being saved correctly.
Comment: When I try to console.log(this.museLibrary[bKey]) it tells me that is undefined. But in the previous line i can console.log(this.museLibrary) just fine.
Comment: Did you print Key also?


multiple regression for job satisfaction

Question: I would like to know how professional and demographic variables influence job satisfaction.
Which method do I have to use?
lm.out <- lm(pv1~AGE+EDU+SIZE+SCOPE+MGMT+SCOPE+TENURE+COLLAR+SEX, data=data)

or this model?
output1 <- lm(pv1~AGE, data=data)
output2 <- lm(pv1~AGE+EDU, data=data)
output3 <- lm(pv1~AGE+EDU+SIZE, data=data)
output4 <- lm(pv1~AGE+EDU+SIZE+SCOPE, data=data)
output5 <- lm(pv1~AGE+EDU+SIZE+SCOPE+MGMT, data=data)
output6 <- lm(pv1~AGE+EDU+SIZE+SCOPE+MGMT+SCOPE, data=data)
output7 <- lm(pv1~AGE+EDU+SIZE+SCOPE+MGMT+SCOPE+TENURE+COLLAR, data=data)
output8 <- lm(pv1~AGE+EDU+SIZE+SCOPE+MGMT+SCOPE+TENURE+COLLAR+SEX, data=data)

Comment: What's going on in those eight outputs, some kind of stepwise regression? Why not start with education or size? (Stepwise regression is discouraged, anyway, though I want to read what you say is happening in those models.)
Comment: How would you analyse the effects of demographic and professional characteristics on job satisfaction? Just a multiple regression or a stepwise regression?
Answer: Do not perform any stepwise procedure to select variables
Stepwise is bad. When you are interested in inference, as you seem to be, there is no hope in uncovering the "correct" estimates.
You are interested in:

how professional and demographic variables influence job satisfaction

The first thing to do is carefully consider whether any of the variables in question are inter-related in a causal way. For example, education is likely to "cause" tenure - that is people with longer time in education may be more likely to be in a position of tenure. Perhaps tenure "causes" job satisfaction, but education itself does not. That means that the causal effect of education is mediated by tenure. Perhaps there is some direct effect of education, in which case it will be partially mediated. When you are interested in estimating the causal effect of education on job satisfaction, it is vitally important that you do not include mediators in the model. Thus, depending on what your main exposure is (for example, education here), you will have a different set of variables to condition on (include in your model). The general rules are:

include variables that are confounders (common cause of both the exposure and the outcome
do not include variables that are mediators (lie on the causal path between the exposure and outcome)
include variables that are competing exposures - causes of the outcome that are unrelated to the exposure.

The best way to do this is by using a causal diagram (or DAG). See this question and answers for details of how to do that:
How do DAGs help to reduce bias in causal inference?
Comment: That is impossible to say. But you can easily extent a linear model with nonlinear terms if you think that is justified, fo example by including `AGE^2` in the model. It is still a linear model though.
Comment: Can I treat it as a linear regression. Or would a nonlinear regression make more sense?


Laravel pagination with API resources

Question: Laravel pagination has different structure when returned by itself vs. through an API resource.
return $query->paginate(request('per_page'));

returns pagination with this structure:
{
    "current_page": 1,
    "data":[...],
    "first_page_url": "http://user-service.test/api/users?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://user-service.test/api/users?page=1",
    "next_page_url": null,
    "path": "http://user-service.test/api/users",
    "per_page": 15,
    "prev_page_url": null,
    "to": 10,
    "total": 10
}

On the other hand, sending the paginator through an API resource like this:
return new UserCollection($query->paginate(request('per_page')));

returns this structure:
{
"data":[...],
"links": {
    "first": "http://user-service.test/api/users/searches?page=1",
    "last": "http://user-service.test/api/users/searches?page=6",
    "prev": null,
    "next": "http://user-service.test/api/users/searches?page=2"
    },
"meta": {
    "current_page": 1,
    "from": 1,
    "last_page": 6,
    "path": "http://user-service.test/api/users/searches",
    "per_page": "1",
    "to": 1,
    "total": 6
    }
}

I need to have the same structure for both types. Am I doing something wrong?
Answer: After some digging I found a solution for this, hope it's helpful.
So this line is fine
return new UserCollection($query->paginate(request('per_page')));
As long as you change the UserCollection toArray() function to:
    public function toArray($request)
    {
        return [
            'current_page' => $this->currentPage(),
            'data' => $this->collection->toArray(),
            'first_page_url' => $this->url(1),
            'from' => $this->firstItem(),
            'last_page' => $this->lastPage(),
            'last_page_url' => $this->url($this->lastPage()),
            'next_page_url' => $this->nextPageUrl(),
            'path' => $this->path(),
            'per_page' => $this->perPage(),
            'prev_page_url' => $this->previousPageUrl(),
            'to' => $this->lastItem(),
            'total' => $this->total(),
        ];
    }

This snippet of code is from the original implementation of LengthAwarePaginator, this way you could have consistent pagination for both collections and simple use of LengthAwarePaginator (->paginate() function).
Answer: That's because you created an Eloquent Resource.
As you can see in the doc, it's taking $this->collection and wraps it around a customer format.
If you wish to have the same format, you do not need to return the UserCollection, just return $query->paginate(request('per_page'))
Without seeing more of your code and how are you using your UserCollection class, it's hard to recommend to keep it or remove it. Also, please read the high overview of that concept here
Answer: just do this
public function __construct($resource)
{
    $this->pagination = [
        'total' => $resource->total(),
        'per_page' => $resource->perPage(),
        'current_page' => $resource->currentPage(),
        'last_page' => $resource->lastPage(),
        'from' => $resource->firstItem(),
        'to' => $resource->lastItem(),
        'count' => $resource->count(),
        'total_pages' => $resource->lastPage()
    ];

    $resource = $resource->getCollection();

    parent::__construct($resource);
}

/**
 * Transform the resource collection into an array.
 *
 * @param  Request  $request
 * @return array
 */
public function toArray($request): array
{
    $this->pagination['data'] = $this->collection;

    return [
        $this->pagination
    ];
}

Laravel pagination with API resources


Multiple parents for one resource MODx Revo

Question: I use pdoTools and I need to assign one resource to many parents, but physically it'll be in one parent category. What I already did:
Created a new TV "listParents", and in Input Options @eval return $modx->runSnippet('listParents');
Created snippet "listParents"
<?php
$criteria = $modx->newQuery('modResource');
$criteria->where(array(
    'published' => 1,
    'deleted' => 0,
    'isfolder' => 1,
    'template' => 6,
    array('AND:id:!=' => 6)
));
$criteria->sortby('menuindex', 'ASC');
$collection = $modx->getCollection('modResource', $criteria);
$output = array();

foreach ($collection as $v) {
    $output[] = !empty($v->get('menutitle')) ? $v->get('menutitle') : $v->get('pagetitle') . '==' . $v->get('id');
}

return implode('||', $output);

Now I can see all categories in resources: http://prntscr.com/gbq34i and can mark in which categories it should output too besides parent category http://prntscr.com/gbq9y3.
And if I want to go to one of checked categories, I should see this resource. But how can I output it via pdoTools?
Answer: I was needed to add small check:
if($isHideInMenu == '1' AND $modx->resource->get("id") != '1') {
  $params['tvFilters'] = 'listParents==%' . $modx->resource->get("id") . '%';
}

The key is this line: $params['tvFilters'] = 'listParents==%' . $modx->resource->get("id") . '%';
It'll find all rows with id of current page, which stores in listParents.


Matching string that contain Metacharacters with re.findall() and re.escape()?

Question: What is the regular expression for matching a sentence that contains metacharacters ?
Following the senario :
I have a string : line = "He finally answer (after taking time to think (5 minutes) * sighs ; end)"
I want to match this part of the sentence : line2 = "after taking time to think (5 minutes) * sighs ; end"
But i don't want to use a regex to find the element inside of parentheses
For that I am using : re.findall(re.escape(line2), re.escape(line))
But I'm getting an empty result
Answer: No need to execute the escape method over text(variable line in this case) you are providing:
import re

line = "He finally answer (after taking time to think (5 minutes) * sighs ; end)"

line2 = "after taking time to think (5 minutes) * sighs ; end"

result = re.findall(re.escape(line2), line)

print(result) # ['after taking time to think (5 minutes) * sighs ; end']


Is is feasible to walk/run an average of 90,000 steps a day?

Question: I use the Samsung S-Health app which has a global step challenge with a public leaderboard. To complete the challenge, you need to walk 200,000 steps in the month.
Looking over the leaderboard though, there are some people with ridiculously high step counts:

Fifth place has ~2.5 million steps. 2.5 million / 27 (days so far) = ~92593 steps/day!
As someone who walks ~8k steps a day, and has a record count of 40k steps in one day, 90k steps a day on average seems impossibly high. I filed a report to Samsung noting how the counts seem suspicious, and they replied, assuring me that they take cheating seriously and that the leaderboard is legitimate.
Is it remotely feasible to walk more than 90,000 steps a day, every day for a month? Is this something that someone may do in the course of training or some running sport?
Comment: They probably shared the tracking device. But you'd be better off asking this kind of question on [Outdoors.SE](https://outdoors.stackexchange.com/). Sports.SE is primarily for competitive sports.
Comment: I once walked 33 miles in a day (say ~65k steps) , I couldn't move for the next 2-3 days!  I was a very fit and healthy 20 year old back then.  I wonder if these apps can be tricked into thinking you're walking when placed on objects such as washing machines that vibrate or move in a certain way.
Comment: @davidjwest That's what I'm wondering, as many cheaper pedometers are susceptible to that. If walking that is remotely feasible, I'd give them the benefit of the doubt, but the consensus seems to be that its not.
Answer: In effect, the people at the top of this list are saying that they walk an equivalent of 50 miles a day or so, every day. Finding myself skeptical, I've done a bit of research.
A world-class race walker can cover 50 km in about four hours. That translates to about 30 miles in four hours. That means that walking at that pace would require about seven hours to cover 50 miles, if one could keep it up that long.
After a 50k race, a competitor typically needs two to three weeks to recover.
So, it seems very feasible that there are thousands of people in the world who could cover 50 miles in 10 hours, at the rapid pace of five mph. (And billions who cold not.) It seems highly unlikely that there are more than a few people — if any — in the world who would be able to do it for 30 days in a row.
I remain skeptical that these numbers are even remotely accurate, Samsung's assertions to the contrary notwithstanding.
Edit: it would seem that we are far from alone in our skepticism of these numbers, to the point that the "challenge" appears generally regarded as something of a joke.
Answer: I would say that it's highly unlikely but not impossible to take 90k steps in one day.
According to the Guinness Book of World Records Walter Geckle walked 108.75 miles in a 24 hour period.
http://www.guinnessworldrecords.com/world-records/farthest-distance-nordic-walking-in-24-hours
According to Temple University there are about 2k steps in a mile. so 2000 x 108.75 = 217,500 steps https://www.temple.edu/hr/departments/benefits/documents/Conversion_Chart.pdf
Finally, in case you're wondering what Nordic Walking is ... https://en.wikipedia.org/wiki/Nordic_walking
Comment: The OP is not just asking about 1 day. Is it possible to do it daily for a month?
Comment: I did actually say highly unlikely, also one could not do this a single time without hard core training - I couldn't even begin to speculate what that would look like
Answer: The average adult's - male or female - stride length is 2.5 feet.  Two steps is 5 feet.  Doing the math (90,000x2.5)/5280, 90,000 steps equals about 42.6 miles. I would be very dubious that any person walks an average of 42+ miles every day.  Maybe they attach the pedometer to their little Chihuahua.
Answer: Samsung's challenge leaderboard is a joke, and I have serious doubts about even some of the lower numbers being posted.
My personal best with a fitness tracker was just over 42,000 steps in a day. I logged that with a Fitbit, which counted a higher step total than my Samsung watch. This happened on a Saturday, starting with a long walk before dawn and ending with a late night rebounding session. I did my regular P90X workout session and I was moving constantly throughout the day. Still, I had to work hard to reach 40,000 and I was feeling the effects of that effort several days later.
So to answer the question, no, an average of 90,000 steps a day is not sustainable. I'd argue that even 40,000 steps a day isn't sustainable for a month. If you look at the average daily steps of all Samsung Health users, it's somewhere in the range of 6,000. When you consider that blatant cheaters are skewing that average... Well, you figure it out.
Any daily average over 20,000 steps is an accomplishment, and it takes a real commitment of time and energy to achieve even that.
Answer: I have a treadmill desk which I use while working.  I am a full time stock trader and comfortably can work and walk at a pace of just under 3 miles per hour.  For 2020, I averaged 46,967 steps per day as measured on my fitbit app (and this misses some of my steps for recharging).  On a typical weekday, I walk 55,000 steps and weekends 40,000 steps.  I am 67 years old.
I've walked one week over 60,000 steps per day and a few days in the year under 20,000 day (on vacation in Europe).  Overall, when I push it, I can easily get 70,000 steps in a day (and on one day exceeded 80,000.  So is it possible to do 50,000 steps per day.  I would say easily.
If I really pushed it, I think at 67, I could do 70,000 steps in a day.  So a young stud at 25, should be able to do 90,000 steps per day.  I think these numbers are believeable.


Configure apache as proxy and remap one domain

Question: For local test, I'm using Charles proxy, for those who don't know about it is a tool to debug HTTP requests. It can be configured to act as a proxy and intercept requests/responses and is able to do several things with it, like the most important for me, "remap" a domain to another.
It means that when I want set up the proxy on my mobile device and try to access a.domain.tld and b.domain.tld I can configure Charles to redirect transparently data to c.domain.tld and d.domain.tld.
This is what I want to do with Apache (preferably) (but suggestion are welcome).
I know a little about mod_proxy but I couldn't find any similar example, I bet I can do something with it while playing around with the rewrite mod, but I'm sure there is a simple thing to do.
What I want to do:

Configure a vhost within apache called proxy.domain.tld
It will act as any proxy except for the domain a.domain.tld and b.domain.tld for which it will target c.domain.tld and d.domain.tld respectively instead.

Any advices?
Comment: In other words: you want to set up a proxy that will transparently hijact certain requests and divert them to some other hosts?
Comment: @Laas, exactly, I want to test some live mobile application against a new code base
Answer: Shooting from the hip, the ProxyRemote should be the thing you are looking for. The intent of that directive is to allow one proxy to forward some requests to next while serving others directly. Untested, but it should be possible to use this to your advantage:
ProxyRequests On
ProxyVia On

<Proxy *>
  Order deny,allow
  Deny from all
  Allow from 188.8.131.52

  # Redirect these two domains to different destination
  ProxyRemote http://a.domain.tld http://c.domain.tld
  ProxyRemote http://d.domain.tld http://d.domain.tld
</Proxy>

NB!: Be sure to fill in some real IP numbers or other authentication, so you dont create yourself an open proxy.
Comment: thank you for your answer, I give it a try but I couldn't make the ProxyRemote directive work
Comment: Maybe set `LogLevel debug` and scan the logs to see what happens. I'm not exactly sure whether the `ProxyRemote` endpoints can be regular HTTP servers or must they be proxies themselves too.


concept drift detection

Question: I'm working on a project that involves concept drift detection for a time series. Are there any well-known techniques/methods/algorithms that are known to be effective for this sort of problem?
Currently, I was thinking of using a Kalman filter approach.
Answer: You might find these useful:

Learn++.NSE from Prof.Robi Polikar. This is his official page which offers lots of additional information, papers on the topic etc. and it is a great starting point.
The GitHub repository of gditzler contains an implementation of incremental learners in MATLAB.

Additionally the Concept Drift wiki page, under sections Projects and Meetings has lots of other materials.hth.
UPDATE
I came across a paper

"Incremental Learning of Support Vector Machines" by Classiffier Combining by Wen and Lu.

stating superior performance and efficiency than concept drift methods.
Comment: whenever possible please provide enough information to still be able to access the information in case the link dies (e.g., instead of "this guy", provide the user name)
Comment: yes, you are right. fixed.

concept drift detection


Arguments.callee - Factorial Pattern

Question: Assuming:
var x = {
  y: function(n){
    console.log(n);
    console.log(n+":"+( n > 0 ? arguments.callee(n-1) + "o" : "all" ));
  }
};
x.y(4)

Console log:
4
3
2
1
0
0 -> all
1 -> o
2 -> o
3 -> o
4 -> o

The first part of the console.log makes sense to me, we're starting with n=4 , and calling the function itself with n-1, ends up 4,3,2,1,0.
However,
the output of
console.log(n+":"+( n > 0 ? arguments.callee(n-1) + "o" : "all" ));

is a bit irritating since it returns the result in a 'reversed' order.
Why is the value of n as first part of that execution, without arguments.callee in it giving a different result than calling it from within a ternary operator with arguments.callee?
Is this a matter of pure definition or is there another logic reason for this?
The process would be as the following:
(n=4) = ( 4 > 0 ? arguments.callee(3) + "o" : "all" ) = "o"
  (n=3) = ( 3 > 0 ? arguments.callee(2) + "o" : "all" ) = "o"
    (n=2) = ( 2 > 0 ? arguments.callee(1) + "o" : "all" ) = "o"
      (n=1) = ( 1 > 0 ? arguments.callee(1) + "o" : "all" ) = "o"
        (n=0) = ( 0 > 0 ? arguments.callee(1) + "o" : "all" ) = "all"

Doesn't this have to end up in ooooall instead of alloooo?
Cheers
Comment: Huh? *"Why is the value of n as first part of that execution..."* Because...that's what the code does. What's the real question here? Note the `console.log(n)` prior to the other `console.log`.
Comment: The ?'s are meant to express a question each. Thank you.
Comment: This post additionally helped on solving the problem:
[Tail Recursion][1]

  [1]: http://stackoverflow.com/questions/33923/what-is-tail-recursion
Answer: When you make the recursive call in the middle of the expression, that call has to execute to completion. What happens in the recursive call? Another iteration of that console.log(), that's what. Therefore, before the first (corresponding to 4) call can complete, the calls for 3, 2, 1, and 0 have to complete first.
Also, there's no reason to use arguments.callee. Just give your anonymous function an internal name:
var x = {
  y: function y(n){
    console.log(n);
    console.log(n+":"+( n > 0 ? y(n-1) + "o" : "all" ));
  }
};

Assuming you're not a time traveler from 2008, that y name is only bound inside the function.
Comment: Bam. Gotcha. Thank you.
Answer: No, because is a recursive function so, when last function end ("all") then all previous console.log will print in reverse order (really is not reverse order, it's the correct order because is a recursive function), for example, we have the 5 steps that you say: (n=4, n=3 ... n=0):
f4 -> f3 -> f2 -> f1 -> f0
we saw that f4 calls f3, f3 calls f2 ..... and f1 calls f0. Well, when f0 finish, did the console.log with output "0" and "all", then, this function (f0) return to previous function (f1) that prints the letter "o", then f1 return to f2 ...... and the same way until return to the first function f4.
It's difficult to explain but easy to understand. I hope that my "explanation" could be enough.

Arguments.callee - Factorial Pattern


I need to prove that $\hat\theta=\max\{X_1,...,X_n\}$ is a mean square consistent estimator for $\theta$

Question: Let $X_1,...,X_n$ a i.i.d from a population with distribution $U[0,\theta]$, i.e.,
$f_{X_i}(x)=\frac{1}{\theta}g_{[0,\theta]}(x)$, for $i=1, \ldots, n$
where
\begin{align}
g_{[0,\theta]}(x) =
\begin{cases}
1 & x \in [0, \theta], \\
0 & x \notin [0, \theta].
\end{cases}
\end{align}
How to prove that $\hat\theta = \max\{X_1, \ldots, X_n\}$ is a root mean square consistent estimator for $\theta$?
I know that an estimator $\hat\theta_n$ is consistent in root mean square if it fulfills that
$$\lim\limits_{n \to \infty}MSE(\hat\theta_n)=0.$$
with $MSE(\hat\theta_n)=E[(\hat\theta_n-\theta)^2]=\operatorname{Var}(\hat\theta_n)+(E(\hat\theta_n)-\theta)^2$.
Comment: @WillowDouglas Exactly, so can you find the CDF of $X_{(n)} := \max(X_1, \ldots, X_n)$?  It is a pretty standard result.
Comment: @WillowDouglas What you "tried to show" is impossible to hold (which would imply $\hat{\theta} \equiv \theta$).  The correct procedure obviously relies on "$\lim_n$".
Comment: What have you tried?
Comment: I tried to show consistency proving that $E(\hat\theta)=\theta$ and $Var(\hat\theta)=0$ but I'm not sure if that's enough to prove root mean square consistency
Comment: @Zhanxiong, my guess is to find the bias from the estimator (by finding $E(\hat\theta_n)$) and $Var(\hat\theta_n)$. But first you have to find the CDF and the density function of the estimator.
Comment: CDF of $\hat\theta_n$ would be :=$\frac{z^n}{\theta^n}$ and then you can easily get the pdf by computing the derivative...
Comment: @Zhanxiong I have the doubt if the CDF of $\hat\theta_n$ would be :=$\frac{x^n}{\theta^n}$ or $\frac{1}{\theta^n}$. Since $g(x)=1$ for $0<=x<=\theta$
Comment: I don't follow how the doubt arises; what's the cdf of $X$? (NB it's not $g$)
Answer: The standard way is to find the CDF of $\hat{\theta}_n$ first, which is
\begin{align*}
F(x) := P(\max(X_1, \ldots, X_n) \leq x) = \prod_{i = 1}^n \frac{x}{\theta} =
\frac{x^n}{\theta^n}, \; 0 \leq x \leq \theta.
\end{align*}
This implies the PDF of $\hat{\theta}_n$ is $f(x) = nx^{n - 1}/\theta^n$ for $0 \leq  x \leq \theta$ and $0$ otherwise, whence
\begin{align*}
E[(\hat{\theta}_n - \theta)^2] = \int_0^\theta(t - \theta)^2f(t)dt =
\frac{n}{\theta^n}\int_0^\theta (t - \theta)^2t^{n - 1}dt. \tag{1}
\end{align*}
To evaluate the integral $(1)$, apply the variable substitution $u = t/\theta$, which transfers $(1)$ to
\begin{align*}
n\int_0^1\theta^2(1 - u)^2 u^{n - 1} du = \theta^2nB(3, n), \tag{2}
\end{align*}
where $B(a, b)$ is the Beta function.  Since $B(a, b) = (a - 1)!(b - 1)!/(a + b - 1)!$ when $a, b$ are positive integers,  the right-hand side of $(2)$ equals to
\begin{align}
\theta^2 \frac{2n(n - 1)! }{(n + 2)!} = \frac{2\theta^2}{(n + 2)(n + 1)},
\end{align}
which converges to $0$ as $n \to \infty$.  This shows that $\hat{\theta}_n \to \theta$ in quadratic mean.
The above method is straightforward.  However, it involves pretty heavy calculations (you may circumvent summoning the Beta function by expanding $(1 - u)^2$ then applying linearity of the integral, which requires less machinery). This motivates me to consider the following alternative solution.
First, show that $\hat{\theta}_n$ converges to $\theta$ in probability.  I will leave this to you as an exercise.  It is similar to finding the CDF of $\hat{\theta}_n$.
Next, for any $\epsilon \in (0, \theta)$, we have
\begin{align*}
& E[(\hat{\theta}_n - \theta)^2] =
E\left[(\hat{\theta}_n - \theta)^2I_{[|\hat{\theta}_n - \theta| \leq \epsilon]}(\omega)\right] +
E\left[(\hat{\theta}_n - \theta)^2I_{[|\hat{\theta}_n - \theta| > \epsilon]}(\omega)\right] \\
\leq & \epsilon^2 + 4\theta^2P[|\hat{\theta}_n - \theta| > \epsilon]. \tag{3}
\end{align*}
Since $\hat{\theta}_n$ converges to $\theta$ in probability, the second term in $(3)$ converges to $0$ as $n \to \infty$. Since $\epsilon$ is arbitrary, this implies that $E[(\hat{\theta}_n - \theta)^2] \to 0$ as $n \to \infty$, completing the proof.
Comment: Well if you show convergence in probability then by Vitali's convergence theorem you have $L^p$ convergence since the sequence of random variables $\hat{\theta}_n$ is uniformly integrable (in fact, its bounded). I guess your last step is encapsulating part of the proof of that theorem.


Does $\frac{f'}{f}=\frac{g'}{g}$ imply that $f$ and $g$ only differ by a constant multiple?

Question: Suppose that $f$ and $g$ are both entire, does $\frac{f'}{f}=\frac{g'}{g}$ imply that $f$ and $g$ only differ by a constant multiple? For the situation that $f$ and $g$ are real and positive this is not hard to see, since they are log derivatives. But how to prove this if $f$ and $g$ are complex functions?
Comment: They don't need to be entire, just nonzero and holomorphic in a connected open set. If the domain is not connected, then it's still true that they differ by a constant multiple, but his constant may be different for different connected components.
Answer: Hint
$$\frac{f'}{f}=\frac{g'}{g} \Leftrightarrow \\
f'g=fg' \Leftrightarrow \\
f'g-fg'=0 \Leftrightarrow \\
(\frac{f}{g} )'=0$$


call to undefined function apache_request_headers Slim framework

Question: I'm only posting this because none of the other posts have helped solve my problem. I'm using slim and advanced rest api app on chrome for testing. I've tried many suggestions on the web but nothing is working. I'm running php 5.5 on hostgator. I am getting the error when passing authorization header:

call to undefined function apache_request_headers()

  <?php

require_once '../include/DbHandler.php';
require_once '../include/PassHash.php';
require '.././libs/Slim/Slim.php';

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

// User id from db - Global Variable
$user_id = NULL;

function authenticate(\Slim\Route $route) {
    // Getting request headers
    $headers = apache_request_headers();
    $response = array();
    $app = \Slim\Slim::getInstance();

    // Verifying Authorization Header
    if (isset($headers['Authorization'])) {
        $db = new DbHandler();

        // get the api key
        $api_key = $headers['Authorization'];
        // validating api key
        if (!$db->isValidApiKey($api_key)) {
            // api key is not present in users table
            $response["error"] = true;
            $response["message"] = "Access Denied. Invalid Api key";
            echoRespnse(401, $response);
            $app->stop();
        } else {
            global $user_id;
            // get user primary key id
            $user_id = $db->getUserId($api_key);
        }
    } else {
        // api key is missing in header
        $response["error"] = true;
        $response["message"] = "Api key is misssing";
        echoRespnse(400, $response);
        //echoRespnse(400, $headers);

        $app->stop();
    }
}

.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

Comment: Function apache-request-headers() if only available for Apache. Hostgrator is most likely using something else such as Nginx.
Comment: I get the same error on my local machine
Answer: Updating, this seems to take care of the the header problem
   if (!function_exists('apache_request_headers')) {

       function apache_request_headers() {
            foreach($_SERVER as $key=>$value) {
                if (substr($key,0,5)=="HTTP_") {
                    $key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
                    $out[$key]=$value;
                }else{
                    $out[$key]=$value;
        }
            }
            return $out;
        }
}

Answer: PHP 5.4.0 and later supports apache_request_headers(). But there are other solutions like the code below which comes from: http://php.net/manual/en/function.apache-request-headers.php
function apache_request_headers() {
  $arh = array();
  $rx_http = '/\AHTTP_/';
  foreach($_SERVER as $key => $val) {
    if( preg_match($rx_http, $key) ) {
      $arh_key = preg_replace($rx_http, '', $key);
      $rx_matches = array();
      // do some nasty string manipulations to restore the original letter case
      // this should work in most cases
      $rx_matches = explode('_', $arh_key);
      if( count($rx_matches) > 0 and strlen($arh_key) > 2 ) {
        foreach($rx_matches as $ak_key => $ak_val) $rx_matches[$ak_key] = ucfirst($ak_val);
        $arh_key = implode('-', $rx_matches);
      }
      $arh[$arh_key] = $val;
    }
  }
  return( $arh );
}


Required em checkbox

Question: Bom dia, estou aqui com uma dúvida relativamente a obrigar que a minha checkbox seja preenchida.

eu estou a utilizar o required e funciona em todos os campo menos na checkbox.
Codigo do campo nome (funcional) -
<input type="text" name="nome" placeholder="Nome..." required=" " >
Codigo da checkBox (nao funcional) -
 <input required=" " type="checkbox" name="termos" value="1"> Eu li e aceito os termos e condições
Comment: Eu não consegui reproduzir esse problema, o `required` funciona normalmente no checkbox, desde que qualquer outro `required` anterior tenha sido preenchido corretamente. Aqui tem uma print: https://i.ibb.co/F5WMK47/capturar2.png, usando o código que você mesmo indicou.
Comment: Por que usar `required=" "` e não apenas `required`?
Answer: Utilizando Javascript você consegue validar o checkbox. Aqui tem um exemplo:

<!doctype html>

 <title>Validar checkbox</title>

    <form>

<input id="termos" type="checkbox" required name="terms"> Eu aceito os termos e condições

<input type="submit" value="Enviar">

 </form>

Comment: resolvido, muito obrigado!

Required em checkbox


Matplotlib figure doesn't display correctly when re-opening

Question: I have an application that I am running from python shell. I have a main figure
fig, (plt1, plt2, plt3) = pl.subplots(3, 1)

I have the following functions:
def do_select_features(self, line):
    global mode, fig
    mode = 'features'
    fig.canvas.mpl_connect('key_press_event', on_key)
    plot_wnd()
    pl.ion()
    pl.show()

def plot_wnd():
    plt1.cla()
    plt2.cla()
    plt3.cla()
    plt1.grid(True)
    plt2.grid(True)
    plt3.grid(True)
    plt1.hold(True)
    plt1.plot(rdata)
    plt1.plot([rng_current[0], rng_current[0]], [min(rdata), max(rdata)], 'r', lw=1)
    plt1.plot([rng_current[1], rng_current[1]], [min(rdata), max(rdata)], 'r', lw=1)
    zdata = compression.fill_in(compression.zigzag(normalize(rdata), zigzag))
    plt2.plot(zdata[rng_current[0]:rng_current[1]], color='r')
    plt2.plot(normalize(rdata)[rng_current[0]:rng_current[1]], color='b')
    plt3.plot(diff(zdata, normalize(rdata))[rng_current[0]:rng_current[1]], color='r')
    pl.draw()

def on_key(event):
    global rng_current

    if event.key == 'right' and (rng_current[1] + stp) < len(rdata):
        rng_current[0] += stp
        rng_current[1] += stp
        plot_wnd()

    if event.key == 'enter':
        f = h5py.File(db, "a")
        pdo.insert_group(f, mode, compression.zigzag(normalize(rdata[rng_current[0]:rng_current[1]]), zigzag))
        f.close
        print "Subseries added to ", mode, " database"

    if event.key == 'left' and (rng_current[0] - stp) > 0:
        rng_current[0] -= stp
        rng_current[1] -= + stp
        plot_wnd()

    if event.key == 'escape':
        pl.close()

So when I am in the command line, I call select_features and it pulls up the figure and everything works great. I then manually exit the window with my mouse or hit ESC (which triggers pl.close(). I then want to be able to call select_features again, but it always brings up a similar window that is all grey. How do I fix this?
Answer: Try moving your fig creation inside the function.  When you close the window, you destroy the figure, so later calls to the function can't access that figure anymore.  You need to recreate a new figure every time you create a new window.
Comment: Thanks this worked...any idea how I can pass (plt1, plt2, plt3) as parameters to on_key in fig.canvas.mpl_connect('key_press_event', on_key)? that would reduce a great amount of redundancy


How to repeat the same number in a for loop like (7,7,6,6,5,5,4,4)?

Question: I was learning on jsdares and it told me to move a robot in a spiral like maze and the spacing between each turn would be (7,7,6,6,5,5,4,4.....) but every time it would drive it would hit the wall and print out (7,6,5,4...). Any help guys?
Also: i need it to stop at 0 which it would hit "goal block"
EDIT: I can't add arrays because it would be input back in to the robots forwardRight function.
function forwardRight(distance) {
  robot.drive(distance);
  robot.turnRight();
}

for (var k = 7; k <= 14; k++) {
  forwardRight(k);
}

Answer: I believe what you're trying to ask is that you want to repeat the given action for each k value?
If so, you can just call the function a second time in each loop:
function forwardRight(distance) {
  robot.drive(distance);
  robot.turnRight();
}

for (var k = 7; k <= 14; k++) {
  forwardRight(k);
  forwardRight(k);
}

Looking at the specific problem on jsdares, you have a few other problems in your code. Your for loop is incrementing k when it should be decrementing until 0:
function forwardRight(distance) {
  robot.drive(distance);
  robot.turnRight();
}

for (var k = 7; k > 0; k--) {
  forwardRight(k);
  forwardRight(k);
}

Testing this out in this very specific environment still causes the robot to run into the wall. The reason for this is because of the length of the first three drive calls should be 7. Your pattern of (7,7,6,6,5,5,4,4,...) just needs an additional forwardRight(7) prior to entering the loop:
function forwardRight(distance) {
  robot.drive(distance);
  robot.turnRight();
}

forwardRight(7);

for (var k = 7; k > 0; k--) {
  forwardRight(k);
  forwardRight(k);
}

Since it scores based on lines with actual content, the empty lines won't matter. This was also the shortest I could come up with that it would also accept as a solution.
Answer: Check this:

var inc = 1;
var array = [];
for (var i = 7; i <= 14; ) {
    if (inc == 0) {
        inc = 1;
    } else {
        i++;
        inc = 0;
    }
    array.push(i);
}
 console.log(array);
Comment: @Zoned _"your for loop only has 2 operators"_. This is so wrong that I just have to comment… His _head_ of the `for` loop has two parts called the _initialization_ and the _condition_. Operators are `=` and `<=`, which are in fact two operators, but the number of operators is completely irrelevant. The "missing" thing you're wondering about is called the _final expression_. This one is optional. By the way, the two other parts are _also_ optional. [Re-read how a `for` loop works](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for).
Comment: invalid syntax at the parentheses after the 14
Comment: your for loop only has 2 operators
Comment: also u cant do arrays


How can I execute Drush commands programmatically?

Question: I'm working on a Drupal 8 site, and part of the requirement is giving the client a page where they can click a button to do a particular task. I am able to do this using a Drush command from the command line, but I want to do it from a module.
I had seen code using either php_exec() or drush_invoke_process(). How can I use this function?
Comment: I had seen that but there the questioner had added a comment. " drush_invoke_process are undefined. Do i need to include any class or file in my custom drupal 8 module?" I am also getting same error..How can i define drush_invoke_process function?
Comment: Yes, I got the same error, it is because Drush doesn't not bootstrap
Comment: when using drush_invoke_process() it is showing me an error that function undefined. If I am using php_exec() my drush commands is not working. Eg:- exec('whoami') is working but exec("/vendor/bin/drush/drush status"); is not working.
Comment: `/vendor/bin/drush/drush` seems to be a bit of an odd location for Drush. `/vendor` in your machine's root, really? I bet you just referenced the wrong location.
Comment: I think this is probably too opinionated because I wuoldn't try to run drush commands in the UI personally. Instead I would probably abstract the code and make an interface to run via batchable or non-batchable actions.
Answer: From Drush 9 and higher drush commands are symfony services, so you can load them as other services though the services container. example:
if (PHP_SAPI === 'cli') {
  $command = \Drupal::service('migrate_tools.commands');
  $command->import('my_migration', ['update' => TRUE, 'sync' => TRUE]);
}

Comment: Be careful using this method because drush is assuming the context is CLI so depending on the command it could not work as expected when is run from UI, but you could use the approach for making drush commands calling another commands or other in other CLI contexts like cron execution.
Comment: I edited the snippet so the code won't fail if called from UI. It will be valid only if the implementation is aim to be called from CLI (i.e custom drush commands, cron jobs, etc)
Comment: I would like to add a note how to get result from command execution. Assume we are running next command: `$command = \Drupal::service('migrate_tools.commands');
    $result = $command->status('migrate_path_alias', ['field' => 'last_imported']);`, then to get some field you need `iterator_to_array($result)[0]['last_imported']`
Comment: you have to set `$command->setOutput()` and `$command->setLogger()`
Answer: Just start it from the other side. Imagine that every Drush command executes some PHP code. Then check the code of the Drush command you want to run. And then refactor it into the submit function of your button.
Doing it like suggested in your question doesn't seem to be very sustainable, taking into account that not every host has Drush installed. So you better make that functionality work independently from its environment.

Found one possible way: How to run Drupal console command from code? using Symfony's Process and flagged question as possible duplicate. And regarding drush_invoke_process(), as how I understand it so far, it seems to be callable only from within other Drush commands.

Next thing that came to my attention: In the comments to your question you are saying that you are trying to execute /vendor/bin/drush/drush status which would mean you have the vendor folder at the root of your machine. Which very probably is wrong and you just need to fix that path.
Comment: @RifasAli – Well, then just don't do it that way. Which command by the way?
Comment: when using drush_invoke_process() it is showing me an error that function undefined. If I am using php_exec() my drush commands is not working. Eg:- exec('whoami') is working but exec("/vendor/bin/drush/drush status"); is not working.
Comment: Actually I am trying to do drush commands from custom module. Actually the use case is I want to create a file upload section with a button. And while clicking this button I want the migration import command to be done. Write now client is using drush command from CLI to do mi import. We want to provide a ui for the user to achieve this , So as a first step I am trying to run any drush commands using my custom module.Am I missing any includes/ use?
Answer: On Drupal 9.5.11, I wanted to call the command from a contrib module (search_api) to get more control over it.
This is how I did :
$self = Drush::aliasManager()->getSelf();
$finished = FALSE;
// These are the options of the drush command
$options = ['limit' => '100', 'batch-size' => '50'];
while (!$finished) {
  // You can specify an index id in the 3rd argument, ex : ['index']
  $process = $this->processManager()->drush($self, 'search-api:index', [], $options);
  // We capture the output to print it here and check if it finished.
  $process->run($process->showRealtime()->hideStdout());
  if (!$process->isSuccessful() || empty($process->getOutput())) {
    $finished = TRUE;
  }
  else {
    // \Drupal::logger('YourModule')->notice($process->getOutput(), []);
  }
}

You can check the command drush search-api:index to identify the argument and the options of it, and how there are dealt with in this code.
Answer: run updb from other drush command class
    public function updateDB() {
        $updb = new \Drush\Commands\core\UpdateDBCommands();
        $updb->setProcessManager($this->processManager());
        $updb->setConfig($this->getConfig());
        $updb->setLogger($this->logger());
        $updb->setSiteAliasManager($this->siteAliasManager());
        $updb->input()->setOption('yes', true);
        $updb->setOutput($this->output());
        $updb->updatedb(['cache-clear' => true, 'entity-updates' => false, 'post-updates' => true]);

    }

Comment: This doesn't really make much sense to me, perhaps you can elaborate how the OP can apply this to their scenario?
Comment: he can apply exaclty the same as on example above: take the class which which implements the command he desires, set the process manager, config, logger channel, i/o stream and data to avoid waiting for user input and run the command class method to do job. In example above $this is a custom drupal service.


Yocto Image build fails because "nothing RPROVIDES libavresample"

Question: I am trying to build a custom Yocto image based on fsl-image-gui for my iMX6 based board SECO A62J. I use Hob to do this.
After having selected my machine, my layers and my image, I custom my packages list by adding chromium. This automatically selects libexif and libav which are Chromium dependencies. The build of the packages is successful
The last step is the build of the image itself, and this is where my problem appears. I select the packages I want to include in my image, including Chromium, libexif and libav (and its dependencies).
And I got those errors :

Nothing RPROVIDES 'libavresample' (but
  /home/adrien/fsl-release-bsp/build_anna/recipes/images/fsl-image-gui-edited-20170131-144607.bb RDEPENDS on or otherwise requires it)

and

Required build target 'fsl-image-gui-edited-20170131-144607' has no
  buildable providers. Missing or unbuildable dependency chain was:
  ['fsl-image-gui-edited-20170131-144607', 'libavresample']

However, the library libavresample.so is built successfully and can be found  under my build directory in sysroots/"machine_name"/usr/lib/
Why Yocto can't find and include this library in my image, What am I missing here?
Comment: No recipe in your yocto build produces a package called "libavresample". Are you sure you need it? Chromium probably uses its own copy anyway.
Comment: At building packages step, libav is automatically selected as Chromium dependency. That's why I thought I needed it, i'll give it a try without including it in my image.
I thought libavresample was built with libav, if not I have no idea where the libavresample.so in my build directory come from. At building image step, when I select libav, its dependencies are also automatically selected like libavresample, libavcodec etc
Comment: It's complicated: Depending on yocto version libavresample _could_ come from libav or ffmpeg (but is not built by default AFAIR), but it may also be contained in e.g. chromium. When you say you "select libav" what exactly do you mean? None of the libav recipes I've seen even build avresample by default, let alone runtime depend on it... Linking to the recipes might help.
Comment: The reason I'm asking about how you select libav is that you say you get libavresample selected automatically but according to the log your image directly RDEPENDS on libavresample -- there does not seem to be any dependencies in between.
Comment: "select libav" means I use Hob so I have a list of built packages I can include into my image by clicking on them, and their dependencies are automatically selected. With libav, it selects other libraries automatically like libavresample
You're right it makes my image depending on libavresample, I don't actually want this. I'll check if Chromium has its own copy. Maybe I won't need to include libav explicitly.
What leaded me to this is that when I selected Chromium to be built, libav was automatically selected and built too. That's why I thought I needed to include libav  explicitly.
Answer: In your local.conf :
<code>LICENSE_FLAGS_WHITELIST += " commercial"
</code>
Comment: Variable LICENSE_FLAGS_WHITELIST has been renamed to LICENSE_FLAGS_ACCEPTED


Is there any shortcut/command available to skip karma tests? like -DskipTests for Maven

Question: I have created Maven Web application and I generally use
mvn clean install

So it execute npm install command as its one of the execution goal and then it run karma tests
So my question is, is there any shortcut or command available to skip karma tests conditionally?
Like we have -DskipTests for Maven project to skip tests.
Off course we can simply remove the npm run test from the package.json file but I want to skip tests using command.
pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>com.github.eirslett</groupId>
            <artifactId>frontend-maven-plugin</artifactId>
            <version>1.5</version>
            <executions>
                <execution>
                    <id>npm install</id>
                    <goals>
                        <goal>npm</goal>
                    </goals>
                    <configuration>
                        <workingDirectory>web/app</workingDirectory>
                        <installDirectory>build</installDirectory>
                        <arguments>install
                            --registry=${npm.registry}
                        </arguments>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Answer: Since I am using the frontend-maven-plugin I had to add below execution to plugin.
                <executions>
                    <execution>
                        <id>javascript tests</id>
                        <goals>
                            <goal>karma</goal>
                        </goals>
                        <phase>test</phase>
                    </execution>
                </executions>

After that, just using -DskipTest build argument able to skip karma tests.
mvn clean install -DskipTests
Answer:
You can define a system property -Dmaven.test.skip=true to skip the unit test.
mvn package -Dmaven.test.skip=true

Define properties in pom.xml
<properties>
    <maven.test.skip>true</maven.test.skip>
</properties>

Use -DskipTests in surefire plugin
mvn package -DskipTests

Define surefire plugin in pox.xml
<plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-surefire-plugin</artifactId>
 <version>3.0.0-M1</version>
 <configuration>
     <skipTests>true</skipTests>
 </configuration>
</plugin>

Comment: The above command will skip the JUnit tests and not the karma tests. I want to skip karma tests using the command.
Answer: use
mvn clean install -DskipTests

-DskipTests will skip the Karma tests. Please refer to the following snippet available at https://github.com/eirslett/frontend-maven-plugin
"Skipping tests: If you run maven with the -DskipTests flag, karma tests will be skipped."
So, Front end test cases are getting executed under "frontend-maven-plugin" which seems to recognize only -DskipTests to skip test cases execution unlike "maven-surefire-plugin" which recognizes both "-DskipTests" as well as "-Dmaven.test.skip=true" command parameters. So, if we use -DskipTests rather -Dmaven.test.skip=true command parameters, both backend as well as front end test cases get skipped.
This is what has been tested locally using -DskipTests
Skip FE Tests
Comment: The above command will skip the JUnit tests and not the karma tests. I want to skip karma tests using the command.
Comment: @GaneshThorat I've edited my response to be more elaborative. Please refer that,


Proguard error preventing APK from building with "returned error with error code 1"

Question: The issue is when trying to build a signed APK, it errors at the last step with this:

[2013-06-20 11:39:34 - MyApp] Proguard returned with error code 1. See console
[2013-06-20 11:39:34 - MyApp] Unable to access jarfile /Users/rob/Android

I am using the latest Eclipse ADT v22.0.1-685705 (just installed this morning) and it seems like this issue has been around for at least a month now according to Google.
Answer: In order to fix this,
Change:
java -jar $PROGUARD_HOME/lib/proguard.jar "$@"

To:
java -jar "$PROGUARD_HOME/lib/proguard.jar" "$@"

in this file <Android SDK Location Here>/sdk/tools/proguard/bin/proguard.sh
Credit here


Why does R have a different definition on convolution?

Question: I found convolution in R works differently from Python. In Python, it will flip the input and run the convolution.
In the R documentation, it says

Note that the usual definition of convolution of two sequences x and y is given by convolve(x, rev(y), type = "o").

Is there any reason behind R's different approach? Do people in the statistics community use convolution differently than do those in the signal processing community?
An example in R:
x = c(c(1,2,3,4),rep(0,4))
y = c(c(5,6,7,8),rep(0,4))
convolve(x,y)

# will return 70 56 39 20  0  8 23 44

But in python
x = np.hstack([np.array([1,2,3,4]), np.zeros(4)])
y = np.hstack([np.array([5,6,7,8]), np.zeros(4)])

np.convolve(x, y)

# will return 5., 16., 34., 60., 61., 52., 32.

Comment: I vote to reopen this question. This question is not opinion based like explaining which is better. It does to me more like a question about *how/why* these differences occur. Why are there multiple views on convolution, why is there a difference?
Comment: I would vote to open as well. This is fact, not opinion. The awareness of difference in different implementation would be helpful. See this question https://stackoverflow.com/questions/49447270/pytorch-forward-pass-using-weights-trained-by-theano
Comment: It is a design decision of the authors of the code. The "why" question is about their motivation, what's subjective.
Comment: I haven't check the details of the functions, but it is likely due to the implementation basing on cross correlation or convolution. I know that it could be different in deep learning frameworks.
Comment: I'd say it's a convention, so as many "why" questions, something subjective, but would not oppose keeping it if people disagree.
Comment: @Tim I do not agree. there are many "facts" behind the decision. I am asking those facts.
Comment: Apperently R's implementation of convolution is unusual. The documentation says: > Note that the usual definition of convolution of two sequences `x`and `y` is given by `convolve(x, rev(y), type = "o")`.
Comment: @SextusEmpiricus I am padding zero, so open or circular are the same
Comment: I am just quoting the documentation.
Comment: @SextusEmpiricus sorry haven't read it carefully, it did indicate it is "unusal"
Comment: Of course this question will just be a matter about simple freedom in definitions/conventions and convolution allows two definitions. But it may be interesting to see why and where the unusual definition (by that I mean the definition used by R) pops up.
Answer: Relation with Fourier transforms
The convolve function in R is using a Fourier transform to compute the convolution (that's a potential source for the difference, although I am not sure, and do not know the details).
$$ x * y = \mathcal{F}^{-1}\{\mathcal{F}\{x\} \cdot \mathcal{F}\{y\}\}$$
But more specifically it is using the complex conjugate, and that is how the operation turns the variable backwards.
x = c(c(1,2,3,4),rep(0,4))
y = c(c(5,6,7,8),rep(0,4))
zx = fft(c(x))
zy = fft(c(y))
round(Re(fft(zx*Conj(zy), inverse = TRUE))/8)
round(Re(fft(zx*zy, inverse = TRUE))/8)

Which returns
[1] 70 56 39 20  0  8 23 44
[1]  5 16 34 60 61 52 32  0

I am not sure why the conjugate is used. This operation with the conjugate relates to convolution according to
$$\mathcal{F}\{x(t) * y^*(-t)\} = \mathcal{F}\{x(t)\}\cdot\left(\mathcal{F}\{y(t)\}\right)^*$$
and if $y$ is real then $y = y^*$. And it also relates a bit to cross-correlation. In which case
$$\mathcal{F}\{x(t) * y(-t)\} = \mathcal{F}\{x(t)\}\cdot \left(\mathcal{F}\{y(t)\}\right)^*$$
Note that R's convolve function is regulating this with a parameter conj which is true by default and setting it to false gives the 'normal' convolution.
convolve(x,y,conj=FALSE)

Indirectly the question could be seen as: "why does R convolve use conj = TRUE as the default option?"
Potential (historic) reason for the difference
Why the standard R function for convolution does it in a reverse way, or how this historically came to be, I do not know. But possibly the origin might stem from the book Time Series: Data Analysis and Theory by David R. Brillinger (1981), which is referenced in the R documentation. In the book the convolution occurs as following:

Suppose the values $X(t)$ and $Y(t)$, $t=0,\dots,T-1$, are available. We will sometimes require the convolution $$\sum_{0\leq {{t}\atop{t+u}} \leq T-1} X(t+u)Y(t) \quad u = 0, \pm 1, \dots \quad (3.6.1)$$

The term convolution is used in a more general sense, and later in the text they refer to a specific case of this type of convolution

One case in which one might require the convolution (3.6.1) is in the estimation of the moment function $m_{12}(u) = E[X_1(t+u)X_2(t)]$...

Also in early descriptions of the use of the fast Fourier transform algorithm (a reference occuring in Brillinger) do they use 'convolution' in a broader sense. In Fast Fourier Transforms: for fun and profit AFIPS '66 (Fall): Proceedings of the November 7-10, 1966, fall joint computer conference, Gentleman and Sande write

... To date, the most important uses of the fast Fourier transform have been in connection with the convolution theorem of Table I. Some uses of numerical convolutions are the following:
Auto- and Cross-Covariances:...
...
...The first major use of the convolution theorem, by Sande, was to compute the auto-covariance...

So it seems that, at least in some circles, convolution has a more general meaning and possibly the writers of the R function found the cross covariance most useful to be the standard (it is mentioned to be a major use).

Differences in conventions also (already) occurs for Fourier transformation
As whuber noted in the comments, Fourier transformation, from which convolution can be derived, is not uniquely defined. There are several conventions for $a$ and $b$ in the below defined Fourier transformation and reverse Fourier transformation formulae:
$$\begin{array}{}
\mathcal{F}(x) = \sqrt{\frac{|b|}{(2\pi)^{1-a}}} \int_{-\infty}^{\infty} f(t) e^{ibxt} \text{d}t \\
f(t) = \sqrt{\frac{|b|}{(2\pi)^{1+a}}} \int_{-\infty}^{\infty} \mathcal{F}(x) e^{-ibxt} \text{d}x
\end{array}$$
and different fields use different parameters $a$ and $b$. The scaling parameter $a$ does not relate much to the 'convolution' operation, but the direction/sign of $b$ may be seen as related.
Personally I am still wondering whether this relationship with Fourier transforms (and its ambiguous conventions) is the reason why the R function is different.
We can use Fourier transforms to compute a convolution, but should that be the reason for the diversity in conventions of convolutions?
(note: In the case of Fourier transforms it may be useful to have different conventions, depending on the field. Because transforms of particular functions, that are more/less relevant depending on the field, might have some simple form or not depending on the convention.)
Comment: I agree, writing '*the* Fourier transform' was sloppy. I've corrected this now. Do you believe that ambiguity in parameters in the Fourier transform is reason for the ambiguity in the direction of convolution (because convolution can be seen as derived from FT)? Historically convolution predates the Fourier transform and deriving convolution by means of FT is only an afterthought to make the computations faster. It's probably how it got into the R function, and why I posted this answer, but to me it does not make much sense yet. It is the first time that I see convolution done in this way.
Comment: The use of "the" Fourier transform masks the fact that there is no universal convention for Fourier transforms--and this is a big part of the reason why software implementations of the FFT and its related operations, especially convolution, differ.  See https://mathworld.wolfram.com/FourierTransform.html.
Comment: The absence of a convention for the FT is only one part of it.  I suspect the ambiguity arises for the usual reasons: different communities have different uses for convolution and different conventions and so the software will differ depending on its target audience.
Comment: All this business about the FT is beside the point; convolution and related operations are defined apart from FT, and any relation between them is a consequence to be derived. The relevant part of this answer is the definition from a book about time series which has a definition of convolution which would be called correlation in every other book I've ever seen. The only way to answer OP's question is to go back and find out why convolution was implemented that way in S or S+ from which R got it.
Comment: @RobertDodier the path to the reasoning for convolution in R being different passes by the use of the FFT algorithm. That is where it's use of cross correlation in place of convolution may stem from (and at least, something interesting as a sidenote is to know that, under the hood, in the code, there is no explicit reversal of the variable but it is done indirectly in the frequency domain where it is the conjugation that switches the convolution into cross correlation). The articles describing FFT as a way to perform convolution discussed convolution in a broader sense.


How can i use OKTA API to create/modify attributes of a public application like O365

Question: I have used Postman per the OKTA developer docs to create a new SAML 2.0 app and that works fine. However, I wanted to know how I can modify my code to edit/or create an instance of a published app like Office 365. I posted my question on OKTA forums as well but no response yet. Thanks! - JC
https://devforum.okta.com/t/api-for-public-apps/6151
I have created a custom app using Postman which works fine.
Answer: As of this writing, unique application attributes from the Okta Integration Network (OIN) are not exposed to the Okta Management API, based on the app model:
https://developer.okta.com/docs/reference/api/apps/#models.
I suspect this is because each template in the OIN is unique, with its own set of attributes, and because of this it may be tricky to deploy an API intuitive enough to account for this uniqueness.
If you are looking to manage a lot of instances of the same application type, it may be worth looking into creating a default application and creating the connection settings from scratch, instead of using templates from the OIN. Although this may not be an option depending on the app, and if provisioning is involved.
Comment: Understood.  Thank you.


Regex to find string containing special characters in text

Question: I'm trying to formulate a regular expression that will allow me to find a string within a piece of text, if the string exists on its own i.e. not within another word (but surrounded by special characters is ok).
/\bword\b/i

The above regex works fine, and finds "word" in the text. The problem comes when the word I want to find is something like "c++". In this case it matches on any occurrence of the "c" character on it's own. I've tried escaping the "+" characters but it doesn't make any difference. I'm assuming because "+" is a non-word character, I'm possibly going down the wrong route and using word boundaries is not what I should be doing.
So I guess the question is, how can I use a regular expression to find a string in a piece of text, on it's own, and regardless of whether the string is alphanumeric or contains special characters. So in the following piece of text it should match on the 3 occurences of "c++":
c++
(c++)
perl/c++/assembly

But it should not match on the following:
maniac++
c++abc

This is intended so that my script can tell if a specific skill exists within a user's CV/resume. I'm using this with PHP's preg_match_all() function.
I've done a lot of searching but can't come up with a solution, hopefully someone with good regex knowledge can help.
Answer: Try this:
/(?<!\w)(c\+\+)(?!\w)/

The (?<!\w) is a negative lookbehind clause, meaning that a word character should not immediately precede your pattern.  The (?!\w) part is negative lookahead, meaning that a word character should not immediately follow.
Hope this helps!
Comment: [:-p](http://sandbox.onlinephpfunctions.com/code/df91dec2fa93f691b683af93bb6973a64d8cf38e)
Comment: Btw, if you're new to developing regexs, you might be interested to know that they can be tested quickly in command line perl.  The following linux command shows which of your example strings are matched: `echo -e 'c++\n(c++)\nperl/c++/assembly\nmaniac++\nc++abc' | perl -lane '/^(.*(?<!\w)(c\+\+)(?!\w).*)$/ && print $1'`  Just don't try reading it out loud without taking a deep breath ;-)


How can I change the name of a Notebook or Section?

Question: Currently it's possible to change a Page's name using the PATCH Page API.
Anyone knows how to change the name of a Section or Notebook using the REST API?
Thanks.
Answer: REST API as of 10/22/15 don't support renaming of sections/notebooks. Only renaming page title is supported. But we'll take the feedback and put in in our backlog.
Thanks


Arithmetic Error in Calculation of the Limit of a Given Function

Question: I consider a function $f(x)$ which is equal to $\dfrac{\frac{3}{x}-\frac{1}{2}}{x-6}$
While trying to evaluate the $\lim_{x \to 6} f(x)$
It is true that $\dfrac{\frac{3}{x}-\frac{1}{2}}{x-6} = \dfrac{\frac{3}{x}}{x-6}-\dfrac{\frac{1}{2}}{x-6}$
It is also true that $\dfrac{a}{\frac{b}{c}} = \dfrac{a\cdot c}{b}$
I apply this property to $f(x)$ and come to the conclusion that $\dfrac{\frac{3}{x}-\frac{1}{2}}{x-6} = \dfrac{\frac{3}{x}}{x-6}-\dfrac{\frac{1}{2}}{x-6} = \dfrac{3x-18}{x}-\dfrac{x-6}{2}$, which is of course incorrect.
Additionally, I believe I'm taking an improper approach to solving this limit.
Comment: $\frac{\frac12}{x-6} \neq \frac{x-6}{2}$ - that's the only error
Comment: @VolodymyrFomenko Sure--but why?
Answer: it is equivalent to $\frac{\frac{6-x}{2x}}{x-6}=-\frac{x-6}{2x(x-6}$
since $\frac{3}{x}-\frac{1}{2}=\frac{6}{2x}-\frac{x}{2x}$
Comment: ... care to elaborate on why?
Answer: Note: $$\frac a{\frac bc} = \frac{ac}b$$
You arrive at only $ac$.
Also, $$\dfrac{\frac ab}{c} = \frac{a}{bc}$$
So $$ \dfrac{\frac{3}{x}-\frac{1}{2}}{x-6} = \dfrac{\frac{3}{x}}{x-6}-\dfrac{\frac{1}{2}}{x-6} = \frac{3}{x(x-6)} - \frac 1{2(x-6)} = \frac{2\cdot 3}{2x(x-6)}-\frac{x}{2x(x-6)} = \dfrac{6-x}{2x(x-6)}$$
$$= \frac{-(x-6)}{2x(x-6)} = \frac{-1}{2x}$$
Comment: Right. I fixed that. I was applying that in practice, but I wrote it down wrong. That statement is true and correct, no? Why then am I arriving at an incorrect equality?
Comment: I don't quite understand why that is. What am I missing here? Isn't $\dfrac{\dfrac{a}{b}}{c} = a \div b \div c = \dfrac{a}{\dfrac{b}{c}}$
Comment: No: Multiply by $1 = \frac bb$ $$\dfrac{\frac ab}{c}\cdot \frac bb = \frac a{bc}$$
Comment: I'm really not certain why this is so incredibly outlandish and difficult for me to grasp. Perhaps I have a weak intuition of the the property in the first place. It is true that $(a \cdot b^{-1})c^{-1} = \dfrac{a}{b \cdot c}$, and $a \cdot (b \cdot c^{-1})^{-1} = \dfrac{\dfrac{a}{c}}{b}$ but $a \cdot b^{-1})^{-1} \neq a \cdot (b \cdot c^{-1})^{-1}$
Comment: $$(ab^{-1})^{-1} = \left(\frac ab\right)^{-1} = \frac{a^{-1}}{b^{-1}}= \frac ba$$
Comment: I made a typo. Retyping.
Comment: $$a(bc^{-1})^{-1} = a{b^{-1}}c = \frac ab \cdot c = \frac {ac}{b}$$
Comment: Ok, it turns out I have no idea what I was talking about. So, even I'm at a loss. I think I just forgot how to do division for some reason.
Answer: $$
\frac 3 x\cdot 2x = 6\text{ since $x$ cancels, and }\frac 1 2\cdot 2x = x\text{ since $2$ cancels.}
$$
Therefore
$$
\frac{\frac{3}{x}-\frac{1}{2}}{x-6}=\frac{\left(\frac{3}{x}-\frac{1}{2}\right)2x}{(x-6)2x} = \frac{6-x}{(x-6)2x} = \frac{-1(x-6)}{(x-6)2x} = \frac{-1}{2x}
$$


How to check what return functions and correctly calculate chars

Question: Welcome. I have two problems. Firstly - function size bool (const char * pass) to check whether the amount of the chars inside of string is at least 8, but there is something wrong. Its always showing that there is minimum 8 chars, even is string contain only 3 chars.
My job is to create several small functions for checking the correctness of the entered string of chars. Can You help you with this one? If all small functions inside of bool check(...) return true i need to write in the console "STRING IS OKAY".
I will be grateful for any suggestions.
    #include <iostream>
    #include <cctype>
    using namespace std;

    //Check the amount of chars
    bool size (const char* pass){
        if(sizeof(pass) > 7)
                        return true;
    }

    //Checks if the ASCII are located between 32 to 126
    bool isPrint (const char* pass){
        for(int x=0; x <= sizeof(pass); x++){
            if(isprint(pass[x]))
                return true;
        }
    }

    //Check the amount of numbers
    bool isNum (const char* pass){
        for(int x=0; x <= sizeof(pass); x++){
            if(isdigit(pass[x]))
                return true;
        }
    }

    //Check the amount of Upper letters
    bool isUpperLetter (const char* pass){
        for(int x=0; x <= sizeof(pass); x++){
            if(isupper(pass[x]))
                return true;
        }
    }

    //Check the amount of lower letters
    bool isLowerLetter (const char* pass){
        for(int x=0; x <= sizeof(pass); x++){
            if(islower(pass[x]))
                return true;
        }
    }

    //Check the amount of Punctuation Marks
    bool isPunctMark (const char* pass){
        for(int x=0; x <= sizeof(pass); x++){
            if(ispunct(pass[x])){
                return true;
            }
        }
    }

    //All small moduls together
    bool check (const char* pass){
        size(pass);
        isPrint(pass);
        isNum(pass);
        isUpperLetter(pass);
        isLowerLetter(pass);
        isPunctMark(pass);
    }

    int main() {
        char x;
        cout << "Enter the string of characters" << endl;
        cin >> x;
        const char *password = &x;
        check(password);
    }

Comment: You are getting the size of a pointer, which is likely `8` on your system. You probably want [`strlen`](http://en.cppreference.com/w/cpp/string/byte/strlen), or better yet, [`std::string`](http://en.cppreference.com/w/cpp/string/basic_string).
Comment: Your string of characters is read into a `char` which is fine as long as you expect only a single character. You can`t use `strlen` on a single `char` because that one is not `\0` terminated. Use `std::string`.
Comment: I am not sure why you got downvoted.... The question conforms to the site rules. You posted code, have had a bash at the problem... Maybe those mean enough to downvote could comment and explain.
Answer: sizeof(pass) returns the size of the pointer. Which is implementation specific, and if your function is always returning true, we can guess that sizeof(char*) is 8, implying you have a 64-bit system.
On many other systems, it will return 4, or may even return 2 or 1, dependant on the architecture.
You probably want to check the length of the string the pointer is pointing to like so:
int len=strlen(pass);
if(len>=8)   //Check for >=8 is clearer than >7)
{
   return true;
}

You could also iterate over the string and check for null. But why bother when there is a nice std library routine that does the job.
to run all checks, do something like
bool isValid(const char* const pass)
{
     if(!isPrint(pass))
     {

         return false;
     }
     if (!isNum(pass))
     {
         return false;
      }
     //etc
 }

You could also have a big long
if(isPrint(pass)&&isNum(pass) .....)
{
    return true;
}

but that would be messier, and harder to debug.
Comment: Early morning brain fart. Corrected. (Considers claiming he is working on a 8 bit micro. Which would be a lie)
Comment: Ok, thanks! And what about the second question? how to check whether all the functions return true?
Comment: @mjs LOL, fair enough.
Comment: wrap them in another isValid func, and call one by one. As soon as one returns `false`, just return false from `isValid()` I have expanded my answer
Comment: @mjs I know I'm grumpy, but you can also look at the place where the get string from user and writes it to a variable password in the main () part.
Comment: @DanielZawadzki Not sure i understand your comment. In any case, there is no main() function in your posted code. It might be best to create a second question anyway....
Answer: sizeof gives you the size of the type of the object passed to it. It is evaluated strictly at compile time. You are passing it a const char *, which is 8 on 64 bit systems.
To get the length of a C-style string, you can use the C function strlen, in the header <cstring>.
That said, I would recommend not doing this. I would recommend moving away from C strings to C++ std::strings, because they are much easier to use correctly.
Now as it is, you are very much using C strings INcorrectly!
int main() {
    char x;
    cout << "Enter the string of characters" << endl;
    cin >> x;
    const char *password = &x;
    check(password);
}

You read a single char (x), then take its address and treat this as a C string. Now there are two significant problems here.
First, you probably meant to read more than one character.
Second, you will hit undefined behaviour, and your computer may well blow up, because C strings are supposed to be a pointer to a NUL-terminated array of char. Any functions that expect a C string will loop through look for an ending '\0', which x does not have, since it is not even an array in the first place.
So, if you use std::string from the <string> header, you can have much safer code, without all this faffing with pointers, NUL-terminators, and such.
(untested)
// one of your functions for example
bool isUpperLetter (const std::string& s){
    for(int x=0; x < s.size(); ++x){ // Use <, not <=. C++ uses 0-indexing.
        if(isupper(s[x]))
            return true;
    }
    return false; // you forgot this!
}

int main() {
    std::string s;
    std::cout << "Enter a string:\n";
    std::cin >> s;

    isUpperLetter(s);
}

By the way, this won't work if your input string contains spaces, but one thing at a time!
(Next steps if you learn fast: Read up on std::getline and the <algorithm> header. std::count_if looks very relevant.)
And while we're at it, kill bad habits early, and read up on why you should avoid using namespace std; and std::endl.
EDIT
From your comment, you are stuck with the signature bool check(const char*), so I guess you are supposed to be learning about how to work with C strings. Let's for the moment assume your instructors know what they are doing.
Then the normal way to loop through a C string is with a pointer, checking for '\0'. So for instance, to count the number of uppercase letters (and really, you don't write it this way for real code. Or at least, if you tried to on a project I was working on I would strongly suggest you fix it):
int countUppercase (const char* c)
{
    if(NULL==c) return 0;

    int count = 0;
    for ( ; '\0' != *c ; ++c ) // loop while not found the NUL
    {
        if (isupper(*c))
            ++count;
    }

    return count;
}

I still strongly recommend reading into a std::string if you can get away with it. If not, you're next best bet is probably std::istream::getline.
Comment: Thanks for the reply. I have already solved the problem, but you get interested me enough that I think Im gonna rewrite this program :).
Comment: @DanielZawadzki Please do! Don't take it personally, but it is **bad**. Hopefully I've managed to address the most important points. The absolutely fundamental thing here is to use `std::string`. May I ask where you are learning from? You may consider getting a [good book](http://stackoverflow.com/q/388242/1171191).
Comment: I had to use the structure bool check (const char* pass), becouse its work to my school, but i want to rewrite it for myself also. :).
Comment: @DanielZawadzki I've added an example of the proper way to loop through all characters in a `C` string.
Answer: You are checking the sizeof(pass), which is size of const char*. You should iterate over the array and chack for str[i]=='\0' instead.
EDIT:
As suggested, you can also use strlen() function instead.
Comment: Why do it yourself when you could use [`strlen`](http://en.cppreference.com/w/cpp/string/byte/strlen)? (which is most likely very heavily optimized, but it's more about not rewriting it yourself.)
Answer: As there was already mentioned you use sizeof pointer in loops of your functions instead of the actual length of the passed string. Moreover sometimes comments before functions do not correspond what they do or have to do. For example
//Check the amount of numbers
bool isNum (const char* pass){
    for(int x=0; x <= sizeof(pass); x++){
        if(isdigit(pass[x]))
            return true;
    }
}

In the comment there is written "check the amount of numbers". I think you should return number of digits in the given string.
So I would rewrite the function the following way
//Check the amount of numbers
size_t DigitCount ( const char* pass )
{
    size_t count = 0;

    for ( ; *pass; ++pass )
    {
        if ( isdigit( *pass ) ) ++count;
    }

    return count;
}


How to print and save the result to a file at the same time?

Question: I'm trying to print on Windows Server 2012. It works fine, but I'd want to generate an output file (some kind of .PRN) in order to save the last print job so it can be printed again later.
Enabling a printer pool with two printer queues doesn't work, because it will choose the fastest one. Moreover, I wouldn't want to use a third party software, if possible.
Any ideas? Help will be apreciated.
Regards.
Comment: We've finally used a Powershell script to solve this out. Thanks everyone for your answers!
Answer: In the Properties pages of the printer, on the Advanced tab, check the "keep printed documents" checkbox.
Comment: Hello,

Thanks for answering, @joeqwerty. We've already thought about that solution, **but it isn't possible because every print job generates a 3 MB file**. We have twenty users, and they can print three or four jobs a minute.

Regards.
Answer: You are not looking for a third party software, but because there has not been an approved answer I can maybe suggest using a commercial solution.
This video shows you how to print a document and also archive and email it. Maybe you can archive it as PDF file on another (network) location or FTP so you can print the PDF files again when necessarry?
video tutorial


What is the reason for endowing the positive semidefinite cone with the Affine Invariant Riemannian Metric instead of a Euclidean metric?

Question: I came across this post Distances defined in manifold of symmetric positive definite matrices because I had the same questions. I did not understand the answers provided, so I wanted to try to answer it myself. Originally, I posted my justifications and intuitions as an answer, but given I do not have a background in differential geometry and was unsure about my answer, I thought it would be better to post it as a question. The two main points I was trying to address were

"I always pictured it as a "curved sheet" like the shell of a sphere but not the sphere itself; therefore, the idea of calling the PSD cone a manifold was confusing"

The main question being asked: "if I understand correctly, SPD matrices lie inside a convex set i.e. linear combinations of SPD matrices will be SPD. Intuitively, I don't see the need of defining a distance that goes along the curvature of SPD matrices since the set is dense"

Do these justifications/intuitions correctly address those questions:

"I always pictured it as a "curved sheet" like the shell of a sphere but not the sphere itself; therefore, the idea of calling the PSD cone a manifold was confusing"

Although it is easier to imagine a manifold as a hyper-surface, a manifold does not need to be in some ambient space of higher dimension to be a manifold. So take the PSD cone formed by the set of the set of 2x2 PSD matrices. This would be a 3 manifold since locally it is diffeomorphic to $\mathbb{R}^3$. Whether that cone is in $\mathbb{R}^3$, $\mathbb{R}^4$, or $\mathbb{R}^n$ does not make a difference. i.e. Manifolds are independent of the ambient space they live/are portrayed in..

The main question being asked: "if I understand correctly, SPD matrices lie inside a convex set i.e. linear combinations of SPD matrices will be SPD. Intuitively, I don't see the need of defining a distance that goes along the curvature of SPD matrices since the set is dense"

Two pictures that help me conceptualize this idea.

Picture 2 is from Riemannian geometry for EEG-based brain-computer
interfaces; a primer and a review. This shows that the boundary is defined by the set of PSD matrices with determinant of 0 and that the interior of the cone contains positive definite matrices with a non zero determinant.
Picture 3 is from A pictorial representation of the positive semidefinite cone and is how I am viewing the PSD cone in practice. I am not sure if this is correct, but my interpretation is that the PSD cone can be viewed as a solid cone made up of infinitely many layers (level-sets) of other cones, where each layer of cone has a certain determinant (however, in this picture each layer of this cone looks like it includes the origin, but in the situation I am describing only the boundary when determinant is 0 would the origin be included). Every matrix on the outside boundary has a determinant of 0, every matrix on the next layer which is in the interior of the boundary has a determinant slightly greater than 0, and so on. As I explain below, I believe in practice, a set of sample covariance matrices usually come from one layer/a group of layers near the boundary. This idea is touched on in these posts Is the set of symmetric positive semi-definite matrices a smooth manifold with boundary and Positive semidefinite cone is generated by all rank-1 matrices..
I think theoretically if your sample covariance matrices were positive definite and had varying determinants than using Euclidean distance to measure the distance would make sense, since the PSD cone is an open convex set and has a non-empty interior with positive volume. However, in practice the sample covariance matrices are usually ill conditioned (eigenvalues lower in the spectrum are closer to zero) due to redundancies in the data. The way I see it is that this means two things. One, the data we are modeling is really close to the surface of the psd cone (at the surface the determinant is 0 and ill conditioned matrices have determinants approaching 0) which means they resemble something closer to the subset of PSD matrices which have determinant equal to 0. Two, the covariance matrices we are modeling have similar determinants which implies they live on some curved sub-manifold/layer of the psd cone. For these reasons we should use the Affine Invariant Riemannian Metric . Since the set of positive semi definite and positive definite matrices is convex, as was mentioned in the original post, the straight line distance will always be further in the interior of the cone. I believe the further you move into the interior of the cone, the higher your determinant is. Assuming your data all has similar determinants, taking the arithmetic mean would cause you to end up with an average matrix that has a larger determinant than the your sample covariance matrices. By using the Affine Invariant Riemannian Metric we will avoid doing things like considering covariance matrices of higher determinants because we are following a curved path. This idea of increasing determinant and determinant identity is discussed in footnote 13 of Riemannian geometry for EEG-based brain-computer
interfaces; a primer and a review and Figure 4.1 in Geometric Means In A Novel Vector Space Structure On Symmetric Positive-Definite Matrices. This paper as well discusses and references some good sources that go over some of the difference between different means/metrics on the PSD cone Riemannian Metric and Geometric Mean for Positive Semidefinite Matrices of Fixed Rank.
I visualized this idea with real data below in image 10. Here I plotted the log determinant of 100 covariance matrices from the same class. I used the log scale on the x axis since all the determinants were numerically close to  0 and different magnitudes away from 0. I then took the determinant of the Riemannian Mean (mean induced by the Affine Invariant Riemannian Metric) of the covariance matrices as shown in green. This seems to correctly predict the mean determinant of the covariance matrices. I also, took the determinant of the arithmetic mean of the covariance, shown in red. The arithmetic average covariance matrix seems to have a determinant that is significantly higher than the class the average came from.
Comment: I guess it is a difference between pure and applied math: in pure math one does not use the terminology "Affine Invariant Riemannian Metric" for this metric.
Comment: Neither question 1 nor question 2 make much sense. It seems that the person who asked these questions does not know what a manifold is and what the curvature is, while using this terminology.
Comment: My suggestion is for you to figure out what kind of a question **you** would like to ask in relation to the cone of PSD matrices. In particular, does your text answer any questions **you** are interested in?
Comment: @MoisheKohan Yes, I was interested in the answers to the main points I listed. I provided my answers, but since I do not have background in this field, I was unsure if my points/understanding/use of terminology were correct, so I wanted to see if someone could confirm or correct it.
Comment: As I said, the questions make very little sense as stated. Unless the author of the original questions comes and clarifies the questions, your question is unanswerable, unless by an answer one means an explanation why do the questions make no sense and are based on misunderstanding and misuse of basic notions of differential geometry. A reasonable question would be "What are applications of non-flat metrics on the cone of PSD matrices?"
Comment: @MoisheKohan Here is how I interpreted their questions 1. Does a manifold need to be a hypersurface to be a manifold? 2. Given that the set of SPD matrices forms a convex cone and that linear combinations of SPD matrices remain SPD, why do we often define a Riemannian metric that takes into account the curvature of this set, rather than using a simpler, flat metric?
Comment: @MoisheKohan Do these questions make sense and do my provided answers correctly address these questions? (For the second question I understand it is application specific so there could be many reasons that lead to the choice of a metric, but is the one I provided a common reason as to why the affine invariant metric is chosen in practice?)
Comment: The first question is awkwardly stated but makes sense (and the answer is "absolutely not", but I do not see this written anywhere in your answer), while the second question does not make sense. As for your example of an application - I have no idea. Applications that I know are completely different.
Comment: @MoisheKohan How would you restate the first question to make it less awkward? Additionally, although it does not say absolutely not, is there anything incorrect/unrelated in the answer I provided?

As for the second question, I am trying to ask and answer why people use the affine invariant metric instead of the euclidean metric. What would be the correct way to phrase that?
Comment: A proper way to restate the 1st question would be "If $M$ is a manifold, does $M$ have to be a hypersurface in some $\mathbb R^N$." You pretty much just stated the question that should have been asked, except "affine" is strange and it is better to say "invariant under $GL(n,\mathbb R)$" (or $SL(n,\mathbb R)$, depending on the precise setup). As for your answer to 1, it is a mixture of correct and incorrect.
Comment: @MoisheKohan That makes sense, but I was specifically referring to a metric I have seen in literature called the Affine Invariant Riemannian Metric (https://ieeexplore.ieee.org/document/7740054), but I should have capitalized it and added the full name and source to avoid confusion. Would you be able to expand upon which parts of the first question (and or the second) are correct and incorrect? Thank you for the clarifications
Answer:
Although it is easier to imagine a manifold as a hyper-surface, a manifold does not need to be in some ambient space of higher dimension to be a manifold.

Validity of the 1st sentence depends on its interpretation. In modern topology and differential geometry, manifolds are indeed abstract and are not considered as subsets of some "ambient space." Nevertheless, every manifold $M$ is naturally embedded as a hypersurface in $M\times \mathbb R$. But, most likely, in the original question it was meant to be a hypersurface in some Euclidean space. Then the answer is that there are, for instance, surfaces, which cannot be embedded in $\mathbb R^3$, e.g. the projective plane and the Klein bottle.

So take the PSD cone formed by the set of the set of 2x2 PSD matrices. This would be a [3 manifold][1] since locally it is diffeomorphic to $\mathbb{R}^3$.

This is correct but, actually, it is not only locally diffeomorphic to $\mathbb{R}^3$, but is globally diffeomorphic to $\mathbb{R}^3$. A bit cleaner statement would be:
The PSD cone $S_2^+$ is an open subset of the 3-dimensional real vector space $S_2$ of symmetric $2\times 2$ matrices. Hence, $S_2^+$ has a natural structure of a differentiable 3-dimensional manifold. As such, it is diffeomorphic to $\mathbb R^3$.

Whether that cone is in $\mathbb{R}^3$, $\mathbb{R}^4$, or $\mathbb{R}^n$ does not make a difference. i.e. Manifolds are independent of the ambient space they live/are portrayed in.

One cannot say "manifolds are independent." One can say that "being a topological manifold is an intrinsic property of a topological space and has nothing to do with its embedding, if it happens to be embedded in an ambient topological space." One can make a similar statement about differentiable manifolds, for instance:
A differentiable manifold is a topological space equipped with an atlas of charts satisfying certain properties. It is a theorem that every $n$-dimensional manifold can be embedded in $\mathbb R^{2n}$ but such an embedding does not change the intrinsic properties of the manifold.
Unstated in all this is the fact that the author of the original questions probably did not even mean a differentiable manifold but had in mind Riemannian manifolds. Only once you equip a manifold with a Riemannian metric (or a semi-Riemannian metric), you can talk about its curvature.


Vivaldi's "The Four Seasons", Who Chose the Title?

Question: Did Vivaldi himself choose the title "The Four Seasons" and the titles for each of the four concerti, or they're chosen by publishers?
Answer: Le quattro stagioni is the original title of this work, which translates to 'The four seasons'. This title was indeed chosen by Vivaldi himself, who deliberately composed the pieces to reflect the mood of each season.
The wikipedia article sums the titles up pretty nicely!
Comment: Thanks. Actually, I read the wikipedia article before writing this post, but I didn't find the answer.
Comment: This man is owed an answer.
Comment: Note that it are actually four separate works, together called *Le quattro stagioni*.
Answer: Vivaldi's Four Seasons is one of the best and earliest examples in music history of what is called programmatic music or tone poems. The instrumental music was written by Vivaldi to tell a specific story which has accompanying words that are written down, not sung.
Vivaldi chose the titles for each movement. Vivaldi wrote four poems, one for each movement, in Italian, which describe the meaning behind the music in each movement and which were part of the original publication of the sheet music.
More importantly, within the sheet music itself, at specific places, Vivaldi wrote in phrases and sentences from the poems that describe the scenes and characters that the music is supposed to evoke, in order to give direction to the musicians.
You can see a facsimile of some pages from a published score in Google Books at this link. Scroll through the pages and you can see Vivaldi's text descriptions attached to the music, in Italian and partial English translation.
Here is a screen shot from the beginning of the Spring sonata.

The Italian text reads: "The birds celebrate her [Spring's] return with festive song, and murmuring streams are softly caressed by the breezes."
Here is a web page that gives the texts of the four sonnets in the original Italian and in English translation.
http://www.baroquemusic.org/vivaldiseasons.html
(It is generally believed that Vivaldi wrote these poems, although it is possible that his original publishing company commissioned someone else to write them; regardless, they have always been regarded as a proper part of the sheet music itself.)