Speed in m/s is normally distributed, but same data expressed as "Time for 10 meters" is not

Question: I am trying to understand why the same data can be normally distributed if expressed in one way, but not normally distributed if expressed in another way.
I have a variable that is "time taken to walk 10 meters" (in seconds). This data is not normally distributed (Shapiro-Wilk: W = 0.632, df = 108, Sig. <0.001, +see "histogram 1" below).
I expressed this same variable as "speed" (in meters per second). I computed it by dividing 10 meters by the time taken to complete the distance, (ex. 14 sec to complete 10 meters becomes 10/14 = 0.71 m/s).
When I now check "speed" for normality, it is very much normally distributed (Shapiro-Wilk: W = 0.984, df = 108, Sig. = 0.234, +see "histogram 2" below).
Am I doing something wrong, or is there a logical explanation for this? While adding the tags, stackexchange mentioned "inverse Gaussian distribution" - is this what is happening here?
Comment: Re the title: Speeds (being non-negative) can't actually be Gaussian. They might sometimes be approximately Gaussian. Elapsed times like this are typically skew.
Comment: Normal distributions only stay normal under linear transformations.
Comment: Whenever you are transforming data then the density distribution will change. You might get this more intuitively when you transform a uniform distributed variable. Say $X$ is uniform distributed between $0$ and $1$, then what is the distribution of $X^2$? For example, how often are you gonna expect $X^2>0.5$, will it be just as much as $X>0.5$?
Comment: Although some cultures want to see significance test results, the graphs show all that is important. Speed is slightly left or negatively skewed; time is strongly right or positively skewed. Although it may seem contradictory, I would not describe speed as normally distributed, but I would be happy to use it in regression or analysis of variance. A normal quantile plot (other names include normal probability plot, normal scores plot, probit plot) is the best graph to assess departure from normality.
Comment: Another exercise. Draw two parallel lines. One with coordinates 0 to 100. Another with coordinates 0 to 1.2. For some evenly spaced points on that second line, say the points  $0.1, 0.2, .... 1.1, 1.2$ draw points on the first line according to the transformation $10/x$. Do you recover evenly distributed points after that transformation?
Comment: I believe this question has been thoroughly answered at https://stats.stackexchange.com/questions/14483/.  Although that question concerns a square root transformation, it (and its answers) are clearly meant to apply to any almost everywhere differentiable transformation such as the reciprocal.
Comment: @Mast https://imgur.com/EpaI9lG
Comment: Does it look better with less bars (increased step size)?
Answer: The image below illustrates intuitively why the transformed variable has a different distribution:
I have drawn two parallel lines.

On the lowest line I have plotted evenly spaced points at $0.1, 0.2, ..., 1.1, 1.2$ which represent the velocity $v$.
On the upper line I have draw points according to the formula $t=0.1/v$ (note I reversed the axis it has 1.2 on the left and 0 on the right)

I have drawn lines connecting the different points. You can see that the evenly spaced points $v$ are not transforming into evenly spaced points $t$ but instead the points are more dense in the low values than in the high values.
This squeezing will happen also to the density distribution. The distribution of times $t$ will not be just the same as the distribution of $v$ with a transformed location. Instead you also get a factor that is based on how much the space gets stretched out or squeezed in.

For instance: The region $0.1 < v < 0.2$ gets spread out over a region $0.5 < t <1$ which is a region with a larger size. So the same probability to fall into a specific region gets spread out over a region with larger size.

Another example: The region $0.4 < v < 0.5$ gets squeezed into a region $0.2 < t <0.25$ which is a region with a smaller size. So the same probability to fall into a specific region gets compressed into a region with smaller size.
In the image below these two corresponding regions $0.4 < v < 0.5$ and $0.2 < t <0.25$ and the area under the density curves are colored, the two different colored areas have the same area size.

So as the distribution for the times $g(t)$ you do not just take the distribution of the velocity $f(v)$ where you transform the variable $v=0.1/t$ (which actually already make the distribution look different than the normal curve, see the green curve in the image), but you also take into account the spreading/compressing of the probability mass over larger/smaller regions.

note: I have taken $t=0.1/v$ instead of $t = 100/v$ because this makes the two scales the same and makes the comparison of the two densities equivalent (when you squeeze an image then this will influence the density).

See more about transformations:
https://en.wikipedia.org/wiki/Random_variable#Functions_of_random_variables
The inverse of a normal distributed variable is more generally:
$$t = a/v \quad \text{with} \quad f_V(v) = \frac{1}{\sqrt{2 \pi \sigma^2}} e^{-\frac{1}{2}\frac{(v-\mu)^2}{\sigma^2}}$$
then
$$g_T(t) = \frac{1}{\sqrt{2 \pi \sigma^2}} \frac{a}{t^2} e^{-\frac{1}{2}\frac{(a/t-\mu)^2}{\sigma^2}}$$
you can find more about it by looking for the search term 'reciprocal normal distribution' https://math.stackexchange.com/search?q=reciprocal+normal+distribution
It is not the same as 'inverse Gaussian distribution', which relates to the waiting time in relation to Brownian motion with drift (which can be described by a Gaussian curve).
Answer: Yes, this is an instance of inverse Gaussian. It has been observed that there is an inverse relationship between the cumulant generating function of the time to cover a unit distance and the cumulant generating function of the distance covered in a unit time. Because the distance covered in a unit time (in this case, walking speed) is approximately normal, then the time to cover a unit distance (which is roughly the first-hitting time of 1-dimensional Brownian particle) is by definition approximately inverse Gaussian.
Comment: I am sorry to say this answer is not correct.   The inverse Gaussian distribution is not the distribution of the inverse of a Gaussian variable, despite the name; it is its own distribution, see https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution.
Comment: Just so as not to confuse other readers, it would be good to clarify that you are refering to the inverse of a Gaussian random variable, not to the distribution known as the "inverse Gaussian distribution" https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution
Comment: "when speed is Gaussian ..., the related time to cover a fixed distance is inverse Gaussian" - this statement is not correct.  The OP was explicitly referring to the "inverse Gaussian distribution" in the question, and it is simply not the case that the inverse of a Gaussian variate has an inverse Gaussian distribution.  Note for one thing that the inverse of a Gaussian variate can take on negative values ($1/-2 = -1/2$) but an inverse Gaussian variate can only take on positive values.
Comment: ok, inverse of a Gaussian random variable, that makes perfect sense - does the distribution followed by this "inverse of a Gaussian random variable" have a name (aka, does Histogram 1 follow a distribution that has a name)?
Comment: @jbowman - The article you referenced gives what was stated here as an example of the inverse Gaussian (it uses Brownian motion, but the idea is the same). This is not simply the inverse of a Gaussian distribution; the difference is the change in what is fixed in each.
Comment: I apologize if my initial comment wasn't clear. This is not about inverses in general, but specifically about the distance/time/speed issue at hand, which will never include a negative.
Comment: *"it uses Brownian motion, but the idea is the same"* No the idea is different. The question is not about brownian motion.


Javascript & PouchDB : can not return array of objects coming from pouchdb (because it is asynchronous?)

Question: I'm using JS and PouchDB in a Cordova project. The structure of the PouchDB database is as follows:
var act = {
  _id: <some_id>,
  activity: <some_description>,
  totaltime: <string_represeting_duration>,
  instances: [{datum: "04/04/18", tijd: "01:10"},{datum: "04/04/18", tijd: "00:35"}]
};

I have a function that should return an array of objects, namely from the field instances:
function queryDbForDatesAndDuration(todo) {
    var objDandD = [];

    db.get(todo._id).then(function(doc) {
        var t = doc.instances.length;
        for(i=0; i<t; i++) {
            objDandD[i] = {
                datum: doc.instances.datum,
                tijd: doc.instances.tijd
            };
        }
    }).then(function(response) {
        console.log(objDandD);
        return objDandD;
    }).catch(function (err) {
        console.log("And error occured while querying the DB for date and duration: " + err);
    });
}

The query to the database works, but ObjDandD is not passed when returned. I first thought that this is because PouchDB works asynchronous and the value is not resolved when returned, but using async / await did not help :
async function createSingleAct(todo) {
    ...
    var Ob = await queryDbForDatesAndDuration(todo);
    ...

It just keeps giving a TypeError :
TypeError: Ob is undefined

Anyone can help me with this? I've been searching desperately without result. Thanks.
Answer: The problem is that your queryDbForDatesAndDuration doesn't actually return anything. So while the db call works ok, and your objDandD object does get set, that's as far as it goes. In order for this to work, you could return the promise generated by db.get. For example:
function queryDbForDatesAndDuration(todo) {
  var objDandD = [];

  return db.get(todo._id).then(function(doc) {
    var t = doc.instances.length;
    ...

But this also makes queryDbForDatesAndDuration an async function, so the caller will need to use .then() to access the result. For example:
queryDbForDatesAndDuration(someTodo).then(objDandD => {
  // do something with objDandD here
})

Or, as you have in your question, await should work as well.


Distribution comparison by AIC

Question: I'd like to compare several distributions fitted to one dataset (of i.i.d. random variables) by AIC. Do there exist some specific rules of thumb for such a situation?
It seems that most of such rules are either for regression models or some extra conditions are needed (e.g. models are nested and sample sizes are large, as in book by Burnham and Anderson).
To be precise, I have a distribution $F$ and a distribution $G$, the sample size $n=100$,
$$
AIC(G) - AIC(F) = 17.9.
$$
Can I claim that there is substantial evidence that the fit of $F$ is better than that one of $G$?
Comment: What do you mean by *compare*? Different aspects of that call for different tools. See https://stats.stackexchange.com/questions/198799.
Comment: Avoid "Rules of thumb." The best way to compare is by getting a good feeling for what log-probabilities are and what they mean. A model with an AIC that's 0.1 higher than another is "10% more likely" or "10% better, as judged by likelihood."
Answer: AIC penalizes the likelihood by the number of parameters of the model under the assumption that a less complex model is preferable. The rules of thumb you mentioned are not specific to regression models, you can use them here as well, though they are only rules of thumb, so there are no guarantees they would be meaningful.
When comparing the distributions, the number of parameters wouldn't usually be your biggest concern. In such a case, you care about comparing the likelihoods. If the models are nested, there are not only rules of thumb, but rigorous criteria for such comparison since the procedure is a likelihood-ratio test where the test statistic follows the $\chi^2$ distribution. In fact, likelihood-ratio tests are common criteria for judging goodness-of-fit in such cases.
Comment: Surely AIC is useful for fitting distributions, regression models are just a particular form of describing a distribution (that also happens to be conditional on some covariates)? E.g. you could trade-off number of mixture components in a mixture distribution via AIC, surely?
Comment: @Björn ok, I improved the wording.
Comment: The likelihood ratio test follow the $\chi^2$ only for nested models, which is not necessarily the case in the OP question
Comment: @matteo right, good catch.
Answer: Distributions are statistical models, therefore you can quantify the evidence in a way that is semantically clearer using Akaike weights or evidence ratios (see section 2.9 and 2.10 in the book by Burnham and Anderson).
In you case, say $\Delta_G = AIC(G)−AIC_{\text{min}}=17.9$ (where $AIC_{\text{min}}$ is the smallest AIC among the set of models considered) we have that
$$
\exp \left( { - \frac{1}{2}{\Delta _G}} \right)=0.0001297372
$$
can be understood as the 'unnormalized' likelihood of $G$. The unnormalized likelihood of $F$ insted is $1$, since $AIC(F)−AIC_{\text{min}}=0$.
Thus you can say that the model $F$ is $\frac{1}{0.0001297372}=7707.892$ times more likely to be the best approximating model in a K-L sense; this would be the evidence ratio for model $F$ (see page 78 in Burnham and Anderson). (One way to think about this is that this is the model more likely to make better predictions of new data.)

Distribution comparison by AIC


Bash file for docker invalid reference $PWD

Question: I wrote a bash file to automatically build a docker image and run the docker. The build goes fine however i get an invalid reference error for using $PWD. The command is as follows:
<code>#!/bin/bash
app="docker.test2"
docker build -t ${app} .
docker run --rm -it -p 5000:5000 -v $PWD:/usr/src/Deployment -w /usr/src/Deployment/microblog2 ${app} flask run --host 0.0.0.0
</code>
When I replace the $PWD with the actual file path it works fine. I also tried replacing it with $pwd, $(pwd) and ${pwd} but to no avail. The error is as follows:
Comment: Docker never *sees* the `$PWD`; it has no way to know that that shell syntax was used, as you can verify if you run `bash -x yourscript` to enable trace logging during the script's execution. With that logging enabled, you'll see that the `$PWD` reference is replaced with the actual directory name before docker is even started.
Comment: ...but really, **do** run `bash -x yourscript`, and compare that to the trace logs generated when running `set -x` at an interactive prompt, and then running the same (working!) command there. If there's something like a hidden character in your script, or any other difference between how the command is executed in the two environments, that'll expose it.
Comment: Keep an eye out, in particular, for the last argument becoming `$'0.0.0.0\r'` in the trace logs; if you see that, it means your script was saved as a DOS/Windows text file, instead of in UNIX format.
Comment: One other thing: If your directory name contains spaces, you'll need double quotes around the `$PWD`. That is, `"$PWD":/usr/src/Deployment`, or `"$PWD:/usr/src/Deployment"`. That said, any bugs caused by a lack of quotes will show up in the `set -x` logs, so consider the request for them reiterated again. :)
Comment: Can you post the command that you run with the actual file path?
Comment: Sorry, what's the actual error message you're getting?  Can you replace the image you've attached here with the actual text of that error?
Comment: the error no longer appears now, i changed the $PWD to $(pwd). however this still does not explain what happened. unfortunately i could not recreate the error and thus had nothing useful to look at from bash -x myscript
Comment: @DavidMaze the second to last line in the screenshot is the actual error. docker: invalid reference format
Comment: @NguyenLamPhuc the command i run is simply bash start.sh with the $PWD replaced with my actual file path,  the path that $PWD should have given me automatically
Answer: <code>Docker/test:latest
</code>
should work fine
Comment: dont understand this, could you please supplement this answer?


How do you sort only the first column in a csv file and not affect any of the other columns while doing so using python

Question: i am working on a table(csv file) where it has the following data:
roll_no,student_name,grade,email_id
1,Aarav Gosalia,Grade 11,firstname.lastname@example.com
2,Aarav Rawal,Grade 11,email@example.com
3,Abizar Chitalwala,Grade 11,firstname.lastname@example.com
4,Ahad Motorwala,Grade 11,firstname.lastname@example.com
5,Armaan Adenwala,Grade 11,firstname.lastname@example.com
6,Aryan Shah,Grade 11,firstname.lastname@example.com
7,Baasit Motorwala,Grade 11,firstname.lastname@example.com
16,Caroline Walker,Grade 11,email@example.com
8,Darsshan Kavedia,Grade 11,email@example.com
9,Devanshi Rajgharia,Grade 11,firstname.lastname@example.com
10,Dhruv Jain,Grade 11,email@example.com
11,Eisa Patel,Grade 11,email@example.com
12,Esha Khimawat,Grade 11,firstname.lastname@example.com
13,Fatima Unwala,Grade 11,firstname.lastname@example.com
14,Hamza Erfan,Grade 11,email@example.com
15,Harsh Gosar,Grade 11,email@example.com

so as you can see all of the names are sorted but the roll number of caroline walker is 16. so i want a way to sort only the roll numbers and not affect any of the other columns while doing so.
I want the final table to look like this:
roll_no,student_name,grade,email_id
1,Aarav Gosalia,Grade 11,email@example.com
2,Aarav Rawal,Grade 11,email@example.com
3,Abizar Chitalwala,Grade 11,email@example.com
4,Ahad Motorwala,Grade 11,firstname.lastname@example.com
5,Armaan Adenwala,Grade 11,email@example.com
6,Aryan Shah,Grade 11,firstname.lastname@example.com
7,Baasit Motorwala,Grade 11,firstname.lastname@example.com
8,Caroline Walker,Grade 11,firstname.lastname@example.com
9,Darsshan Kavedia,Grade 11,email@example.com
10,Devanshi Rajgharia,Grade 11,email@example.com
11,Dhruv Jain,Grade 11,email@example.com
12,Eisa Patel,Grade 11,firstname.lastname@example.com
13,Esha Khimawat,Grade 11,email@example.com
14,Fatima Unwala,Grade 11,email@example.com
15,Hamza Erfan,Grade 11,firstname.lastname@example.com
16,Harsh Gosar,Grade 11,email@example.com

Please help me and keep in mind that i am yet a beginner in python.
Comment: Have you managed to look at the `csv` module - specifically `csv.DictReader` and do you know of the `sorted` function? eg: how far along are you - do you know how to open a file and read it into memory etc... or at you literally sitting at your keyboard just with a file and have no idea where to start...?
Answer: just use pandas. df['roll_no'] = range(1:len(df))
Answer: pandas is one way.
import pandas as pd

df = pd.read_csv('file.csv')
df.sort_values(by='roll_no')
df.to_csv('file.csv',index=False)

Answer: This will work:
df = pd.DataFrame({'id':[1,3,2,7],
                   'name': ['M', 'r', 'd', 'd']})
df['id'] =  list(df['id'].sort_values())
df

Result:
    id  name
0   1   M
1   2   r
2   3   d
3   7   d


Audit reserved IPs for UNIX/Linux ISC-DHCP

Question: Are there any good FOSS tools to do an audit of reserved IPs used in a Linux/UNIX ISC DHCPd environment?  I'm trying to ensure that we do not have stale IP addresses reserved when old MAC addresses are pulled.
Answer: Per your comments to David's answer, it sounds like you need something to regularly poll the ARP tables on your default gateway and/or servers.
Some relatively simple Perl scripting of their SNMP tables should allow you to probe that, and build a long-term database of MAC -> IP mappings.  See e.g. http://docstore.mik.ua/orelly/perl/sysadmin/ch10_03.htm
Answer: The original question asked for FOSS tools for this purpose, but I'm not aware of any that do it just right.
I have had to perform this exercise in the past, so I can explain why some other suggestions here may not be enough.  I'd ask what kind of routers you're using on your network.

Scanning the network at a particular time is not sufficient; it ignores the temporal aspect of use, among other things.  Simply, a host may not be online while you did the scan.  Another problem is that a host may have a firewall enabled to block the scan.
A human process... well, they're such squishy things, why would you want a human to do this?
Comparing DHCP conf to vended leases may be insufficient as well.  The leases database would again have to be tracked over time.  But the real problem is that you may have created an entry in your configuration which is being used statically, rather than via DHCP.  Someone may have requested an address, found they could not configure DHCP properly, and hard-coded the address assigned to the machine.

The solution I used was to collect ARP records from (Cisco) routers.  The minimal information you need to capture is IP address, MAC address and some temporal data (first seen, last seen) over some period of time.  This could then be compared against your DHCP configuration to see which registrations are NOT being used and may be reclaimed.  ARP logs reveal other information of use, such as

Registered MAC with registered IP address but no DHCP lease record -- host is hard-coded to their registration, not using DHCP.
Registered MAC not using registered IP address -- if on the same network, likely hard-coding to the wrong address; if on another network, host may have relocated.
Unregistered MAC with registered or unregistered IP address -- perhaps a new NIC, perhaps a rogue hard-coder.

You also need to create (and publish for users) a policy so the script that compares DHCP records with ARP information will nominate addresses to be reclaimed after some time N of non-usage.  We used six months, though we did end up reclaiming an address of a staff member who went on sabbatical.  Adjust as reasonable.
Hope this helps!
Answer: I've no idea if or how well this works but it appears to collect some of the data you require so it could be a start.
Answer: If you mean dynamic allocation of leases, you don't have to do anything.  The ISC dhcpd tries to hold on to previously assigned leases as long as possible until the lease pool is empty.  It will then scavenge from expired (and therefore currently unused) leases.
If you mean static reservations, the answer is: human process.
You are cleaning up your DNS (and, if applicable, NIS) when old computers are decommissioned, right?  So add a note to that process to clean up DHCP reservations at the same time.
In our case, we have a perl script that reads a specially formatted source file and generates NIS, DNS (forward AND backward), and DHCP tables automatically, distributes them, and notifies the serving daemons.  This means we have one stop to clean up after ourselves and/or add something new.
Comment: I'm looking for something that helps the human process.  That is the process that usually breaks down.  So if I could see that 10.0.0.2 hasn't had the fixed machine connect to it all year, I'd see that I may no longer need that reservation.  The big problem is the networking staff may not be notified when some receives a new laptop.  The laptop is not on the network all the time either so it is harder to track.
Answer: I think you could put together a pretty simple perl script that would compare /etc/dhcpd.conf and /var/lib/dhcp/dhcpd.leases
I'd look at http://search.cpan.org/~jhthorsen/Net-ISC-DHCPd/lib/Net/ISC/DHCPd.pm which seems to have modules for reading both of those types of files.
Answer: Another thought would be to capture and parse the output of a command like:
nmap -sP -oG output.txt 10.0.0.0/8
If the command was run at Noon, or some other time when "everyone" should be on line it would likely capture the phantom laptop most of the time.
Answer: In places like schools and universities they register users based on their mac address, Tools like arpwatch have a database of static ARP entries. It is best to audit your network space prior to building an MAC address database. This is run on the NAT/DHCP gateway.
DHCP should not be depended on for network user management. What happens if someone picks a static IP?
Good luck,
Ash

arpwatch is a computer software tool for monitoring Address Resolution Protocol traffic on a computer network. It generates a log of observed pairing of IP addresses with MAC addresses along with a timestamp when the pairing appeared on the network.
Network administrators monitor ARP activity to detect ARP spoofing. -- Wikipedia


Linux routing and port forwarding to a secondary network not working from WAN

Question: I have a linux box acting as a router, with two interfaces
· eth0 - 192.168.0.61
· as0t0 - 172.27.224.1
Network 192.168.2.0/24 is accesible through as0t0, so I have this routes:
[email@example.com ~]# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         gateway         0.0.0.0         UG    100    0        0 eth0
172.27.224.0    0.0.0.0         255.255.240.0   U     0      0        0 as0t0
192.168.0.0     0.0.0.0         255.255.255.0   U     100    0        0 eth0
192.168.2.0     0.0.0.0         255.255.255.0   U     0      0        0 as0t0

I also have a port forwarding rule:
iptables -t nat -A PREROUTING -p tcp -i eth0 --dport 8123 -j DNAT --to-destination 192.168.2.245:8123

Currently a host of 192.168.0.0/24 can use the web server at 192.168.2.245:8123 perfectly, it does not work from host of the WAN. Main router is 192.168.0.251 with routes and port forwarding.
Packets reach 192.168.0.61 eth0, but they don't go through as0t0, and I do not know why.
As example, when the host 192.168.0.6 use a web browser to 192.168.0.61:8123 all works perfectly.
[firstname.lastname@example.com ~]# tcpdump -i eth0 port 8123 -n
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
16:47:22.232044 IP 192.168.0.6.58898 > 192.168.0.61.8123: Flags [SEW], seq 361471277, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
16:47:22.305155 IP 192.168.0.61.8123 > 192.168.0.6.58898: Flags [S.], seq 226116772, ack 361471278, win 64240, options [mss 1258,nop,nop,sackOK,nop,wscale 7], length 0
16:47:22.305722 IP 192.168.0.6.58898 > 192.168.0.61.8123: Flags [.], ack 1, win 1027, length 0
16:47:22.305868 IP 192.168.0.6.58898 > 192.168.0.61.8123: Flags [P.], seq 1:601, ack 1, win 1027, length 600
16:47:22.446997 IP 192.168.0.61.8123 > 192.168.0.6.58898: Flags [.], ack 601, win 501, length 0
16:47:22.447020 IP 192.168.0.61.8123 > 192.168.0.6.58898: Flags [P.], seq 1:170, ack 601, win 501, length 169
16:47:22.447035 IP 192.168.0.61.8123 > 192.168.0.6.58898: Flags [P.], seq 170:230, ack 601, win 501, length 60
16:47:22.447484 IP 192.168.0.6.58898 > 192.168.0.61.8123: Flags [.], ack 230, win 1026, length 0
16:47:22.537873 IP 192.168.0.6.58898 > 192.168.0.61.8123: Flags [P.], seq 601:1431, ack 230, win 1026, length 830
16:47:22.646742 IP 192.168.0.61.8123 > 192.168.0.6.58898: Flags [.], ack 1431, win 501, length 0
16:47:22.646762 IP 192.168.0.61.8123 > 192.168.0.6.58898: Flags [P.], seq 230:400, ack 1431, win 501, length 170
16:47:22.646777 IP 192.168.0.61.8123 > 192.168.0.6.58898: Flags [P.], seq 400:570, ack 1431, win 501, length 170
16:47:22.647193 IP 192.168.0.6.58898 > 192.168.0.61.8123: Flags [.], ack 570, win 1024, length 0
...

[firstname.lastname@example.com ~]# tcpdump -i as0t0 port 8123 -n
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on as0t0, link-type RAW (Raw IP), capture size 262144 bytes
16:47:22.232111 IP 192.168.0.6.58898 > 192.168.2.245.8123: Flags [SEW], seq 361471277, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
16:47:22.305136 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [S.], seq 226116772, ack 361471278, win 64240, options [mss 1258,nop,nop,sackOK,nop,wscale 7], length 0
16:47:22.305863 IP 192.168.0.6.58898 > 192.168.2.245.8123: Flags [.], ack 1, win 1027, length 0
16:47:22.305872 IP 192.168.0.6.58898 > 192.168.2.245.8123: Flags [P.], seq 1:601, ack 1, win 1027, length 600
16:47:22.446980 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [.], ack 601, win 501, length 0
16:47:22.447013 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [P.], seq 1:170, ack 601, win 501, length 169
16:47:22.447030 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [P.], seq 170:230, ack 601, win 501, length 60
16:47:22.447495 IP 192.168.0.6.58898 > 192.168.2.245.8123: Flags [.], ack 230, win 1026, length 0
16:47:22.537892 IP 192.168.0.6.58898 > 192.168.2.245.8123: Flags [P.], seq 601:1431, ack 230, win 1026, length 830
16:47:22.646728 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [.], ack 1431, win 501, length 0
16:47:22.646755 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [P.], seq 230:400, ack 1431, win 501, length 170
16:47:22.646771 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [P.], seq 400:570, ack 1431, win 501, length 170
16:47:22.647207 IP 192.168.0.6.58898 > 192.168.2.245.8123: Flags [.], ack 570, win 1024, length 0

firstname.lastname@example.com:~ $ sudo tcpdump -i tun0 port 8123 -n
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on tun0, link-type RAW (Raw IP), capture size 262144 bytes
16:47:22.283238 IP 192.168.0.6.58898 > 192.168.2.245.8123: Flags [SEW], seq 361471277, win 64240, options [mss 1258,nop,wscale 8,nop,nop,sackOK], length 0
16:47:22.283327 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [S.], seq 226116772, ack 361471278, win 64240, options [mss 1460,nop,nop,sackOK,nop,wscale 7], length 0
16:47:22.375692 IP 192.168.0.6.58898 > 192.168.2.245.8123: Flags [.], ack 1, win 1027, length 0
16:47:22.375946 IP 192.168.0.6.58898 > 192.168.2.245.8123: Flags [P.], seq 1:601, ack 1, win 1027, length 600
16:47:22.375988 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [.], ack 601, win 501, length 0
16:47:22.383365 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [P.], seq 1:170, ack 601, win 501, length 169
16:47:22.383586 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [P.], seq 170:230, ack 601, win 501, length 60
16:47:22.494391 IP 192.168.0.6.58898 > 192.168.2.245.8123: Flags [.], ack 230, win 1026, length 0
16:47:22.585272 IP 192.168.0.6.58898 > 192.168.2.245.8123: Flags [P.], seq 601:1431, ack 230, win 1026, length 830
16:47:22.585325 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [.], ack 1431, win 501, length 0
16:47:22.593274 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [P.], seq 230:400, ack 1431, win 501, length 170
16:47:22.594160 IP 192.168.2.245.8123 > 192.168.0.6.58898: Flags [P.], seq 400:570, ack 1431, win 501, length 170
16:47:22.693687 IP 192.168.0.6.58898 > 192.168.2.245.8123: Flags [.], ack 570, win 1024, length 0

However when the ask come from the internet 192.168.0.61 receive the ask but is not forwarded through as0t0. As example:
[email@example.com ~]# tcpdump -i eth0 port 8123 -n
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
16:51:55.079366 IP 126.96.36.199.54673 > 192.168.0.61.8123: Flags [S], seq 331949659, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
16:51:55.759341 IP 184.108.40.206.54674 > 192.168.0.61.8123: Flags [S], seq 459540767, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
16:51:55.785218 IP 220.127.116.11.54675 > 192.168.0.61.8123: Flags [S], seq 3837920396, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
16:51:56.037321 IP 184.108.40.206.54676 > 192.168.0.61.8123: Flags [S], seq 1212264514, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
16:51:56.095399 IP 220.127.116.11.54673 > 192.168.0.61.8123: Flags [S], seq 331949659, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
16:51:56.775268 IP 184.108.40.206.54674 > 192.168.0.61.8123: Flags [S], seq 459540767, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
16:51:56.797301 IP 18.104.22.168.54675 > 192.168.0.61.8123: Flags [S], seq 3837920396, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
16:51:57.055209 IP 188.8.131.52.54676 > 192.168.0.61.8123: Flags [S], seq 1212264514, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
16:51:58.115261 IP 188.8.131.52.54673 > 192.168.0.61.8123: Flags [S], seq 331949659, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
16:51:58.799213 IP 220.127.116.11.54674 > 192.168.0.61.8123: Flags [S], seq 459540767, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
16:51:58.800187 IP 22.214.171.124.54675 > 192.168.0.61.8123: Flags [S], seq 3837920396, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
16:51:59.067247 IP 22.214.171.124.54676 > 192.168.0.61.8123: Flags [S], seq 1212264514, win 64240, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0
...

[firstname.lastname@example.com~]# tcpdump -i as0t0 port 8123 -n
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on as0t0, link-type RAW (Raw IP), capture size 262144 bytes

firstname.lastname@example.com:~ $ sudo tcpdump -i tun0 port 8123 -n
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on tun0, link-type RAW (Raw IP), capture size 262144 bytes

I do not know how continue troubleshooting. Any idea?
Thanks
Edit 1:
[firstname.lastname@example.com ~]# iptables-save -c
# Generated by iptables-save v1.4.21 on Tue Oct 19 16:14:28 2021
*mangle
:PREROUTING ACCEPT [47:10649]
:INPUT ACCEPT [560:148103]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [548:147705]
:POSTROUTING ACCEPT [548:147705]
:AS0_MANGLE_PRE_REL_EST - [0:0]
:AS0_MANGLE_TUN - [0:0]
[533:144894] -A PREROUTING -m state --state RELATED,ESTABLISHED -j AS0_MANGLE_PRE_REL_EST
[2:251] -A PREROUTING -i as0t+ -j AS0_MANGLE_TUN
[533:144894] -A AS0_MANGLE_PRE_REL_EST -j ACCEPT
[2:251] -A AS0_MANGLE_TUN -j MARK --set-xmark 0x2000000/0xffffffff
[2:251] -A AS0_MANGLE_TUN -j ACCEPT
COMMIT
# Completed on Tue Oct 19 16:14:28 2021
# Generated by iptables-save v1.4.21 on Tue Oct 19 16:14:28 2021
*raw
:PREROUTING ACCEPT [611:161750]
:OUTPUT ACCEPT [577:150493]
COMMIT
# Completed on Tue Oct 19 16:14:28 2021
# Generated by iptables-save v1.4.21 on Tue Oct 19 16:14:28 2021
*filter
:INPUT ACCEPT [7:1954]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [504:140983]
:AS0_ACCEPT - [0:0]
:AS0_IN - [0:0]
:AS0_IN_NAT - [0:0]
:AS0_IN_POST - [0:0]
:AS0_IN_PRE - [0:0]
:AS0_IN_ROUTE - [0:0]
:AS0_OUT - [0:0]
:AS0_OUT_LOCAL - [0:0]
:AS0_OUT_POST - [0:0]
:AS0_OUT_S2C - [0:0]
:AS0_U_OPENVPN_IN - [0:0]
:AS0_U_OPENVPN_OUT - [0:0]
:AS0_WEBACCEPT - [0:0]
[534:144934] -A INPUT -m state --state RELATED,ESTABLISHED -j AS0_ACCEPT
[13:780] -A INPUT -i lo -j AS0_ACCEPT
[0:0] -A INPUT -m mark --mark 0x2000000/0x2000000 -j AS0_IN_PRE
[2:120] -A INPUT -d 192.168.0.61/32 -p tcp -m state --state NEW -m tcp --dport 1194 -j AS0_ACCEPT
[0:0] -A INPUT -m state --state RELATED,ESTABLISHED -j AS0_WEBACCEPT
[0:0] -A INPUT -p tcp -m state --state NEW -m tcp --dport 943 -j AS0_WEBACCEPT
[0:0] -A FORWARD -m state --state RELATED,ESTABLISHED -j AS0_ACCEPT
[0:0] -A FORWARD -m mark --mark 0x2000000/0x2000000 -j AS0_IN_PRE
[0:0] -A FORWARD -o as0t+ -j AS0_OUT_S2C
[0:0] -A OUTPUT -o as0t+ -j AS0_OUT_LOCAL
[549:145834] -A AS0_ACCEPT -j ACCEPT
[0:0] -A AS0_IN -d 172.27.224.1/32 -j ACCEPT
[0:0] -A AS0_IN -s 172.27.224.2/32 -j AS0_U_OPENVPN_IN
[0:0] -A AS0_IN -s 192.168.2.0/24 -j AS0_U_OPENVPN_IN
[0:0] -A AS0_IN -j AS0_IN_POST
[0:0] -A AS0_IN_NAT -j MARK --set-xmark 0x8000000/0x8000000
[0:0] -A AS0_IN_NAT -j ACCEPT
[0:0] -A AS0_IN_POST -d 192.168.0.0/24 -j ACCEPT
[0:0] -A AS0_IN_POST -o as0t+ -j AS0_OUT
[0:0] -A AS0_IN_POST -j DROP
[0:0] -A AS0_IN_PRE -d 169.254.0.0/16 -j AS0_IN
[0:0] -A AS0_IN_PRE -d 192.168.0.0/16 -j AS0_IN
[0:0] -A AS0_IN_PRE -d 172.16.0.0/12 -j AS0_IN
[0:0] -A AS0_IN_PRE -d 10.0.0.0/8 -j AS0_IN
[0:0] -A AS0_IN_PRE -j DROP
[0:0] -A AS0_IN_ROUTE -j MARK --set-xmark 0x4000000/0x4000000
[0:0] -A AS0_IN_ROUTE -j ACCEPT
[0:0] -A AS0_OUT -d 172.27.224.2/32 -j AS0_U_OPENVPN_OUT
[0:0] -A AS0_OUT -d 192.168.2.0/24 -j AS0_U_OPENVPN_OUT
[0:0] -A AS0_OUT -j AS0_OUT_POST
[0:0] -A AS0_OUT_LOCAL -p icmp -m icmp --icmp-type 5 -j DROP
[0:0] -A AS0_OUT_LOCAL -j ACCEPT
[0:0] -A AS0_OUT_POST -j DROP
[0:0] -A AS0_OUT_S2C -s 192.168.0.0/24 -j ACCEPT
[0:0] -A AS0_OUT_S2C -j AS0_OUT
[0:0] -A AS0_U_OPENVPN_IN -d 192.168.0.0/24 -j AS0_IN_ROUTE
[0:0] -A AS0_U_OPENVPN_IN -j AS0_IN_POST
[0:0] -A AS0_U_OPENVPN_OUT -s 192.168.0.0/24 -j ACCEPT
[0:0] -A AS0_U_OPENVPN_OUT -s 192.168.2.0/24 -j ACCEPT
[0:0] -A AS0_U_OPENVPN_OUT -s 172.27.224.0/20 -j ACCEPT
[0:0] -A AS0_U_OPENVPN_OUT -j AS0_OUT_POST
[0:0] -A AS0_WEBACCEPT -j ACCEPT
COMMIT
# Completed on Tue Oct 19 16:14:28 2021
# Generated by iptables-save v1.4.21 on Tue Oct 19 16:14:28 2021
*nat
:PREROUTING ACCEPT [36:10120]
:INPUT ACCEPT [14:2429]
:OUTPUT ACCEPT [18:1141]
:POSTROUTING ACCEPT [18:1141]
:AS0_NAT - [0:0]
:AS0_NAT_POST_REL_EST - [0:0]
:AS0_NAT_PRE - [0:0]
:AS0_NAT_PRE_REL_EST - [0:0]
:AS0_NAT_TEST - [0:0]
[0:0] -A PREROUTING -m state --state RELATED,ESTABLISHED -j AS0_NAT_PRE_REL_EST
[0:0] -A PREROUTING -i eth0 -p tcp -m tcp --dport 1883 -j DNAT --to-destination 192.168.2.245:1883
[0:0] -A PREROUTING -i eth0 -p tcp -m tcp --dport 1884 -j DNAT --to-destination 192.168.2.245:1884
[0:0] -A PREROUTING -i eth0 -p tcp -m tcp --dport 8123 -j DNAT --to-destination 192.168.2.245:8123
[0:0] -A PREROUTING -i eth0 -p tcp -m tcp --dport 2223 -j DNAT --to-destination 192.168.2.245:22
[0:0] -A POSTROUTING -m state --state RELATED,ESTABLISHED -j AS0_NAT_POST_REL_EST
[0:0] -A POSTROUTING -m mark --mark 0x2000000/0x2000000 -j AS0_NAT_PRE
[0:0] -A AS0_NAT -o eth0 -j SNAT --to-source 192.168.0.61
[0:0] -A AS0_NAT -j ACCEPT
[0:0] -A AS0_NAT_POST_REL_EST -j ACCEPT
[0:0] -A AS0_NAT_PRE -m mark --mark 0x8000000/0x8000000 -j AS0_NAT
[0:0] -A AS0_NAT_PRE -d 169.254.0.0/16 -j AS0_NAT_TEST
[0:0] -A AS0_NAT_PRE -d 192.168.0.0/16 -j AS0_NAT_TEST
[0:0] -A AS0_NAT_PRE -d 172.16.0.0/12 -j AS0_NAT_TEST
[0:0] -A AS0_NAT_PRE -d 10.0.0.0/8 -j AS0_NAT_TEST
[0:0] -A AS0_NAT_PRE -j AS0_NAT
[0:0] -A AS0_NAT_PRE_REL_EST -j ACCEPT
[0:0] -A AS0_NAT_TEST -o as0t+ -j ACCEPT
[0:0] -A AS0_NAT_TEST -m mark --mark 0x4000000/0x4000000 -j ACCEPT
[0:0] -A AS0_NAT_TEST -d 192.168.0.0/24 -j ACCEPT
[0:0] -A AS0_NAT_TEST -d 192.168.2.0/24 -j ACCEPT
[0:0] -A AS0_NAT_TEST -d 172.27.224.0/20 -j ACCEPT
[0:0] -A AS0_NAT_TEST -j AS0_NAT
COMMIT
# Completed on Tue Oct 19 16:14:28 202

Edit 2:
As @a-b suggest I give more info about the network layout, because there is a openVPN tunnel (routing) which may be filtering some packets. The openVPN tunnel is represented as a ray.

In the examples 192.168.0.6 can go through the tunnel, but public ip (184.108.40.206) not.
Comment: Please add the output of this in your question: `iptables-save -c`.(ie: the whole firewall, not an excerpt). Also as0t0 appears to not be Ethernet-like but probably some kind of layer 3 tunnel. So any additional information about the real network layout could also help.
Comment: I have just edited the post adding the output of iptables-save -c.
Comment: Yes, the network layout is a bit more complex, but I try to keep the question as simple as possible.
192.168.0.61 is a OpenVPN AS server (as0t0) and 192.168.2.245 is a OpenVPN client (tun0). But as far as I know there is no problem with that, as 192.168.2.245 is accesible from 192.168.0.0/24 without problems.
Comment: I would insert (rather than append) a rule in the filter FORWARD chain to allow traffic between eth0 and as0t0 and the other way around to check it's an iptables problem and not a routing problem. Then I'd check the tool which generated these rules (they don't look made by hand, do they?) to see how to enable the blocked traffic. I don't really see how to make an answer with these rules around.
Answer: Following @A.B suggestion I looked at OpenVPN AS settings, which generate a lot of iptables rules. I modified one field that was:
Routing
Specify the private subnets to which all clients should be given access (one per line):
192.168.0.0/24

By:
Routing
Specify the private subnets to which all clients should be given access (one per line):
192.168.0.0/24
0.0.0.0/0

Now packets with a public IP are forwared from eth0 to as0t0 with no problem and all is working.
If now I do a iptables-save -c I get:
[firstname.lastname@example.com ~]# iptables-save -c
# Generated by iptables-save v1.4.21 on Wed Oct 20 16:25:06 2021
*mangle
:PREROUTING ACCEPT [232:55794]
:INPUT ACCEPT [2986:381728]
:FORWARD ACCEPT [15:2541]
:OUTPUT ACCEPT [2929:1099682]
:POSTROUTING ACCEPT [2944:1102223]
:AS0_MANGLE_PRE_REL_EST - [0:0]
:AS0_MANGLE_TUN - [0:0]
[2899:374408] -A PREROUTING -m state --state RELATED,ESTABLISHED -j AS0_MANGLE_PRE_REL_EST
[12:1506] -A PREROUTING -i as0t+ -j AS0_MANGLE_TUN
[2899:374408] -A AS0_MANGLE_PRE_REL_EST -j ACCEPT
[12:1506] -A AS0_MANGLE_TUN -j MARK --set-xmark 0x2000000/0xffffffff
[12:1506] -A AS0_MANGLE_TUN -j ACCEPT
COMMIT
# Completed on Wed Oct 20 16:25:06 2021
# Generated by iptables-save v1.4.21 on Wed Oct 20 16:25:06 2021
*raw
:PREROUTING ACCEPT [3175:434235]
:OUTPUT ACCEPT [2972:1103685]
COMMIT
# Completed on Wed Oct 20 16:25:06 2021
# Generated by iptables-save v1.4.21 on Wed Oct 20 16:25:06 2021
*filter
:INPUT ACCEPT [61:5708]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [2839:1062541]
:AS0_ACCEPT - [0:0]
:AS0_IN - [0:0]
:AS0_IN_NAT - [0:0]
:AS0_IN_POST - [0:0]
:AS0_IN_PRE - [0:0]
:AS0_IN_ROUTE - [0:0]
:AS0_OUT - [0:0]
:AS0_OUT_LOCAL - [0:0]
:AS0_OUT_POST - [0:0]
:AS0_OUT_S2C - [0:0]
:AS0_U_OPENVPN_IN - [0:0]
:AS0_U_OPENVPN_OUT - [0:0]
:AS0_WEBACCEPT - [0:0]
[2900:374448] -A INPUT -m state --state RELATED,ESTABLISHED -j AS0_ACCEPT
[14:840] -A INPUT -i lo -j AS0_ACCEPT
[0:0] -A INPUT -m mark --mark 0x2000000/0x2000000 -j AS0_IN_PRE
[1:60] -A INPUT -d 192.168.0.61/32 -p tcp -m state --state NEW -m tcp --dport 1194 -j AS0_ACCEPT
[0:0] -A INPUT -m state --state RELATED,ESTABLISHED -j AS0_WEBACCEPT
[0:0] -A INPUT -p tcp -m state --state NEW -m tcp --dport 943 -j AS0_WEBACCEPT
[0:0] -A FORWARD -m state --state RELATED,ESTABLISHED -j AS0_ACCEPT
[0:0] -A FORWARD -m mark --mark 0x2000000/0x2000000 -j AS0_IN_PRE
[15:2541] -A FORWARD -o as0t+ -j AS0_OUT_S2C
[0:0] -A OUTPUT -o as0t+ -j AS0_OUT_LOCAL
[2915:375348] -A AS0_ACCEPT -j ACCEPT
[0:0] -A AS0_IN -d 172.27.224.1/32 -j ACCEPT
[0:0] -A AS0_IN -s 172.27.224.2/32 -j AS0_U_OPENVPN_IN
[0:0] -A AS0_IN -s 192.168.2.0/24 -j AS0_U_OPENVPN_IN
[0:0] -A AS0_IN -j AS0_IN_POST
[0:0] -A AS0_IN_NAT -j MARK --set-xmark 0x8000000/0x8000000
[0:0] -A AS0_IN_NAT -j ACCEPT
[0:0] -A AS0_IN_POST -j ACCEPT
[0:0] -A AS0_IN_POST -o as0t+ -j AS0_OUT
[0:0] -A AS0_IN_POST -j DROP
[0:0] -A AS0_IN_PRE -j AS0_IN
[0:0] -A AS0_IN_PRE -j DROP
[0:0] -A AS0_IN_ROUTE -j MARK --set-xmark 0x4000000/0x4000000
[0:0] -A AS0_IN_ROUTE -j ACCEPT
[0:0] -A AS0_OUT -d 172.27.224.2/32 -j AS0_U_OPENVPN_OUT
[0:0] -A AS0_OUT -d 192.168.2.0/24 -j AS0_U_OPENVPN_OUT
[0:0] -A AS0_OUT -j AS0_OUT_POST
[0:0] -A AS0_OUT_LOCAL -p icmp -m icmp --icmp-type 5 -j DROP
[0:0] -A AS0_OUT_LOCAL -j ACCEPT
[0:0] -A AS0_OUT_POST -j DROP
[15:2541] -A AS0_OUT_S2C -j ACCEPT
[0:0] -A AS0_OUT_S2C -j AS0_OUT
[0:0] -A AS0_U_OPENVPN_IN -d 192.168.0.0/24 -j AS0_IN_ROUTE
[0:0] -A AS0_U_OPENVPN_IN -j AS0_IN_POST
[0:0] -A AS0_U_OPENVPN_OUT -j ACCEPT
[0:0] -A AS0_U_OPENVPN_OUT -s 192.168.2.0/24 -j ACCEPT
[0:0] -A AS0_U_OPENVPN_OUT -s 172.27.224.0/20 -j ACCEPT
[0:0] -A AS0_U_OPENVPN_OUT -j AS0_OUT_POST
[0:0] -A AS0_WEBACCEPT -j ACCEPT
COMMIT
# Completed on Wed Oct 20 16:25:06 2021
# Generated by iptables-save v1.4.21 on Wed Oct 20 16:25:06 2021
*nat
:PREROUTING ACCEPT [207:53029]
:INPUT ACCEPT [63:5230]
:OUTPUT ACCEPT [19:1202]
:POSTROUTING ACCEPT [21:1562]
:AS0_NAT - [0:0]
:AS0_NAT_POST_REL_EST - [0:0]
:AS0_NAT_PRE - [0:0]
:AS0_NAT_PRE_REL_EST - [0:0]
:AS0_NAT_TEST - [0:0]
[0:0] -A PREROUTING -m state --state RELATED,ESTABLISHED -j AS0_NAT_PRE_REL_EST
[0:0] -A PREROUTING -i eth0 -p tcp -m tcp --dport 1883 -j DNAT --to-destination 192.168.2.245:1883
[0:0] -A PREROUTING -i eth0 -p tcp -m tcp --dport 1884 -j DNAT --to-destination 192.168.2.245:1884
[0:0] -A PREROUTING -i eth0 -p tcp -m tcp --dport 8123 -j DNAT --to-destination 192.168.2.245:8123
[0:0] -A PREROUTING -i eth0 -p tcp -m tcp --dport 2223 -j DNAT --to-destination 192.168.2.245:22
[0:0] -A POSTROUTING -m state --state RELATED,ESTABLISHED -j AS0_NAT_POST_REL_EST
[0:0] -A POSTROUTING -m mark --mark 0x2000000/0x2000000 -j AS0_NAT_PRE
[0:0] -A AS0_NAT -o eth0 -j SNAT --to-source 192.168.0.61
[0:0] -A AS0_NAT -j ACCEPT
[0:0] -A AS0_NAT_POST_REL_EST -j ACCEPT
[0:0] -A AS0_NAT_PRE -m mark --mark 0x8000000/0x8000000 -j AS0_NAT
[0:0] -A AS0_NAT_PRE -j AS0_NAT_TEST
[0:0] -A AS0_NAT_PRE -j AS0_NAT
[0:0] -A AS0_NAT_PRE_REL_EST -j ACCEPT
[0:0] -A AS0_NAT_TEST -o as0t+ -j ACCEPT
[0:0] -A AS0_NAT_TEST -m mark --mark 0x4000000/0x4000000 -j ACCEPT
[0:0] -A AS0_NAT_TEST -j ACCEPT
[0:0] -A AS0_NAT_TEST -j AS0_NAT
COMMIT
# Completed on Wed Oct 20 16:25:06 2021[root@centoscwp ~]# iptables-save -c
# Generated by iptables-save v1.4.21 on Wed Oct 20 16:25:06 2021
*mangle
:PREROUTING ACCEPT [232:55794]
:INPUT ACCEPT [2986:381728]
:FORWARD ACCEPT [15:2541]
:OUTPUT ACCEPT [2929:1099682]
:POSTROUTING ACCEPT [2944:1102223]
:AS0_MANGLE_PRE_REL_EST - [0:0]
:AS0_MANGLE_TUN - [0:0]
[2899:374408] -A PREROUTING -m state --state RELATED,ESTABLISHED -j AS0_MANGLE_PRE_REL_EST
[12:1506] -A PREROUTING -i as0t+ -j AS0_MANGLE_TUN
[2899:374408] -A AS0_MANGLE_PRE_REL_EST -j ACCEPT
[12:1506] -A AS0_MANGLE_TUN -j MARK --set-xmark 0x2000000/0xffffffff
[12:1506] -A AS0_MANGLE_TUN -j ACCEPT
COMMIT
# Completed on Wed Oct 20 16:25:06 2021
# Generated by iptables-save v1.4.21 on Wed Oct 20 16:25:06 2021
*raw
:PREROUTING ACCEPT [3175:434235]
:OUTPUT ACCEPT [2972:1103685]
COMMIT
# Completed on Wed Oct 20 16:25:06 2021
# Generated by iptables-save v1.4.21 on Wed Oct 20 16:25:06 2021
*filter
:INPUT ACCEPT [61:5708]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [2839:1062541]
:AS0_ACCEPT - [0:0]
:AS0_IN - [0:0]
:AS0_IN_NAT - [0:0]
:AS0_IN_POST - [0:0]
:AS0_IN_PRE - [0:0]
:AS0_IN_ROUTE - [0:0]
:AS0_OUT - [0:0]
:AS0_OUT_LOCAL - [0:0]
:AS0_OUT_POST - [0:0]
:AS0_OUT_S2C - [0:0]
:AS0_U_OPENVPN_IN - [0:0]
:AS0_U_OPENVPN_OUT - [0:0]
:AS0_WEBACCEPT - [0:0]
[2900:374448] -A INPUT -m state --state RELATED,ESTABLISHED -j AS0_ACCEPT
[14:840] -A INPUT -i lo -j AS0_ACCEPT
[0:0] -A INPUT -m mark --mark 0x2000000/0x2000000 -j AS0_IN_PRE
[1:60] -A INPUT -d 192.168.0.61/32 -p tcp -m state --state NEW -m tcp --dport 1194 -j AS0_ACCEPT
[0:0] -A INPUT -m state --state RELATED,ESTABLISHED -j AS0_WEBACCEPT
[0:0] -A INPUT -p tcp -m state --state NEW -m tcp --dport 943 -j AS0_WEBACCEPT
[0:0] -A FORWARD -m state --state RELATED,ESTABLISHED -j AS0_ACCEPT
[0:0] -A FORWARD -m mark --mark 0x2000000/0x2000000 -j AS0_IN_PRE
[15:2541] -A FORWARD -o as0t+ -j AS0_OUT_S2C
[0:0] -A OUTPUT -o as0t+ -j AS0_OUT_LOCAL
[2915:375348] -A AS0_ACCEPT -j ACCEPT
[0:0] -A AS0_IN -d 172.27.224.1/32 -j ACCEPT
[0:0] -A AS0_IN -s 172.27.224.2/32 -j AS0_U_OPENVPN_IN
[0:0] -A AS0_IN -s 192.168.2.0/24 -j AS0_U_OPENVPN_IN
[0:0] -A AS0_IN -j AS0_IN_POST
[0:0] -A AS0_IN_NAT -j MARK --set-xmark 0x8000000/0x8000000
[0:0] -A AS0_IN_NAT -j ACCEPT
[0:0] -A AS0_IN_POST -j ACCEPT
[0:0] -A AS0_IN_POST -o as0t+ -j AS0_OUT
[0:0] -A AS0_IN_POST -j DROP
[0:0] -A AS0_IN_PRE -j AS0_IN
[0:0] -A AS0_IN_PRE -j DROP
[0:0] -A AS0_IN_ROUTE -j MARK --set-xmark 0x4000000/0x4000000
[0:0] -A AS0_IN_ROUTE -j ACCEPT
[0:0] -A AS0_OUT -d 172.27.224.2/32 -j AS0_U_OPENVPN_OUT
[0:0] -A AS0_OUT -d 192.168.2.0/24 -j AS0_U_OPENVPN_OUT
[0:0] -A AS0_OUT -j AS0_OUT_POST
[0:0] -A AS0_OUT_LOCAL -p icmp -m icmp --icmp-type 5 -j DROP
[0:0] -A AS0_OUT_LOCAL -j ACCEPT
[0:0] -A AS0_OUT_POST -j DROP
[15:2541] -A AS0_OUT_S2C -j ACCEPT
[0:0] -A AS0_OUT_S2C -j AS0_OUT
[0:0] -A AS0_U_OPENVPN_IN -d 192.168.0.0/24 -j AS0_IN_ROUTE
[0:0] -A AS0_U_OPENVPN_IN -j AS0_IN_POST
[0:0] -A AS0_U_OPENVPN_OUT -j ACCEPT
[0:0] -A AS0_U_OPENVPN_OUT -s 192.168.2.0/24 -j ACCEPT
[0:0] -A AS0_U_OPENVPN_OUT -s 172.27.224.0/20 -j ACCEPT
[0:0] -A AS0_U_OPENVPN_OUT -j AS0_OUT_POST
[0:0] -A AS0_WEBACCEPT -j ACCEPT
COMMIT
# Completed on Wed Oct 20 16:25:06 2021
# Generated by iptables-save v1.4.21 on Wed Oct 20 16:25:06 2021
*nat
:PREROUTING ACCEPT [207:53029]
:INPUT ACCEPT [63:5230]
:OUTPUT ACCEPT [19:1202]
:POSTROUTING ACCEPT [21:1562]
:AS0_NAT - [0:0]
:AS0_NAT_POST_REL_EST - [0:0]
:AS0_NAT_PRE - [0:0]
:AS0_NAT_PRE_REL_EST - [0:0]
:AS0_NAT_TEST - [0:0]
[0:0] -A PREROUTING -m state --state RELATED,ESTABLISHED -j AS0_NAT_PRE_REL_EST
[0:0] -A PREROUTING -i eth0 -p tcp -m tcp --dport 1883 -j DNAT --to-destination 192.168.2.245:1883
[0:0] -A PREROUTING -i eth0 -p tcp -m tcp --dport 1884 -j DNAT --to-destination 192.168.2.245:1884
[0:0] -A PREROUTING -i eth0 -p tcp -m tcp --dport 8123 -j DNAT --to-destination 192.168.2.245:8123
[0:0] -A PREROUTING -i eth0 -p tcp -m tcp --dport 2223 -j DNAT --to-destination 192.168.2.245:22
[0:0] -A POSTROUTING -m state --state RELATED,ESTABLISHED -j AS0_NAT_POST_REL_EST
[0:0] -A POSTROUTING -m mark --mark 0x2000000/0x2000000 -j AS0_NAT_PRE
[0:0] -A AS0_NAT -o eth0 -j SNAT --to-source 192.168.0.61
[0:0] -A AS0_NAT -j ACCEPT
[0:0] -A AS0_NAT_POST_REL_EST -j ACCEPT
[0:0] -A AS0_NAT_PRE -m mark --mark 0x8000000/0x8000000 -j AS0_NAT
[0:0] -A AS0_NAT_PRE -j AS0_NAT_TEST
[0:0] -A AS0_NAT_PRE -j AS0_NAT
[0:0] -A AS0_NAT_PRE_REL_EST -j ACCEPT
[0:0] -A AS0_NAT_TEST -o as0t+ -j ACCEPT
[0:0] -A AS0_NAT_TEST -m mark --mark 0x4000000/0x4000000 -j ACCEPT
[0:0] -A AS0_NAT_TEST -j ACCEPT
[0:0] -A AS0_NAT_TEST -j AS0_NAT
COMMIT
# Completed on Wed Oct 20 16:25:06 2021

As you can see some rules has been changed, like:
before:
[0:0] -A AS0_IN_POST -d 192.168.0.0/24 -j ACCEPT
[0:0] -A AS0_OUT_S2C -s 192.168.0.0/24 -j ACCEPT
[0:0] -A AS0_U_OPENVPN_OUT -s 192.168.0.0/24 -j ACCEPT
[0:0] -A AS0_NAT_PRE -d 192.168.0.0/16 -j AS0_NAT_TEST

after:
[0:0] -A AS0_IN_POST -j ACCEPT
[15:2541] -A AS0_OUT_S2C -j ACCEPT
[0:0] -A AS0_U_OPENVPN_OUT -j ACCEPT
[0:0] -A AS0_NAT_PRE -j AS0_NAT_TEST

I attach a screenshot of the OpenVPN setting I have changed


How to modify HttpContext in ActionExecutionContext to deny the request with a body?

Question: The ActionExecutionContext is defined in a ActionFilter attribute.
Example:
 internal class TestAttribute : ActionFilterAttribute
 {
     public override void OnActionExecuting(ActionExecutingContext context)
     {

         context.HttpContext.Response.StatusCode = 400;

         //context.HttpContext.Response.Body
     }
 }

How do you make the response of the ActionExecutionContext's HttpContext have status code 400 (Bad Request), and to also have a body of for example "You have no access."
In ASP.NET you could easily do this with the following code:
HttpActionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
   Content = "You have no access.";
}

You can define the status code by using
ActionExecutionContext.HttpContext.Response.StatusCode = 400;

but what about the contents, and is this really the best approach - to manually write in the status code number?
Comment: I think you can use methods on `Response` property e.g. `Response.ClearContent();` and `Response.Write("You have no access.");`
Comment: Is it `context.Result = new BadRequestObjectResult("You have no access.");`?
Comment: It's not in a controller, it's part of an action filter. Aren't ActionExecutionContext only used there? I'll clarify just in case.
Answer: As suggested by dropoutcoder and stuartd, both approaches are valid and work perfectly!
internal class TestAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // Suggested by dropoutcoder
        context.HttpContext.Response.Clear();
        context.HttpContext.Response.WriteAsync("You have no access").Wait();
        context.HttpContext.Response.StatusCode = 400;

        // Suggested by stuartd
        context.Result = new BadRequestObjectResult("You have no access");
    }
}


Nested Case-Control vs propensity score matching vs inverse probability when comparing differences in incident outcomes

Question: I am not sure about the best design in this case.
I have a representative sample (N=15,000) of individuals with a moderately rare condition and I want to match them to controls who do not have this condition. I want to compare rates of fatal and non-fatal vascular events and all-cause mortality between cases and controls controlling for confounders (demographic, SES, and clinical characteristics). As for controls I can extract them from a random sample (N=1,000,000) which is also state representative.
In summary I want to match case and controls and follow them up for 10 years to compare rates of different outcomes.
My first thought was to perform a propensity score 1:m kernel matching (including for the matching estimator age, sex, but also vascular risk factors considering I am going to look at vascular outcomes) and compare incident outcomes. However, I read it does not perform well when you try to match selected cases to a random sample of control. Any good reference that might support the opposite?
I also thought about a nested case control design matching by age and sex and controlling in the conditional logistic regression for the baseline cardiovascular risk factor. However, in my case I would match at baseline and then follow-up my two groups over time to compare rates (or probability as in the conditional logistic regression). Would this design still be appropriate? Normally NCC look retrospectively at outcomes. Also, I am considering multiple outcomes, would it be suitable for that?
I also thought about the inverse probability weighting but I guess this approach shares majority of the weakness and strengths with the first. correct?
Any good reference would also be appreciated.
Answer: What you have described is not a case-control study, and it is very important to know that because the methods you would use to analyze a case-control study are different form what you would use to analyze a cohort study, which is what this is. In a case-control study, you perform selection on the outcome, which in your case is vascular events and mortality, and see how they differ with respect to the exposure, which in your case is whether they have the condition or not. What you described is a cohort study, in which you examine those with and without the exposure and see how they differ with respect to the outcome. A cohort study is more straightforward to analyze; you need to eliminate confounding and approximate a randomized control trial (or similar randomized design). To this end, matching, weighting, or regression-based methods work well.
With a sample this large, if possible, you should include all control units that bear any resemblance to the exposed units. You have the opportunity to perform an advanced statistical technique for causal effect estimation; in this case I would recommend targeted maximum likelihood estimation (TMLE), which combines regression and weighting and is easy to implement. You could also try Bayesian additive regression trees (BART), which has also proven to be highly effective and fairly easy to implement, but I'm not sure how it fares for survival outcomes.
If you do matching, make sure you try to retain as many control units as possible; throwing away a large percentage of your 1m control units would be disastrous. Kernel matching is popular but isn't prima facie better than other matching methods that optimize a criterion; check out other sophisticated methods such as FLAME (Fast Large-scale Almost Matching Exactly) and Zubizarreta's designmatch.
Weighting (i.e., with entropy balancing or similar optimization-based approaches)would also be effective. Whatever you do, make sure you include as many pre-exposure covariates as possible and incorporate highly flexible models that attempt to balance on many functions of the covariates. With sample sizes that large, the effect of bias will be larger than most decreases in precision.


Bias and Variance term, in regards to bias Neural Network

Question: I have recently been working with ANN, where I have come to the term of bias, which from my understanding is a constant value being added to the summation of weights and activation of previous neurons during training and backpropagation.
Previously I have introduced to the term bias and variance, in regards to Linear Regression, where Variance was described as the term, of the different fits from training data and testing data. Whereas low bias, meaning, that the model is not overfitting, and can handle different types of training samples.
Am I confusing these terms?
Answer: You're conflating two usages of bias.
In the neural networks literature, "bias" is sometimes used to refer to adding a constant to a neuron.
In the broader statistical literature, "bias" (of an estimator) is used to describe the difference between an estimator's expected value and its true value. https://en.wikipedia.org/wiki/Bias_of_an_estimator


How to prove that all primes of the form $4k+1$ can be represented by the sum of two squares in only one way regardless of the order?

Question: I am reading a book about Number Theory as a new learner.
The book has proved that all primes of the form $4k+1$ can be represented by the sum of two squares.
This question is given as exercise and I truly have no idea for the solution.
The only thing that I found may be helpful is that one of the squares is even and one is odd.
Thanks for any help ^_^

Edit: About duplication, I suppose that question is about the process in a specified proof.
Will Jagy has given a complete proof.
Thanks so much for the answer!
Comment: Look here : https://proofwiki.org/wiki/Fermat%27s_Two_Squares_Theorem
Comment: It would help to know what sort of proof the book gave of the existence.  For example, if it's based on the fact that the Gaussian integers $\mathbb{Z}[i]$ are a PID, then the uniqueness just follows from the fact that if $a^2 + b^2 = p$ is prime then $a+bi$ is irreducible in $\mathbb{Z}[i]$.  So if $c^2 + d^2 = p$ also then $c+di$ must be a unit times either $a+bi$ or $a-bi$...
Answer: Let us have positive integers with $$  n = a^2 + b^2 = c^2 + d^2  $$ with $a,c$ odd, then $b,d$ even, also $b < d$ and $a > c.$ So these are two genuinely distinct ways of writing $n.$
$$ (a-c)(a+c) = (d-b)(d+b). $$
Define $$ r = \gcd(a-c, d-b)  $$
Note that $r$ is even. Next we define
$$ a-c = rs \; , \; \; \;  d-b = r t \; , $$ so that
$$ \gcd(s,t) = 1. $$
Note that at least one of $s,t$ is odd. This gives us
$$ (a+c)s = (d+b)t. $$
The gcd property tells us that $t | (a+c).$ We define $u$ with
$$ a+c = t u. $$ We immediately conclude $d+b = s u.$ As $a+c, d+b$ are even, but at least one of $s,t$ is odd, we find $u$ is even.
In one line,
$$ \color{magenta}{ a-c = rs \; , \; \;  a+c = tu \; , \; \;  d-b = rt \; , \; \;  d+b = su \; }.   $$
If we now solve for $a$ and $b$ and square and combine, we get
$$  a = \frac{1}{2}(rs+tu) \; , \; \; \;   b = \frac{1}{2}(su-rt) \; , $$
$$ a^2 + b^2 = \frac{1}{4}\left( r^2 s^2 + r^2 t^2 + u^2 s^2 + u^2 t^2\right) = \frac{1}{4}\left( r^2 + u^2 \right) \left( s^2 + t^2 \right)\; , $$
$$ \color{magenta}{ n = a^2 + b^2 = c^2 + d^2 = \left( \left(\frac{r}{2}\right)^2 +\left(\frac{u}{2}\right)^2  \right) \left(s^2 + t^2 \right) } . $$
That is to say, because $n$ had two distinct representations as the sum of two squares, it is composite.
The contrapositive is that a number $4k+1$ with just one expression as the sum of two nonzero squares is prime. It is probably worth pointing out that this is the contrapositive in the setting of having at least one representation. We are not making any conclusions about numbers that have no representation as the sum of two squares.
Comment: Did you mean converse in the last sentence?  Note that for example, 9 has essentially only $3^2 + 0^2$ as a representation as a sum of two squares, yet 9 is not prime.
Comment: @DanielSchepler I will need to think about it. What I wrote is just about two representations with nonzero $a,b,c,d,$ so is silent about some issues.


Hidden functions in cells

Question: I have an Excel form with some hidden functions. I'm not an Excel person so I'm translating it into another program code but I need help in understanding how Excel converts dates and time to make an arithmetic operations.
Here is an example:
<code> Cell B5: 11/9/12
 Function
     =B5                =0.1/24           =D2+2415018.5+E2-$B$5/24
 D2: 11/9/12    E2: 0:06:00   F2: 2456240.96
</code>
So my problem is that I don't understand how Excel coverts D2 and E2 in the equation:
D2+2415018.5+E2-$B$5/24 so that I can write it in python code.
Would appreciate some clarification please!
Answer: I don't follow your example, but what you need to know is that Excel stores dates as the number of days since January 0, 1900 (not a typo). An hour is 1/24 of a day, a minute is 1/24/60, etc. See this for more.
Comment: +1 was about to type the same - `1.99999999` would equal `1.1.1900 23:59:59,999`
Comment: @A. Webb - Hi, I tried to calculate the number of days since 1900-1-1 and what Excel writes as the representation of 6/21/10 = 40350.0. In python I cannot represent 1900-1-0 so I added one day but still come up a with 40349. What am I missing here?
Comment: @Shejo284 What you are missing is February 29, 1900, a non-existent date since 1900 was not a leap year, which is a "feature" of Excel. This is described in the second paragraph under "Dates" of the article I linked to.
Comment: @A.Web Yes, you are right. I needed to add 2. Can I ask another question: in a cell E2 there is 12:00:00 and this is used in a arithmetic function E2*5.0. What is the value of E2 here? How do I convert 12:00:00? to a scalar?
Comment: @Shejo284 Each hour past midnight is 1/24 of the day, a day being 1. So noon would be 1/2 of the day or 0.5.

Hidden functions in cells


Powershell - Can you use a custom object type contraint for function parameters?

Question: I have a function defined as follows:
function Get-LatestProjects
{
    [CmdletBinding()]
    Param
    (
        [Parameter(ValueFromPipeline = $true, Position = 0)]
        [Company.Project.Entities.Project[]] $Projects
    )
    Begin {}
    Process
    {
        ...
    }
    End {}
}

I'm calling this function from C# and the parameter in the code is an array of that type, but I'm getting this error:

Cannot process argument transformation on parameter 'Projects'. Cannot convert the "Company.Project.Entities.Project[]" value of type "Company.Project.Entities.Project[]" to type "Company.Project.Entities.Project".

The C# code that makes the call:
var script = @". \\server01\Runspace.ps1; Get-LatestProjects $args";
var args = _pmRepository.GetAllProjects().ToArray(); // GetAllProjects returns List<Project>

using (Runspace runSpace = RunspaceFactory.CreateRunspace())
{
    runSpace.Open();
    var ps = PowerShell.Create();
    ps.Runspace = runSpace;
    ps.AddScript(script);
    ps.AddArgument(args);

    Collection<PSObject> results = ps.Invoke();
    ...
}

Do I need to do any conversion of the objects before I pass them to the powershell function?  Or can I not add a type constraint in the powershell function for the $Projects parameter?
Answer: It looks like _pmRepository.GetAllProjects() return only one project. Can't you just declare $Projects without type and use $Projects.gettype to have a look to the type.
function Get-LatestProjects
{
    [CmdletBinding()]
    Param
    (
        [Parameter(ValueFromPipeline = $true, Position = 0)]
        $Projects
    )
    Begin {
       #Set-Content -path c:\temp\debug.txt -value $Projects.Gettype()
       $projects | get-member -force | out-file -filepath c:\temp\debug.txt
    }
    Process
    {
        for ($i=0 ; $i -le $projects.count ; $i++)
        {
           $projects[$i].State  | out-file  -filepath c:\temp\debug.txt -append
        }
    }
    End {}
}

----Edited------
You can avoid your array to be wraped into another array by writting.
var script = @". \\server01\Runspace.ps1; Get-LatestProjects $args[0]";

Comment: I Edit answer to continue debug
Comment: TypeName: Company.Project.Entities.Project[]

Name               MemberType    Definition
----               ----------    ----------
Count              AliasProperty Count = Length
pstypenames        CodeProperty  System.Collections.ObjectModel.Collection`1[...
psadapted          MemberSet     psadapted {Length, LongLength, Rank, SyncRoo...
psbase             MemberSet     psbase {Length, LongLength, Rank, SyncRoot, ...
psextended         MemberSet     psextended {Count} ...
Comment: I Edit answer to continue debug
Comment: I added $Projects.Count to the Begin block and it's showing 1.  I know for a fact that the array I'm passing in has 2082 items in it, I verified it.  When I run your updated code I get `Property 'State' cannot be found on this object. Make sure that it exists.`
Comment: So try to retreive the type of $projects[0] with Get-Member
Comment: I was able to get at all the Project's by looking at $Projects[0].  I'm not sure why it wrapped it inside another array.


Advice extracting //td text and numbers

Question: I have been working through the tutorial adapting it to a project I want to achieve. I seem to have something going wrong that i just can't find the error to.
When using 'scrapy shell' I can get the response I expect. So for this site Nrl Ladder
In [1]: hxs.select('//td').extract()
Out[1]:
[u'\r\n
\r\n

Home
\r\n
NRL
\r\n
NYC
\r\n
Rep Matches
\r\n\r\n

\r\n	',
 u'Round 4	',
 u'Updated: 26/3/2012	',
 u'1. Melbourne	',
 u'4	',
 u'4	',
 u'0	',
 u'0	',
 u'0	',
 u'122	',
 u'39	',
 u'83	',
 u'8	',
 u'2. Canterbury-Bankstown	',

And on it goes.
I am really struggling to understand how to alter the tutorial project to change it to a different data type.
Is there anyway to bring up a help or documentation list to see what types I should use in items when using 'td' or any other item. Like i say it works easy in the shell but I cannot transform it to the files. Specifically both the team names and the points are 'td' but the team name is text.
here is what I have done.
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector

from nrl.items import NrlItem

class nrl(BaseSpider):
    name = "nrl"
    allowed_domains = ["http://live.nrlstats.com/"]
    start_urls = [
        "http://live.nrlstats.com/nrl/ladder.html",
        ]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        sites = hxs.select('//td')
        items = []
        for site in sites:
           item = nrlItem()
           item['team'] = site.select('/text()').extract()
           item['points'] = site.select('/').extract()
           items.append(item)
        return items

Comment: Have you tried BeautifulSoup? It is a bit more manual, but you might be able to get a bit more control that way
Comment: No not yet but maybe if this doesn't work I will.
Comment: @PreetKukreti it turns out that scrapy can use beautifulsoup as well http://doc.scrapy.org/en/latest/topics/spiders.html
Answer: I didn't quite understand your question, but here is a starting point, imo (haven't tested; see some comments in the code):
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector

from nrl.items import NrlItem

class nrl(BaseSpider):
    name = "nrl"
    allowed_domains = ["live.nrlstats.com"] # domains should be like this
    start_urls = [
        "http://live.nrlstats.com/nrl/ladder.html",
        ]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        rows = hxs.select('//table[@class="tabler"]//tr[starts-with(@class, "r")]') # select team rows
        items = []
        for row in rows:
           item = nrlItem()
           columns = row.select('./td/text()').extract() # select columns for the selected row
           item['team'] = columns[0]
           item['P'] = int(columns[1])
           item['W'] = int(columns[2])
           ...
           items.append(item)
        return items

UPDATE:
//table[@class="tabler"//tr[starts-with(@class, "r")] is an xpath query. See some xpath examples here.
hxs.select(xpath_query) always returns a list of nodes (also of type HtmlXPathSelector) which fall under the given query.
hxs.extract() returns string representation of the node(s).
P.S. Beware that scrapy supports XPath 1.0, but not 2.0 (at least on Linux, not sure about Windows), so some of the newest xpath features might not work.
See also:

http://doc.scrapy.org/en/latest/topics/selectors.html
http://doc.scrapy.org/en/latest/topics/firefox.html
Comment: This is an xpath question, not related to scrapy. I don't think scrapy docs have this. See my update. I have also added [tag:xpath] tag to your question.
Comment: how do I find extra info on stuff like this line rows = hxs.select('//table[@class="tabler"//tr[starts-with(@class, "r")]') from the tutorial its not obvious thats what I would do.
Comment: I receive this error with the Xpath selector   raise ValueError("Invalid XPath: %s" % xpath)
 exceptions.ValueError: Invalid XPath: //table[@class="tabler"//tr[starts-with(@class, "r")]
Comment: sorry, forgot one closing `]`: `//table[@class="tabler"]//tr[starts-with(@class, "r")]`

Advice extracting //td text and numbers


Mostrar div apenas após checar 3 radio buttons

Question: Estou com um problema que não consigo resolver.
Preciso que uma div seja mostrada APENAS após 3 radio buttons forem checados, mas não está funcionando. Eu só estou conseguindo com uma opção só, mas tem que ser os 3 de uma vez e só depois de marcar os 3 é que tem que aparecer a div.

$(function() {
    $('.control').on('click', function(){
        var n1 = $('#profissional-nao:checked');
        var n2 = $('#institucionalizada-nao:checked');
        var n3 = $('#indigena-nao:checked');

        if(n1.length > 0 && n2.length > 0 && n3.length > 0) {
            document.getElementById("fase-dois").style.display = 'block';
        } else {
            document.getElementById("fase-dois").style.display = 'none';
        }
    });
});

    Profissional de Saúde:

    <input id="profissional-sim" name="{$q2_name}" type="radio" value="Sim" checked="" class="form-control"> Sim
    <input id="profissional-nao" name="{$q2_name}" type="radio" value="Não" class="form-control control"> Não

    Pessoa Institucionalizada?:

    <input id="institucionalizada-sim" name="{$q3_name}" type="radio" checked="" value="Sim" class="form-control"> Sim
    <input id="institucionalizada-nao" name="{$q3_name}" type="radio" value="Não" class="form-control control"> Não

    Poulação Indigena ou em Terras Demarcadas?:

    <input id="indigena-sim" name="{$q4_name}" type="radio" value="Sim" checked="" class="form-control"> Sim
    <input id="indigena-nao" name="{$q4_name}" type="radio" value="Não" class="form-control control"> Não

teste

Answer: Como mencionado por @anthony-accioly você precisa escutar o clique de todos os inputs para reavaliar a cada clique deles.
Passos:

Dá para fazer isso, por exemplo, adicionado a classe .control também aos inputs 'sim'
Separar em funções para não ficar repetitivo
Avaliar ao carregar da página se deve mostrar ou não (opcional)

Link para codepen

$(function() {
    function isAllChecked () {
        // jQuery retorna um array com o element em si no index 0 (primeira posição)
        // Abaixo é array destructure para captar o primeiro item do array
        var [input1] = $('#profissional-nao');
        var [input2] = $('#institucionalizada-nao');
        var [input3] = $('#indigena-nao');

        // Checka se todos (e somente se todos) os inputs do array estão checked
        // Se sim, retorna true, se um ou mais não estiver, retorna false
        return [input1, input2, input3].every(
            (input) => input.checked
        );
    }

    // Elemento a ser mostrado / escondido
    var element = $("#fase-dois");

    // Checar se todos estão marcados nao a cada clique
    // e mostrar / esconder elemento a partir da resposta de isAllChecked()
    $('.control').on('click', function() {
        // Usar método toggle passando true ou false
        // sendo true mostra o elemento e vice-versa
        element.toggle(isAllChecked());
    });

    // Opcional: Checar se já está marcado tudo em nao ao carregar a página
    // e mostrar a div caso positivo
    $(document).ready(function() {
        element.toggle(isAllChecked());
    });
});

    Profissional de Saúde:

    <input id="profissional-sim" name="{$q2_name}" type="radio" value="Sim" checked="" class="form-control control"> Sim
    <input id="profissional-nao" name="{$q2_name}" type="radio" value="Não" class="form-control control"> Não

    Pessoa Institucionalizada?:

    <input id="institucionalizada-sim" name="{$q3_name}" type="radio" checked="" value="Sim" class="form-control control"> Sim
    <input id="institucionalizada-nao" name="{$q3_name}" type="radio" value="Não" class="form-control control"> Não

    Poulação Indigena ou em Terras Demarcadas?:

    <input id="indigena-sim" name="{$q4_name}" type="radio" value="Sim" checked="" class="form-control control"> Sim
    <input id="indigena-nao" name="{$q4_name}" type="radio" value="Não" class="form-control control"> Não

teste

Answer: Você pode modificar seu código de modo que o if fique da seguinte forma:
if(document.getElementById('id-radio-1').checked && document.getElementById('id-radio-2').checked && document.getElementById('id-radio-3').checked){
      document.getElementById("fase-dois").style.display = 'block';
}else{
      document.getElementById("fase-dois").style.display = 'none';
}

Lembrando que precisa modificar também o HTML para que os id's correspondam.
Comment: Obrigada pela sua respostas, mas ainda não tá funcionando. Devo estar fazendo algo errado.

$(function() {

    $('.control').on('click', function(){

        if(document.getElementById('profissional-nao').checked && document.getElementById('institucionalizada-nao').checked && document.getElementById('indigena-nao').checked){
         document.getElementById("fase-dois").style.display = 'block';
  }else{
        document.getElementById("fase-dois").style.display = 'none';
  };
    });
});
Answer: A única alteração que precisei fazer no seu código para que ele funcione foi alterar o binding  do event handler click para trabalhar com a classe form-control (e assim tratar cliques de todos os radio buttons):
$(function() {
    $('.form-control').on('click', function(){
        var n1 = $('#profissional-nao:checked');
        var n2 = $('#institucionalizada-nao:checked');
        var n3 = $('#indigena-nao:checked');

        if(n1.length > 0 && n2.length > 0 && n3.length > 0) {
            document.getElementById("fase-dois").style.display = 'block';
        } else {
            document.getElementById("fase-dois").style.display = 'none';
        }
    });
});

Veja funcionando no JSFiddle.
É importante escutar por eventos de click em todos os radio buttons para esconder a div caso alguma opção seja trocada de Não para Sim.
Comment: Obrigada!! Funcionou!


Unable to Create Terraform Resource Group when using modules

Question: I am optimizing my terraform code by using modules. When i create a resource group module it works perfectly well but it creates two resource groups
i.e.

Temp-AppConfiguration-ResGrp
Temp-AppServices-ResGrp

instead it should only create
Temp-AppConfiguration-ResGrp
Code Resourcegroup.tf.
resource "azurerm_resource_group" "resource" {
  name     = "${var.environment}-${var.name_apptype}-ResGrp"
  location = var.location
  tags = {
    environment = var.environment
  }
}
output "resource_group_name" {
  value = "${var.environment}-${var.name_apptype}-ResGrp"
}

output "resource_group_location" {
  value = var.location
}

Variable.tf
variable "name_apptype" {
  type    = string
  default = "AppServices"
}
variable "environment" {
  type    = string
  default = "Temp"
}
variable "location" {
  type    = string
  default = "eastus"
}

Main.tf
 module "resourcegroup" {
  source = "../Modules"
  name_apptype = "AppConfiguration"
}

I want to pass name_apptype in main.tf when calling resource group module. So that i don't need to update variable.tf every time.
Any suggestions
where i am doing wrong. Plus i am also unable to output the value, i need it so that i could pass resource group name in the next module i want to create.
Thanks
Comment: code is fine, how are you executing terraform? and where is main.tf? What did you plan show?
Answer: You need to do that in the Main.tf
module "resourcegroup" {
  source = "../Modules"
  name_apptype = "AppConfiguration"
}

module "resourcegroup-appservices" {
  source = "../Modules"
  name_apptype = "AppServices"
}

These create a 2 resources groups with the values that you need, additionally you can remove the default value from the name_apptype variable.
If you want to create with the same module both resource groups you need to use count to iterate over an array of names
Comment: Carlos  It didn't work. Let me clear my problem statement

i want to override name_apptype  value when creating a resource group. But with my current code it doesn't override it instead it creates two resource groups. one with default value and other with value passed.
I want to create resource group with only value passed through module.


Running Job and Paused Job Writing to the same File

Question: So I ran tcpdump twice overnight by accident, both outputting to the same file.  However, I ran them as jobs and one of them has been paused the whole time.  Anyone have a recommendations on how to keep the file? So far I have thought of:

kill -9 the paused job
Pause the running job, copy the file, and then stop both.

Two sounds like the safest option, anyone have a better idea other than not doing this in the first place ;-)
Comment: I vote for option #2
Answer: I'd make a backup of the file just in case, better to be safe than sorry!


nginx + PHP-FPM disable PHP functions only for certain virtual hosts

Question: How can I disable some php functions only for some of(currently only 1) virtualhosts on my Nginx+PHP-FPM stack?
Comment: Which PHP functions? What is your current nginx configuration?
Answer: You can make a separate pool for your host and put restricted functions in there like this (on the last line):
[example.com]
listen = 127.0.0.1:9001
listen.allowed_clients = 127.0.0.1
user = web1
group = client0
pm = dynamic
pm.max_children = 50
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35
chdir = /
php_admin_value[open_basedir] = /var/www/www.example.com:/usr/share/php5:/tmp:/usr/share/phpmyadmin:/etc/phpmyadmin:/var/lib/phpmyadmin
php_admin_value[disable_functions] = dl,exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source

Answer: Its spelt out in the manual page on setting up process pools - use environment vars to append to the disable_functions ini setting.
Answer: In fact, seems it can't.
disable_functions can only be set in php.ini (PHP_INI_SYSTEM).
Although the PHP pool from FPM seems like a separate procces - see https://supportex.net/blog/2012/02/lemp-disabling-php-functions/
Comment: It's possible to add (they are appended to the list from php.ini) custom disabled functions in FPM pool configuration like described at https://www.php.net/manual/en/install.fpm.configuration.php


STM32L47x GPIO register config

Question: I'm trying to blink LED on my ST board B-L475E-IoT01A1 (basically STM32L475). LED2 is connected tp PB14. To enable GPIOB, I have to enable AHB2 bus (RCC->AHB2ENR).

Than I Configured GPIO port mode to General Purpose output mode (GPIOB->MODE)

than port output type (GPIOB->OTYPER)

than outputspeed (GPIOB->OSPEEDR)

than port pull-up/pull-down (GPIOB->PUPDR)

finally bit set and reset register (GPIOB->PUPDR)

I have attached my code below, I don't know what I have done wrong, my LED2 is not blinking.
#include "stm32l4xx_hal.h"

void Delay (uint32_t time)
{
    while (time--);
}

int main()
{
    RCC->AHB2ENR |= (1<<1);
    GPIOB->MODER |= (1<<28);
    GPIOB->OTYPER &= ~(1<<14);
    GPIOB->OSPEEDR |= (1<<29);
    GPIOB->PUPDR &= ~((1<<28) | (1<<29));

  while(1)
  {
      GPIOB->BSRR = (1<<14);
      //for(int i =0; i<=50000; i++) ;
      Delay(10000000);
      GPIOB->BSRR = (1<<14+16);
      Delay(10000000);
      //for(int i =0; i<=50000; i++) ;
  }
}

Thank you for your help.
Comment: Does the LED turn on at all?  Are you sure about the operator precedence of `(1<<14+16)`?  Does the LED toggle when you single-step through the code with the debugger?  Does the `Delay()` function work as you intend and actually delay?
Comment: No, the LED do not turns ON. I also tried (1<<30), but no luck. sorry the operator is suppose to be (1<<(14+16)). Yes, I tried break on GPIOB->BSRR = (1<<14); no luck. I took the delay function from an example, I also tried delaying with for loop. I dont know what I'm missing.
Comment: It is a poor example.  You should use SYSTICK, or at least declare `time` `volatile`: `void Delay (volatile uint32_t time)`
Comment: You have included the HAL but not used it (or initialised it).  The HAL has a delay function BTW.  Although personally I'd avoid the HAL - not ST's finest offering.  Here you only need "stm32l4xx.h"
Comment: You should never use `1<<` in C. In your case `1<<31` would invoke undefined behavior. Always use `1u <<`.
Answer: I was up to write 01 to GPIOB->MODER [29:28].
So I've added
GPIOB->MODER &= ~(1<<29);

before
GPIOB->MODER |= (1<<28);

This solves my problem.
Btw: in my code a for loop works better for a delay than the delay(...) function.

STM32L47x GPIO register config


Causal inference - difference between blocking a backdoor path and adding a variable to regression

Question: I have just started this introductory course to causal inference. The DAG approach is completely new to me even though I come from an econometric background (though that dates back to 15 years ago).
The discussion around confounders reminds me of the endogeneity problem in econometrics, especially when confounders are unmeasured (e.g. omitted variable bias). In this case, I remember instrumental variables to be a workaround strategy, and explaining IV with DAGs makes a lot more sense!
However, the prefered strategy with DAGs seems to be blocking backdoor paths by conditioning on confounders (which will allow the ignorability assumption $(Y^{0}, Y^{1} \perp A|X)$ to be valid). I am wondering how blocking a path from a confounder is actually different from including those confounder in the regression?
For simplicity, suppose we have this DAG :

I would believe that if $X$ (the confounder) is measured in addition to $A$ (the treatment), then regressing $Y$ (the outcome) on both variables would lead to correct estimates (supposing we are using the correct regression function).
Am I wrong?
Answer: You're not wrong. Including $X$ in the regression is typically how you condition on a variable in the regression setting. There are other ways to condition (stratify, backdoor adjustment, frontdoor adjustment, and instrumental variables).
Comment: Just want to add that propensity score methods do this too!
Comment: Is there a rule of thumb indicating which method is superior to another (or maybe given enough context)? I have recently encountered this statement suggesting to ban matching: "Much has been written about [propensity matching and] why it's terrible and how it will lead to wrong estimates. If you can compute propensity scores, you can use inverse propensity weighting instead." (see https://towardsdatascience.com/beyond-a-b-testing-primer-on-causal-inference-d8e462d90a0b).


Fuglede's theorem in finite-dimensional vector space

Question: Let $V$ be a finite dimensional vector space and $A$ be normal operator on $V$ and $B$ is an operator such that $AB=BA$. Show that $BA^*=A^*B$.
I guess that this problem should not be so difficult. I have tried different approaches and I got some identities which do not lead to desired equality.
So I would be thankful if you show the solution to this problem, please!
Comment: have you tried explicitly using the commuting polar decomposition from your last post?  https://math.stackexchange.com/questions/3611748/commuting-operators-in-polar-decomposition-of-normal-operator
Comment: @user8675309, no to be honest.
Comment: I dont think that it will work.
Comment: I tried to use the previous problem but i failed.
Comment: See also [this post](https://math.stackexchange.com/q/675239/81360)
Answer: The way to think about this problem is when $B$ is diagonalizable, and $A$ being normal is diagonalizable (over $\mathbb C$) so we can call on simultaneous diagonalizability, recognize that being normal $A^*$ may also be simultaneously diagonalized with $B$ (via the same similarity transform that we'd use on $AB$)  which implies that $A^*B = BA^*$.  However it is  conceivable that $B$ might be defective-- so a more direct argument can be employed to compute the norm of the commutator
$\Big\Vert  A^*B - BA^*\big\Vert_F^2$
$=\text{trace}\Big(\big(A^*B - BA^*\big)^*\big(A^*B - BA^*\big)\Big)$
$=\text{trace}\Big(\big(B^*A - AB^*\big)\big(A^*B - BA^*\big)\Big)$
$=\text{trace}\Big(B^*AA^*B\Big) + \text{trace}\Big(AB^*BA^*\Big)- \text{trace}\Big(B^*ABA^*\Big) -\text{trace}\Big(AB^*A^*B\Big) $
$=\text{trace}\Big(AA^*BB^*\Big) + \text{trace}\Big(B^*BA^*A\Big)- \text{trace}\Big(B^*ABA^*\Big) -\text{trace}\Big(BAB^*A^*\Big) $
$=\text{trace}\Big(AA^*BB^*\Big) + \text{trace}\Big(B^*BA^*A\Big) - \text{trace}\Big(B^*BAA^*\Big) -\text{trace}\Big(ABB^*A^*\Big)$
$=\text{trace}\Big(AA^*BB^*\Big) + \text{trace}\Big(B^*BA^*A\Big) - \text{trace}\Big(B^*BAA^*\Big) -\text{trace}\Big(A^*ABB^*\Big)$
$=\text{trace}\Big(AA^*BB^*\Big) + \text{trace}\Big(B^*BA^*A\Big) - \text{trace}\Big(B^*BA^*A\Big) -\text{trace}\Big(AA^*BB^*\Big)$
$=0$
thus by positive definiteness of the (squared) Frobenius norm we have
$\Big\Vert  A^*B - BA^*\big\Vert_F^2 = 0 \longrightarrow A^*B - BA^* = \mathbf 0\longrightarrow A^*B = BA^*$
Comment: I guess that I got you reasoning almost completely. Am I right that when you wrote $\text{trace}(B^*AA^*B)=\text{trace}(AA^*BB^*)$ you used that $\text{trace}(CD)=\text{trace}(DC)$, right?
Comment: right.  The idea here is we have 4 matrices and the manipulations allowed are (i) cyclic property of trace, (ii)$AB = BA$, (iii)$B^*A^* = A^*B^*$, (iv) $AA^* = A^*A$... we always have (i) but $\{\text{ii, iii, iv}\}$ are special features of your problem.
Comment: I am not so familiar with norm of an operator. Could you explain what is Frobenius norm? And why it can be calculated as a trace? Would be nice if you can give details about that
Comment: Am I right that $\Big\Vert A \Big\Vert_F^2=\Big\Vert C^{-1}AC\Big\Vert_F^2$ where $C$ is non-singular matrix? If its true how to prove it?
Comment: your second question is incorrect, just try a few example.  Your first question... I assume that you know what the 2 norm of a vector is -- the Frobenius norm is the natural generalization of said 2 norm to matrices *if you view matrices as living in a vector space*.  In any case the Frobenius norm is induced by an inner product and easy to work with.   $\mathbf A =
\bigg[\begin{array}{c|c|c|c|c}
\mathbf a_1 & \mathbf a_2 &\cdots & \mathbf a_{n-1} & \mathbf a_{n}
\end{array}\bigg]$.
Comment: if the norm of operator depends on the basis how are you defining the norm then? Could you give more details, please?
Comment: $\Big \Vert A\Big \Vert_F = \big(\sum_{i=1}^m\sum_{j=1}^n \vert a_{i,j}\vert^2 \big)^\frac{1}{2} $  $= \big(\sum_{k=1}^n \big \Vert \mathbf a_k\big \Vert_2^2\big)^\frac{1}{2}   $ $=\Big(\text{trace}\big(A^*A\big)\Big)^\frac{1}{2}$.  To be honest I find it extremely hard to believe that you are unfamiliar with the Frobenius norm of a matrix, because you are asking about *normal matrices* and a common way of *defining them* is $\big \Vert \mathbf A \big \Vert_F^{2}   \geq \sum_{i = 1}^{n} \big \vert \lambda_i\big \vert ^2$ and a matrix is normal *iff* that is met with equality (due to Schur)
Comment: it is common to choose an orthonormal basis
Comment: So the norm of operator depends on the basis? I am a bit confused.
Comment: For purposes of this problem --it's actually the other way around -- a matrix is isn't normal under arbitrary change of basis.  Your questions echo this one: https://math.stackexchange.com/questions/3542129/are-unitary-matrices-still-unitary-under-similarity-transformations/3542169 where unitary matrices are a special case of normal.  To be honest the way 'choice/change of basis' is being used is abusive here... being normal corresponds much more with bilinear forms than linear maps (i.e. effecting congruence transforms instead of similarity transforms).  I think you have some reading to do.
Comment: Thanks a lot! I got your solution completely! Really nice reasoning!  I realized that Frobenius norm is the norm generated from usual inner product on the space of matrices, i.e. $(A,B):=\text{trace}(A^*B)$. I accept your answer as the best! How did you come up with this?
Comment: another way of characterizing normality of $A$ is $\text{trace}\Big(\big(A^* A\big)^2 \Big) \geq  \text{trace}\Big(\big(A^2\big)^* \big(A^2\big)  \Big)$ with equality *iff* $A$ is normal.  It's a worthwhile exercise to prove this to yourself; (a) one approach is compute $\big \Vert \mathbf A^* \mathbf A - \mathbf {AA}^* \big \Vert_F^2 $ (b) a  nicer approach comes from Cauchy-Schwarz (try it).  For your problem I kept trying to prove the result via use of Cauchy-Schwarz in the spirit of (b) but I hit too many dead ends and decided instead to imitate (a)
Answer: This is Fuglede's theorem. From the spectral theorem, $A$ can be written as
$$A=\sum_{i=1}^{n}\lambda_iP_i,$$
and $A^{*}$ can be expressed similarly by replacing $\lambda_i$ by its conjugate. Now, notice that for $p_i(x)=x\prod_{j : \lambda_j \neq \lambda_i}(x-\lambda_j)$
$$p_i(A)=\sum_{j=1}^{n}p_i(\lambda_j)P_j=\lambda_i\prod_{j : \lambda_j \neq \lambda_i}(\lambda_i-\lambda_j)\sum_{j : \lambda_j=\lambda_i}P_j.$$
(The first equality is a generalization of the fact that $A^k = \sum_{i=1}^{n}\lambda_i^kP_i$.) This implies that
$$\lambda_i\sum_{j : \lambda_j=\lambda_i}P_j=\frac{p_i(A)}{\prod_{j : \lambda_j \neq \lambda_i}(\lambda_i-\lambda_j)}.$$
Given that A and B commute, we have that $p_i(A)$ and $B$ also commute. So,
$$\lambda_i\sum_{j : \lambda_j=\lambda_i}BP_j=\lambda_i\sum_{j : \lambda_j=\lambda_i}P_jB,$$
and by replacing $\lambda_i$ with its conjugate and summing over all distinct eigenvalues we get that $BA^{*}=A^{*}B$.
Comment: You applied spectral theorem to $A$. But in my lectures spectral theorem is proved for self-adjoint operators. Our $A$ may not be self-adjoint.
Comment: The spectral theorem applies more generally to normal matrices.