How to plot a decision boundary for binary logistic regression in matlab

Question: let me preface by saying this is from a homework question, but the question is not to plot the decision boundary, just to train the model and do some predictions. I have already done that and my predictions seem to be correct.
But I would like to verify my results by plotting the decision boundary. This is not part of the homework.
The question was to take a simple dataset $$ X = \begin{bmatrix}
-1&0&2&0&1&2\\
-1&1&0&-2&0&-1
\end{bmatrix} $$
$$ y = \begin{bmatrix}
1&1&1&-1&-1&-1
\end{bmatrix}
$$
Given this, convert the input to non-linear functions:
$$
z = \begin{bmatrix}
 x_1\\x_2\\x_1^2\\x_1x_2\\x_2^2
\end{bmatrix}
$$
Then train the binary logistic regression model to determine parameters $\hat{w} = \begin{bmatrix} w\\b \end{bmatrix}$ using $\hat{z} = \begin{bmatrix} z\\1 \end{bmatrix}$
So, now assume that the model is trained and I have $\hat{w}^*$ and would like to plot my decision boundary $\hat{w}^{*T}\hat{z} = 0$
Currently to scatter the matrix I have
scatter(X(1,:), X(2,:))
axis([-1.5 2.5 -2.5 1.5])
hold on
% what do I do to plot the decision boundary?

Not sure where to go from here. I have tried using symbolic functions, but fplot doesn't like using 2 variables.
Answer: I could plot it using the following code:
syms X Y y

X = [-1 -1; 0 1; 2 0; 0 -2; 1 0; 2 -1]
Y = [1 1 1 -1 -1 -1]
y = categorical(Y)
B = mnrfit(X,y)

scatter(X(:,1),X(:,2))
hold on
plot(X(:,1),-((B(1)*1+B(2)*X(:,1))/B(3)));
axis([-1.5 2.5 -2.5 1.5])
hold off

Note that I needed to change the $y$ values to categorial values (internally, these are positive integers), since mnrfit required this. But it has no influence on our decision problem.
The result is:
Comment: Hi there, thanks for the reply. This plots a linear decision boundary, however the transformation in my question changes the parameters to be quadratic on the input.
Answer: I was able to plot the curve using ezplot:
X = [-1 0 2 0 1 2; -1 1 0 -2 0 -1];
P = length(X);
z = zeros(6, P);

for i = 1:P
    z(:,i) = z_calc(X(:,i));
end

syms x1 x2
z_fn = [x1; x2; x1^2; x1*x2; x2^2; 1];

% xs was previously computed by the logistic regression model
eqn = (xs'*z_fn == 0);

ezplot(eqn)
hold on
scatter(X(1,1:3), X(2,1:3), 'red')
axis([-1.5 2.5 -2.5 1.5])
hold on
scatter(X(1,4:6), X(2,4:6), 'blue')
title("Decision Boundary")
hold off


For which values of $k$ is there an $X$ with $\Omega^kX \cong X$?

Question: Bott periodicity can be formulated as $\Omega^2 U \cong U$ where $\Omega$ denotes the based loop space functor and $U$ is the direct limit of unitary groups. The real version can be formulated as $\Omega^8 O \cong O$ where $O$ is the direct limit of orthogonal groups.

Are there other spaces which are homotopy equivalent to an iterated loop space of themselves? For which values of $k$ is there an $X$ such that $\Omega^kX \cong X$ (but $\Omega^iX \not\cong X$ for $1 \leq i < k$)?
Answer: There are always such spaces, for silly reasons: you can take $X$ to be a periodic product of Eilenberg-MacLane spaces.
All of the natural examples I know have even period, though.
Comment: @Michael: there's a $4$-periodic spectrum called the L-theory spectrum that figures in surgery theory. There are also examples with periods like $2, 12, 24, 576$ coming from elliptic cohomology and related ideas.
Comment: Do you know of any 'natural examples' other than the ones I mentioned in the question?
Answer: Sure, it is easy to construct such spaces.  For instance, let $G$ be any nontrivial abelian group and let $X=\prod_{n=0}^\infty K(G,nk)$.  More generally, given a spectrum $Y$, you could define $X=\prod_{n\in\mathbb{Z}} \Omega^{\infty-nk}Y$ (though for general $Y$ that $X$ might by chance have a smaller period).
Comment: What do you mean by $\Omega^{\infty - nk}Y$?
Comment: That refers the $(nk)$th space of the $\Omega$-spectrum.  That is, if a spectrum $Y$ is a sequence of spaces $(Y_n)_{n\in\mathbb{Z}}$ together with equivalences $Y_n\to\Omega Y_{n+1}$, $\Omega^{\infty-nk}Y$ refers to $ Y_{nk}$.


Synchronizing threads in multithreaded applications

Question: I use the SIESTA dft package on a CentOS 8 (core) system with a 16 core, 32 thread XEON processor with OpenMPI version 4.1.1 for all calculations.

Since I have 32 threads, I use 28 of them to do a SIESTA calculation (which consumes a good amount of the memory ~60%) and keep the remaining 4 free.

However, if I start using 2 or 3 of the remaining threads for some other application (which has negligible memory usage), while maintaining the SIESTA calculation at 28 threads, I see that the speed of the SIESTA calculation is decreased by around 50-60%.

I have checked the CPU utilization and I see that one thread remains almost idle when using the system in scenario 2.

Is there a way to diagnose and solve this problem? Does this happen because of some process scheduling error? Can some sort of process binding or job scheduling package be used to improve this?
Answer: CPU utilization as a simple % cannot convey the complexity of a multiple core, multiple thread, multiple execution unit CPU and memory.  Almost certainly CPU is actually stalled on memory or cache.  And processes that do have their data will be fighting over execution units.

This CPU only has 16 cores. Treating it like it has 32 will at some point degrade performance severely, as you discovered. Even with SMT 2. Maybe you can get the number of threads to 125% of cores (20) but 175% (28) is pushing it. Especially with other things running.  Back down the threads.
Be sure to calculate useful work done per thread per second.  Experiment, changing one variable at a time. Maybe try processors with different cache and core count configurations, if you have access to those.

Measure how stalled you are with performance monitoring counters. Won't work in a VM, but worth a try on Linux. From Gregg which I linked earlier:
perf stat -a -- sleep 10

Theoretical top speed on Xeons is 4 or 5 instructions per cycle. You won't get that, but < 1.0 IPC is extra stalled on memory.

Definitely get an understanding of the application's code and hot spots. What functions spend most of the time on CPU? What assembly code gets hit the hardest? Which execution units on your CPU in particular are working the hardest to process these uops?
Flame graphs are nice for visualizing on CPU functions. You mentioned EL 8, which has packaged flamegraph tooling.
yum install perf js-d3-flame-graph
# system wide, 99 Hz, for 60 seconds
perf script flamegraph -a -F 99 sleep 60

A developer level understanding of the program is necessary to fully interpret the results. With symbols or source code, perf reports can be annotated in a debugger like experience.
Comment: Hi, thanks for the reply. I checked and my IPC was 0.97 so it seems the system is stalled on memory. However I have only this one system and so cannot check elsewhere. I shall check on the IPC changes by varying the number of cores used once the current running calculation ends (would probably take over a week).
Comment: What is your opinion regarding the `taskset` tool. Would it make any difference if I bind the SIESTA calculations to a set of cores and the other program to a separate core? Would that enable the given core to work with only one type of a workload?


Python (Regex: Replacing Every Character After a Single Letter)

Question: I'm looking to match all strings in a Pandas column. The strings are in a similar format.
9201 AVENUE B - GROUND FL REAR
56-58 AVENUE B STORE #2
9201 AVENUE B - GROUND FL REAR
1315 AVENUE C
431 WEST AVENUE D BASEMENT UNIT
12334 Avenue Z Store

Essentially I want to remove character after the single letter that follows "Avenue" (i.e. everything after Avenue C).
9201 AVENUE B
56-58 AVENUE B
9201 AVENUE B
1315 AVENUE C
431 WEST AVENUE D
12334 Avenue Z

I have this current code:
r"AVENUE\s([^A-Z].*)", ''

However, the code is failing to replace everything that comes after the letter. Any help would be appreciated. Thanks!
Comment: Use `re.sub(r"\b(AVENUE\s+[A-Z]).*", r"\1", text, flags=re.I)`
Comment: You're replacing everything, not just what comes after it.
Comment: Why do you have `^` in `[^A-Z]`. That prevents it from matching the letter after `AVENUE`.
Answer: You may use
re.sub(r"\b(AVENUE\s+[A-Z]).*", r"\1", text, flags=re.I)

See the regex demo and the Python demo:
import re
strs = ['9201 AVENUE B - GROUND FL REAR', '56-58 AVENUE B STORE #2', '9201 AVENUE B - GROUND FL REAR', '1315 AVENUE C', '431 WEST AVENUE D BASEMENT UNIT', '12334 Avenue Z Store ']
for s in strs:
    print(re.sub(r"\b(AVENUE\s+[A-Z]).*", r"\1", s, flags=re.I))
# => [9201 AVENUE B, 56-58 AVENUE B, 9201 AVENUE B, 1315 AVENUE C, 431 WEST AVENUE D, 12334 Avenue Z]

The pattern matches:

\b - a word boundary
(AVENUE\s+[A-Z]) - Group 1 (the value is referred to with the \1 placeholder from the replacement pattern):

AVENUE - a literal string
\s+ - 1+ whitespaces
[A-Z] - an ASCII letter

.* - any 0+ chars other than line break chars as many as possible.

NOTE: the re.I flag will make the [A-Z] case insensitive. To avoid that, use re.sub(r"\b((?i:AVENUE)\s+[A-Z]).*", r"\1", s), see this Python demo.
Comment: Works perfectly. I inputed it into my existing str.replace. Thank you so much. Was stuck on that for a bit .
Comment: Hi follow question if possible. i also have address like 888 Avenue Store. I want to keep the 888 Avenue but get rid of everything behind it. I've played around with the regex code but I ended up getting rid of the streets that I want to keep (i.e 9201 Avenue B ). How can I do both ?   I know moving the group () helps
Comment: @ynnad Use a word boundary, `r'\b(AVENUE\s+[A-Z])\b.*'`, see [demo](https://regex101.com/r/rggYK0/3)
Answer: Your regexp matches everything starting with AVENUE followed by a non-letter, and replaces all of that with the empty string. So it removes the whole thing when it matches.
You can use a lookbehind to match the remainder of the line when it's preceded by AVENUE <letter>, but not include that in the match.
re.sub(r"(?<=AVENUE [A-Z]).*", "", text)

Answer: With pandas you can do str replace
df[col].str.replace('((?<=AVENUE [A-Z]).*)', '')
0        9201 AVENUE B
1       56-58 AVENUE B
2        9201 AVENUE B
3        1315 AVENUE C
4    431 WEST AVENUE D
5       12334 AVENUE Z


Server overloaded with log messages: "tty_release_dev: pts0: read/write wait queue active!"

Question: In the logs, I have this (extract from the full kernel messages logges at 06:01:14):
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.863038] BUG: unable to handle kernel NULL pointer dereference at 0000000000000015
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861081] Process telnet (pid: 20247, threadinfo ffff8800f8598000, task ffff8800024d4500)

And then the server logs flooded by this message:
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861547] tty_release_dev: pts0: read/write wait queue active!

In the end, 2 hours later, I had to reboot because it had become inaccessible: the load hat grown to 160%.
The last command does not show anyone logged on pts0 at that time. I also don't know where this telnet process could come from.
This is an EC2 instance running UBUNTU 10.04 LTS.
And here are the complete logs:
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.863038] BUG: unable to handle kernel NULL pointer dereference at 0000000000000015
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861007] IP: [<ffffffff81363dde>] n_tty_read+0x2ce/0x970
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861019] PGD ee13d067 PUD f8698067 PMD 0
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861025] Oops: 0000 [#1] SMP
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861028] last sysfs file: /sys/devices/xen/vbd-2208/block/sdk/removable
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861032] CPU 0
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861034] Modules linked in: ipv6
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861040] Pid: 20247, comm: telnet Not tainted 2.6.32-312-ec2 #24-Ubuntu
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861042] RIP: e030:[<ffffffff81363dde>]  [<ffffffff81363dde>] n_tty_read+0x2ce/0x970
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861047] RSP: e02b:ffff8800f8599d88  EFLAGS: 00010246
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861049] RAX: 0000000000000015 RBX: ffff8800f8598000 RCX: 0000000001aed069
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861052] RDX: 0000000000000000 RSI: ffff8800f8599e67 RDI: ffff8801dd833d1c
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861054] RBP: ffff8800f8599e98 R08: ffffffff8135eb10 R09: 7fffffffffffffff
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861057] R10: 0000000000000000 R11: 0000000000000246 R12: ffff8801dd833800
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861059] R13: 0000000000000000 R14: ffff8801dd833a68 R15: ffff8801dd833d1c
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861065] FS:  00007f90121f6720(0000) GS:ffff880002c40000(0000) knlGS:0000000000000000
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861068] CS:  e033 DS: 0000 ES: 0000 CR0: 000000008005003b
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861070] CR2: 0000000000000015 CR3: 0000000032a59000 CR4: 0000000000002660
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861073] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861076] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861081] Process telnet (pid: 20247, threadinfo ffff8800f8598000, task ffff8800024d4500)
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861083] Stack:
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861085]  0000000000000000 0000000001aed069 ffff8801dd8339c8 ffff8800024d4500
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861089] <0> ffff8801dd8339c0 ffff8801dd833c90 0000000001aed027 ffff8800024d4500
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861094] <0> ffff8801dd8338d8 0000000000000000 ffff8800024d4500 0000000000000000
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861099] Call Trace:
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861107]  [<ffffffff81034bc0>] ? default_wake_function+0x0/0x10
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861113]  [<ffffffff8135ebb6>] tty_read+0xa6/0xf0
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861118]  [<ffffffff810ee7e5>] vfs_read+0xb5/0x1a0
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861122]  [<ffffffff810ee91c>] sys_read+0x4c/0x80
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861127]  [<ffffffff81009ba8>] system_call_fastpath+0x16/0x1b
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861131]  [<ffffffff81009b40>] ? system_call+0x0/0x52
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861133] Code: 85 d2 0f 84 92 00 00 00 45 8b ac 24 5c 02 00 00 f0 45 0f b3 2e 45 19 ed 49 63 84 24 5c 02 00 00 49 8b 94 24 50 02 00 00 4c 89 ff <0f> be 1c 02 e8 a9 d3 14 00 41 8b 94 24 5c 02 00 00 41 83 ac 24
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861171] RIP  [<ffffffff81363dde>] n_tty_read+0x2ce/0x970
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861175]  RSP <ffff8800f8599d88>
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861171] RIP  [<ffffffff81363dde>] n_tty_read+0x2ce/0x970
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861175]  RSP <ffff8800f8599d88>
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861177] CR2: 0000000000000015
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861205] ---[ end trace f10eee2057ff4f6b ]---
Apr 21 06:01:14 ip-10-49-109-107 kernel: [233185.861547] tty_release_dev: pts0: read/write wait queue active!

Comment: Telnet? I thought this was 2011?
Answer: Amazon is experiencing problems with EBS in us-east-1 availability zone:

2:18 AM PDT We can confirm connectivity errors impacting EC2 instances and increased latencies impacting EBS volumes in multiple availability zones in the US-EAST-1 region. Increased error rates are affecting EBS CreateVolume API calls. We continue to work towards resolution.
Comment: This is an instance in zone eu-west1. Is that zone also impacted? Btw, this is not at creation time of an EBS, it is an already running instance, using EBS volume to store a database.
Comment: Only the us-east-1 data center is marked as being affected, see the link i added to the answer above. Perhaps you have another unrelated problem.
Comment: Yes, sorry. Just took a look and in EU all seems normal.
Comment: Here is what I think happened.
The logs tell us that a telnet process has caused trouble. From that
point, the logs are flooded by this message:
 tty_release_dev: pts0: read/write wait queue active!

the kernel got in a loop until the server went down under the load.

The biggest question was: where did this telnet process come from?
It comes from a script I have written to report the memcache hitrate,
which I let run yesterday.
It requested every 2 seconds the hitrate, and for each request it
launched a telnet process.
One of these calls got into trouble and brought down the server.
Answer: Latest kernel security update is at  2.6.32-314.27. I think you should update and see if it helps.


Can't get CALayer or UIView from SwiftSVG to render to UIImage with UIGraphicsImageRenderer()

Question: I'm trying to render a CALayer from SwiftSVG package (on github) as a UIImage. It isn't working.
Source .svg file defines a viewBox 1169 x 1000.
If I add CALayer to UIView and add UIView (not UIImage) to view hierarchy, the SVG graphics are perfect, so CALayer is fine.
I added renderer.cgContext based drawing commands in the closure, to draw an outline around the rendering area. It worked. The resulting UIImage had an outline drawn, proving the image renderer block itself works.  Thus...
svgLayer.render() does not render visible graphics in the produced image.
svgView.drawHierarchy() doesn't work either (for example if I add the SVG layer as a sublayer of a view and try to render the view instead).

WORKS AND PRODUCES VALID CALAYER WITH PERFECT SVG GRAPHICS:
    let viewBox : CGRect? = CGRectMake(0, 0, 116.9, 100)
    let filename =  (fieldKey + ".svg").lowercased()
    let svgURL = gbl_svgDataUrl.appendingPathComponent(filename)

    let svgLayer = CALayer(SVGURL: svgURL) { (svgLayer) in
        svgLayer.fillColor = color.cgColor
        if let viewBox {
            svgLayer.resizeToFit(viewBox)
        }
    }

CAN GET DRAWN GRAPHICS INTO IMAGE BUT NOT RENDERED CALAYER OR VIEW:
    let format = UIGraphicsImageRendererFormat.preferred()
    format.opaque = false
    let image = UIGraphicsImageRenderer(size: viewBox.size, format: format).image { renderer in
        svgLayer.render(in: renderer.cgContext)  // <-- DOESN'T WORK

        //svgView.drawHierarchy(in: viewBox,     // <-- DOESN'T WORK
        //   afterScreenUpdates: false)
    }

Comment: Where are you putting the `UIGraphicsImageRenderer` code? It should be inside the completion handler of `CALayer.init`. Drawing SVG is asynchronous.
Answer: I figured out a resolution.
Tricky situation, so I'm answering my own question so this may come up in searches for related terms and help someone in the future

@Sweeper's comment to the question right, when trying to create a CALayer with SwiftSVG CALayer(SVGURL), it is async, and the layer can only be added to the view inside the closure.  What confused me is that's different than how SwiftSVG docs (at github project main page) shows the UIView(SVGURL:) API, which does complete synchronously, and the view is ready when the main call completes. Therefore, I switched from using CALayer(SVGURL:) to UIView(SVGURL:) to avoid async problems. And that necessitated to using view.drawHierarchy() instead of layer.render()

Then I hit a Catch-22 with this line:
svgView.drawHierarchy(in: viewBox, afterScreenUpdates: ??)

If I set afterScreenUpdates:false, I got this warning in the console:

"Rendering a view (0x117405440, UIView) that has not been rendered at least once requires afterScreenUpdates:YES."

But if I set afterScreenUpdates:true, I got this error:

"View (0x10a159e00, UIView) drawing with afterScreenUpdates:YES inside CoreAnimation commit is not supported."

And with either error the SVG View would not render into the image.
I tried forcing the view to display with setNeedsLayout() and layoutIfNeeded() before image rendering, which didn't work.  Neither did moving code into viewDidLayoutSubviews().
Solution: afterScreenUpdates:true and add a delay to avoid the 2nd error.
let viewBox = CGRectMake(0, 0, 116.9, 100)
let filename =  (fieldKey + ".svg").lowercased()
let svgURL = gbl_svgDataUrl.appendingPathComponent(filename)

let svgView = UIView(SVGURL: svgURL) { (svgLayer) in
    svgLayer.fillColor = color.cgColor
    svgLayer.resizeToFit(viewBox)
}

let format = UIGraphicsImageRendererFormat.preferred()
format.opaque = false
var image: UIImage?

// Add a slight delay to ensure the view has been rendered at least once

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {

    image = UIGraphicsImageRenderer(size: viewBox.size, format: format).image { renderer in
        svgView.drawHierarchy(in: viewBox, afterScreenUpdates: true)
    }

    if let image = image {

        let imageView = UIImageView(image: image)
        imageView.frame = viewBox
        imageView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(imageView)

        NSLayoutConstraint.activate([
            imageView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            imageView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
            imageView.heightAnchor.constraint(equalToConstant: viewBox.size.height),
            imageView.widthAnchor.constraint(equalToConstant: viewBox.size.width),
        ])
    }
}


Proof of $ \forall a \in \Bbb{R}: -a = (-1) a $.

Question:
Problem. Prove that $ \forall a \in \Bbb{R}: -a = (-1) a $.

I already have a proof but I would like to see another. :)

Proof by contradiction
Suppose that $ -a \neq (-1) a $. Then
\begin{align}
-a     & < (-1) a, \\
-a + a & < (-1) a + a, \\
-a + a & < (-1) a + (1) a, \\
0      & < ((-1) + 1) a, \\
0      & < (0) a, \\
0      & < 0. \quad (\text{Contradiction!!!})
\end{align}
Therefore, $ \forall a \in \Bbb{R}: -a = (-1) a $. $ \quad \blacksquare $
Is my proof correct?
Comment: Well, it depends. Have you proved that $a\cdot0=0$ for all $a\in\Bbb R,$ yet? Also, have you justified why we need not address the case $-a>(-1)a$?
Comment: Thank you, YES I have proved that $a0 = 0 \forall a \in \Bbb{R}$, The case -a > (-1)a is not necessary because there is a contradiction.
With this arguments, is my proof correct?
Answer: Well, you haven't considered the case $-a > (-1)a$...
But why not run your proof in reverse:
$0 = 0\\0 = a0\\0 = a(-1 + 1)\\-a + a = a(-1) + a(1)$
$-a + a = a(-1) + a\\(-a + a) + (-a) = (a(-1) + a) + (-a)\\-a +(a + (-a)) = a(-1) + (a + (-a))$
$-a + 0 = a(-1) + 0\\-a = a(-1) = (-1)a$
...?

As you can see (and is remarked in the comments above), this depends on the fact that $a0 = 0$.
Let's prove this:
$a0 = a(0+0) = a0 + a0\\a0 + (-(a0)) = (a0 + a0) + (-(a0))\\0 = a0 + (a0 + (-(a0)))$
$0 = a0 + 0 = a0$.


A linear isomorphism $T:\mathbb{R}^{n+1} \to \mathbb{R}^{n+1}$ induces a smooth map $\tilde{T}:\mathbb{RP}^n \to \mathbb{RP}^n$.

Question: A linear isomorphism $T:\mathbb{R}^{n+1} \to \mathbb{R}^{n+1}$ induces a smooth map $\tilde{T}:\mathbb{RP}^n \to \mathbb{RP}^n$ via $L \mapsto T(L)$. I want to understand why this is a smooth map. I am having trouble computing the coordinate representation with respect to the smooth atlas $\{(U_i,\phi_i)\}$ where $U_i$ is the collection of lines that intersect the affine hyperplane $x_i = 1$ and $\phi_i:U_i \to\mathbb{R}^n$ is defined by $[x_1,\ldots,x_{n+1}] \mapsto \left( \frac{x_1}{x_i},\ldots,\frac{x_{i-1}}{x_i}, \frac{x_{i+1}}{x_i},\ldots,\frac{x_n}{x_i}\right)$.
Answer: This is one instance where abstracting things further helps. Coordinates are a distraction. If $V$ is a vector space and $PV$ is the projective space over $V$, one defines an atlas $\{(U_f,\phi_f)\mid f \in V^*\setminus \{0\}\}$ by setting $$U_f =\{L \in PV \mid f[L] = \Bbb R\}$$and $\phi_f:U_f \to f^{-1}(1)$ as $\phi_f(L)=x/f(x)$ for any $x$ with $L = \Bbb R x$. For $V = \Bbb R^{n+1}$ and the projections $f = \pi_i$, we have exactly your atlas (under the homeomorphism $\pi_i^{-1}(1)\cong \Bbb R^n$ that deletes the $i$th entry). The inverse of $\phi_f$ is the span map. Any isomorphism $T:V\to V$ induces $PT:PV\to PV$ by $PT(L)= T[L]$.
Goal: show that $PT$ is smooth.
Given $f,g\in V^*\setminus \{0\}$, we compute $\phi_g\circ PT \circ \phi_f^{-1}$ as $$\phi_g\circ PT \circ \phi_f^{-1}(u) = \phi_g(PT(\Bbb R u)) = \phi_g(\Bbb R T(u)) = \frac{T(u)}{g(T(u))}.$$Since $u\mapsto T(u)/g(T(u))$ is smooth (where defined) for all $g \in V^*\setminus \{0\}$, we conclude that $PT$ is smooth.
(I'm denoting your $\widetilde{T}$ by $PT$ just to emphasize the functorial behavior of the whole thing.)


Can not find the property Featured of undefined in Ionic 3

Question: I am working on Ionic framework. I have fetching the JSON from an API. I have successfully fetched all the data but the problem is , when I am trying to show it on my page, then it is giving an error of Can not read property **Featured** of undefined.
My Featured.ts is:
import { ApiProvider } from './../../providers/api/api';
import { Component } from '@angular/core';
import { IonicPage, NavController } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'page-featured',
  templateUrl: 'featured.html',
})
export class FeaturedPage {
  videos: Observable<any>;

  constructor(public navCtrl: NavController, public apiProvider: ApiProvider) {
    this.videos = this.apiProvider.getVideos();
     this.videos
    .subscribe(data => {
      console.log('my data: ', data);
    })
  }
}

My Featured.html is:
<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>My First List</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-list>
  hey

      <ion-icon name="{{item.icon}}" item-left></ion-icon>
      {{fetch.category_name}}

        <youtube-player
                        content="default-src *; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'; img-src * data: 'unsafe-inline'; connect-src * 'unsafe-inline'; frame-src *;"
                        [videoId]="fetch.video_id_" (ready)="savePlayer($event)"
                        (change)="onStateChange($event)"></youtube-player>

  </ion-list>
</ion-content>

My JSON is:
{
    "api_status": "200",
    "api_version": "1.0",
    "data": {
        "featured": [{
            "id": 254,
            "video_id": "hsIL3Lgshbmh3sP",
            "user_id": 13,
            "title": "Dear Future Generations: Sorry | by Prince ea",
            "description": "Dear Future Generations: Sorry | by Prince ea
The sole purpose of this inspirational video is to raise awareness about the alarming rates of deforestation and the reckless destruction of our environment for which we all are responsible. This video tries to inspire the people of this world that immediate action must be taken to stop the destruction of the forests and to bring mainstream attention to this issue. This video teaches us that it is up to us to take care of this planet, it is our only home. To betray nature is to betray us, to save nature is to save us. Nothing will matter at last because if we don't work together to save the environment, we will be equally extinct.
Prince Ea, an activist, and inspirational spoken word artist has done it again this is one of the most powerful videos I have ever seen about mitigating climate change.",
            "thumbnail": "https:\/\/i.ytimg.com\/vi\/eRLJscAlk1M\/maxresdefault.jpg",
            "video_location": "https:\/\/www.youtube.com\/watch?v=eRLJscAlk1M",
            "youtube": "eRLJscAlk1M",
            "vimeo": "",
            "daily": "",
            "time": 1529352372,
            "time_date": "2018-06-18 20:06:12",
            "active": 0
        }]
    }
}

Answer: You need set data to this.videos not subcriber itself:
in your typescript:
this.apiProvider.getVideos()
.subscribe(data => {
    this.videos = data;
     console.log('my data: ', data);
})

Now in your html for loop like this:
*ngFor="let fetch of videos?.data?.featured"

hope this helps!!!
Comment: @NSharma  call async pipe  `(videos | async)?.data?.featured`
Comment: sorry but not a good idea. It clear the errors on console, but will not eliminate them.
Answer: try changing this
this.videos = this.apiProvider.getVideos();
     this.videos
    .subscribe(data => {
      console.log('my data: ', data);
    })

to
this.apiProvider.getVideos().subscribe(data => {
this.videos = data;
console.log('my data: ', data);
        })

Answer: you can try this

ts file code

videos:any;
this.apiProvider.getVideos().subscribe(data => {
    this.videos = data;
     console.log('my data: ', data);
})

html file code

*ngFor="let fetch of videos?.data?.featured"

Comment: Sorry, but it is not a right approach. It just clear the errors on console.
Comment: Please be aware that using the elvis operator (?) as Krishna suggests _is_ the right approach (at least partly), because for a certain time, before the api completes, `this.videos` ***has  no value*** and therefore you must guard against evaluation of `data.featured` when data is undefined - as your error message is telling you.
Comment: The other thing that Krishna recommends is to change videos to be non-observable, and set it in the subscribe - is probably the best way to go. Otherwise you need to use the async pipe as suggested in other comments.


find the value of $\int_0^1(C(-y-1)\cdot\sum_{k=1}^{2016}\frac{1}{y+k})dy$

Question:
The problem: find the value of $\int_0^1 (C(-y-1)\cdot\sum_{k=1}^{2016}\frac{1}{y+k}) dy$, where $C(\alpha$) is the coefficient of $x^{2016}$ in the Maclaurin series for $(1+x)^\alpha$

What I tried:
First of all, substituting $-y-1$ for $\alpha$ I get $C(-y-1) = \frac{-(y+1)(y+2)...(y+2017)}{2016!}$
Then $C(-1-y)\sum_{k = 1}^{2016}\frac{1}{y+k} = \frac{1}{2016!}\sum_{k=1}^{2016}\frac{\prod_{i=1}^{2016}(y+i)}{y+k}$, excuse my wonky formatting. This doesn't seem pretty at all and I'm kind of stuck here.
Questions:
Is there any way to reduce $\sum_{k=1}^{2016}\frac{1}{y+k}$ to something more managable? Like for example how $\sum_{k = 1}^n k^2 = \frac{n(n+1)(2n+1)}{6}$.
And if not, how do I even proceed? Thank you!
Comment: Hint: $\sum_{k=1}^{2016} \frac{1}{y+k} = \frac{d}{dy}\log\left(\prod_{k=1}^{2016}y+k\right)$
Answer: Whenever I see a problem with a year number in it, I just replace by $N$, i.e., let $N=2016$.
The coefficient of $x^N$ in $(1+x)^{\alpha}$ is
$$C(\alpha) = \frac1{N!} \prod_{m=0}^{N-1} (\alpha-m)$$
Thus,
$$C(-y-1) = \frac{(-1)^N}{N!} \prod_{m=1}^N (y+m) = \frac{(-1)^N}{N!} p_N(y)$$
Note that
$$p_N'(y)  = p_N(y) \sum_{k=1}^N \frac1{y+k} $$
Thus the integral is equal to
$$\begin{align}I &= \int_0^1 dy \, C(-y-1)  \sum_{k=1}^N \frac1{y+k} \\ &= \frac{(-1)^N}{N!} \int_0^1 dy \,  p_N(y) \sum_{k=1}^N \frac1{y+k} \\ &= \frac{(-1)^N}{N!} \int_0^1 dy \, p_n'(y) \\ &= \frac{(-1)^N}{N!} [p_n(1)-p_n(0)] \\ &= \frac{(-1)^N}{N!} [(N+1)!-N!]  \end{align} $$
Thus,

$$\int_0^1 dy \, C(-y-1)  \sum_{k=1}^{N} \frac1{y+k} = (-1)^N N$$

and in our special case, the answer is $2016$.
Answer: I think I maybe solved it! Thanks to achille hui's hint and using integration by parts I get:
$\int_0^1 (\prod_{k=1}^{2017}(y+k))\cdot(\ln(\prod_{k=1}^{2016}(y+k))')dy = -\frac{1}{2016!}(\prod_{k=1}^{2017}(1+k)\cdot\prod_{k=1}^{2016}(1+k) - \prod_{k=1}^{2017}k\cdot\prod_{k=1}^{2016} - \int_0^1\ln(\prod_{k=1}^{2016}(y+k))\cdot(\prod_{k=1}^{2017}(y+k))'dy)$
Let $I$ equal to the first integral, then using integration by parts again I get:
$I = -\frac{1}{2016!}(\prod_{k=1}^{2017}(1+k)\cdot\prod_{k=1}^{2016}(1+k) - \prod_{k=1}^{2017}k\cdot\prod_{k=1}^{2016}- \ln(\prod_{k=1}^{2016}(1+k))\prod_{k = 1}^{2017}(1+k) -\ln(\prod_{k=1}^{2016}k)\prod_{k=1}^{2017}k - I)$
Then evaluating all of those I get:
$I = -\frac{2017!(2018!-2016!-2017\ln(2016!)-2018\ln(2017))}{1+2016!}$
I don't know if this is the correct answer, but hooray!


Convert numeric value in module to its variable name

Question: In python 2.7, what's the best / easiest / most "pythonic" way to convert an integer value to the name of a module-scoped constant with that value?
Bonus points if there's a way to scope the search for variable names to those beginning with a magic prefix.
In other words:
EVT_FOO =0x0001
EVT_BAR =0x0002
EVT_SPAM=0x0004
EVT_EGGS=0x0008

def getEvtName( val ):
    """ This should return 'EVT_FOO' when given the number 0x1 """
    pass

I know I could just create a dictionary to do a reverse-lookup, but I'd like to think there's a better way in Python.  Suggestions?
Comment: What if `val` is assigned to more than one name (not unlikely, if it's a small integer)? Why not use an `Enum` (either the backport or one of the other suggestions - see http://stackoverflow.com/q/36932/3001761)? What is the *"better"* by which you plan to measure alternatives to a dictionary (and/or what's the problem with a dictionary)?
Comment: This is for a small `ctypes` wrapper that covers 2 functions, on that accepts a bitwise-or-ed together mask of events to watch, and one that returns a single event at a time.  Its simple enough and small enough that I'm sure I'll never have a collision unless an end user adds a value to the module post-import.
Comment: By "better" I mean less code I have to write and maintain.  Performance is of secondary concern since I want this mostly for debugging/testing.  A reverse lookup dictionary would add 30 lines to a module that's only 75 lines to begin with.  I'd like to have the constants stay at the module level so I can do modulename.SOME_CONSTANT in the code that uses it....  unless I'm missing something, I think that rules out Enum equivalents for 2.7, right?
Answer: You can use globals() function to get the name if a global object :
>>> EVT_FOO =0x0001
>>> EVT_BAR =0x0002
>>> EVT_SPAM=0x0004
>>> EVT_EGGS=0x0008
>>>
>>> def getEvtName( val ):
...     return next((i for i,j in globals().iteritems() if j==val and i.startswith(something)),None)
...
>>> getEvtName(0x0001)
'EVT_FOO'

Comment: @BrianMcFarland The `next` function accepts a default value at its second argument. check the edit!
Comment: Works like a charm with one exception, it throws `StopIteration` if the value is not found.   Depending on application, other users may want to return `None` or an empty string instead.  Also I ended up adding a simple `i.startswith()` condition to narrow the search-space from all global symbols.


boost and Curl not work together

Question: I really can not understand what my problem
Here is my code:
#include <iostream>
#include <curl/curl.h>
#include <boost/regex.hpp>

using namespace std;
using namespace boost;

int Write_callback(char *data, size_t size, size_t nmemb, string *buffer)
{
  int result = 0;
  if (buffer != NULL)
  {
    buffer->append(data, size * nmemb);
    result = size * nmemb;
  }
  return result;
}

char *Get(string url)
{
    CURL *curl;
    CURLcode res;
    char *readBuffer;
    int retries = 2;

    curl = curl_easy_init();
    if (curl) {
        do {
            curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Write_callback);
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
            curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
            curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt");
            curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.txt");
            curl_easy_setopt(curl, CURLOPT_USERAGENT,
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.5");
            res = curl_easy_perform(curl);
        } while (CURLE_OK != res && retries--);

        curl_easy_cleanup(curl);

        return readBuffer;
    }
}

int main(int argc, char** argv)
{
    char *www = Get("google.com");

    string Str = "dsfgdasgadgasdg";
    boost::regex RegEx("(.+)");
    boost::smatch Results;
    boost::regex_match(Str, Results, RegEx);
    cout << "Print entire match:\n " << Results[1] << endl;

    return 0;
}

This compiles, but when you run an error:
terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::_S_create

If I comment out this:
char *www = Get("google.com");

That works
If I comment out this:
string Str = "dsfgdasgadgasdg";
boost::regex RegEx("(.+)");
boost::smatch Results;
boost::regex_match(Str, Results, RegEx);
cout << "Print entire match:\n " << Results[1] << endl;

That works too..
Why it does not work together ??
Answer: In your Get function you declare the local variable readBuffer character pointer:
char *readBuffer;

You use the address of that as the userdata for your Write_callback function.  So the userdata is a char**.  But in your Write_Callback you have the userdata field a a std::string:
int Write_callback(char *data, size_t size, size_t nmemb, string *buffer)

With LibCurl the callback has the userdata parameter as a void* so it isn't a std::string:
size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata);

See http://curl.haxx.se/libcurl/c/CURLOPT_WRITEFUNCTION.html
Pass a std::string pointer as the userdata instead of a char**.  And I would keep the Write_callback parameter a void* and cast that void* to a std::string* in the callback.
Hope that helps!

boost and Curl not work together


At IE7, action "javascript:history.back()" in JSP jump back to main page, not previous viewed page

Question: Below are the code pieces in one jsp page, the function is to jump back to previous page, it works on Firefox 3.5, but does not work on IE7, at IE7, it will jump back to main index page.
how to enhance it to support IE7/Firefox at the same time?
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
<link rel='stylesheet' href="/css/main.css">

title

        <form action="javascript:history.back()">
            <input type="submit" value='back'>
        </form>

Answer: I prefer to use
history.go(-1);

instead of
history.back();

Comment: I changed it from history.back() to history.go(-1), it works on both IE7 and FF3.5.
Answer: I'm betting you're using an AJAX application. The problem is the IE7 does not update the history stack on hash changes or any AJAX action for that matter. There are ways around it though, I'd personally recommend http://www.mikage.to/jquery/jquery_history.html
Answer: Don't use JavaScript for this. Just let JSP/Servlet remember the previous page and put its URL in <form action> instead. You can grab the request URL by HttpServletRequest#getRequestURL().
Or, better, display the errors in the same page as the original form. This way you don't need to bother the enduser to remember all the errors before taking the extra action to go back to a page without error messages. Yes, this is bad user experience.


Binomial-type distribution with different probabilities

Question: I fear this may be too simple for many of you, but I'm stuck as to how to start solving this problem. I have five agents each performing a single task which has a yes/no answer. Four of them have a probability of 0.75 of getting a yes answer. The fifth has a 0.9 probability. What is the probability that three or more of them will answer yes? A (Philosophy!) paper I was reading suggested that it was around 0.93, but I would quite like to be able to prove this for myself. If the agents had the same probability I (think I) could use binomial distributions. However, I am stuck when one of the agents has a different probability. How should I proceed?
(I am not a hard-line mathematician, so the simpler the better…)
Kind Regards,
Peter
Answer: As you said, since the probabilities are different, the binomial distribution won't work as it is. My first inclination is to split this into cases:
1) The fifth agent answers yes, with probability .9. In this case, at least 2 of the 4 remaining agents have to say yes. You can model this sub-problem using a binomial distribution, since all agents have the same probability.
In short, the resulting probability of this case would be .9 * (Probability of 2 of the 4 remaining agents say yes) since this case occurs with .9 probability.
2) The fifth agent answers no, with probability .1. Now we need at least 3 of the 4 remaining agents to say yes. This, again, can be modeled using binomial distribution.
Once each case is evaluated, you can add them to get the overall probability of at least 3 people answering yes.
Hope this helps! :)
Answer: For $i=1,2,3,4$ let $X_i=1$ if agent $i$ gets answer "yes" and let $X_i=0$ otherwise.
Then $X:=X_1+X_2+X_3+X_4$ has binomial distribution with parameters $n=4$ and $p=0.75$.
Let $Y=1$ if agent $5$ gets answer "yes" and let $Y=0$ otherwise.
Then $Y$ has Bernoulli distribution with parameter $0.9$.
Then to be found is $P\left(X+Y\geq3\right)$ or equivalently:$$P\left(X+Y=3\right)+P\left(X+Y=4\right)+P\left(X+Y=5\right)$$where $X$ and $Y$ are independent.
Each of the terms can be split up like this:$$P\left(X+Y=k\right)=P\left(X+Y=k\mid Y=0\right)P(Y=0)+P\left(X+Y=k\mid Y=1\right)P(Y=1)=$$$$P\left(X=k\mid Y=0\right)0.1+P\left(X=k-1\mid Y=1\right)0.9=$$$$P\left(X=k\right)0.1+P\left(X=k-1\right)0.9$$where the last equation rests on independence of $X$ and $Y$.
To finish this properly you only need familiarity with binomial distribution.
Can you take it from here?
Comment: Still stuck. Suspect I am being dense. I assume that you mean that the bernoulli prob should be 0.90. I confess I am lost.
Comment: Yes, I meant 0.9. Repaired now. Can you find $P(X=k) $ for $k=2,3,4$ where  $X $ has binomial distribution with parameters  $n=4$ and $p=0.75$?


How does one know if normalizing is improves reconstructions in the task of auto-encoding?

Question: I wanted to understand the performance on an algorithm in the auto-encoding task and compare understand if normalizing the data was a good idea or not and compare the performance when the data is normalized vs when its not (normalize as in $\frac{x}{\| x \|}$ ).
The algorithm is trained via stochastic gradient descent (say its some neural network) and I train it via with the data and when the data is not normalized. Naturally, when the data is normalized, its likely to see smaller errors (just because we are dividing by a quantity $ \| x \| \geq 1$) so nearly by definition the error "seems" smaller because the data has been shrunk. However, this doesn't mean that the algorithm necessarily performed better (or worse). Therefore, I was trying to understand how should compare the performance of the algorithm on the same task when the data is normalized and when its not.
Naturally, if the problem I was trying to solve was instead classification, the problem would be very easy to solve, because, if the accuracy (in terms of correct labels predicted) increases, then we know that the algorithm is performing better when the data (say images) are normalized. But in the case of auto-encoding, its harder to see this.
Is the issue of having a hard time to compare the performance inherit in that I am considering the wrong loss function (i.e. $ L(f(x), y) = \| f(x) - y \|^2$ doesn't capture the information I want to learn) or what is the issue? How do people overcome this issue in practice and know if its worth normalizing in the case of auto-encoding task?
Obviously, one can just observe the reconstruction for say, a fraction of the images and the human can asses which one is better, but this approach doesn't seem to scale. Is there a better way to do this or has this been addressed in practice or theoretically?
Comment: What is $ y $? Does the output activation linear?
Comment: @yasin.yazici $y = x$ since its an auto-encoder. I think the issue I presented is not really an issue in particular to NN or any specific learning algorithm (so it doesn't matter if the activation is linear, its just any kernel or activation, linear, non-linear). The issue is that comparing the results/errors of an auto-encoder where the error is normalized vs when its not. The error is (potentially) artificially shrunk by normalization, but that doesn't necessarily mean the auto-encoder is doing better.
Answer: You can compute your error not on the on the original input image vs output image, but on scaled input image and scaled output image, which will solve your problems of different scales. Also you can use different similarity metrics, that are scale invariant, for example correlation or cosine similarity.
Comment: so after the learning has been done one do as follow: $L(\frac{ f(x) }{ \| f(x) \| } , \frac{ x }{\| x \| } )$, right? Is there a way to prove that this is mathematially correct? What worried me about this approach was that $f(x)$ would be normalized in the method you mentioned, but the function learned on the normalized training data set is not necesserily normalized. Wouldn't that be an issue?
Answer: Did you consider scaling the loss of the normalized auto-encoder by your normalization factor? As in multiply by ||x|| again?
Be careful with squared error though. You'd have to apply the scaling factor inside the power (i.e. (f(x)*||x||)² not f(x)² * ||x||. Or just use absolute error instead.
.
One thing from the theoretical side to consider: IIRC, An auto-encoder layer with N nodes is identical to the rank-N truncated SVD of the input matrix.
For the SVD, if your data is not centered around the origin, the first singular vector will point to the center of the data (you can easily see this in an example).
So, for equal N, when your data is z-normalized (I know, this is not what you're doing here), i.e. mean = 0, std = 1, you have one more singular vector to "work with" to describe the variance of your data compared to when it's unnormalized.
This also makes sense intuitively, as you lose the information about where your data is located (say in an area between x = 2 and x = 5) during normalization, while you keep the information about its structure around that center point.
Comment: Sorry, maybe I was imprecise. My line of thinking was that you "scale up" your loss by the normalization factor again.

|| (f(x) - y) * ||x|| ) || ²

In a sense, you normalize your data, perform the auto-encoding and de-normalize the results back to the original scale, then compute the error. This way you're comparing apples to apples.

What you mention here would not be mathematically correct, because (square of normalized loss) * normalization factor is not the same as the square of the unnormalized loss

Alternatively you can choose a loss where this property holds, such as absolute error
Comment: as in, for any loss $L(f(x), y)$, do $\| x \| L(f(x), y) $? For the squared loss I mentioned would be $ \| f(x) - y \|^2 \cdot \| x\| $, why would that be mathematically correct?


Manter o valor de um contador regressivo com javascript

Question: Tenho um cotador regressivo, porém quando o navegador é atualizado ele volta a contar do inicio, o que eu preciso é que ele mantenha a contagem mesmo atualizando a página.
Andei pesquisando essa solução com cookies porém não achei a solução, não quero a resposta dada, quero aprender como faz, alguém pode me dar um norte a seguir?
Obs: Caso alguém não entenda o problema, é o mesmo que esse aqui.

function tempo(op) {
  if (op == 1) {
    document.getElementById('parar').style.display = "block";
    document.getElementById('comeca').style.display = "none";
  }
  var s = 59;
  var m = 1;
  var h = 1;
  intervalo = window.setInterval(function() {
    if (s == 0) { m--; s = 59; }
     if (m == 0) { h--; m = 0; }
      if (h < 0) h = 0;
       if (h < 10) document.getElementById("hora").innerHTML = "0" + h; else document.getElementById("hora").innerHTML = h;
         if (s < 10) document.getElementById("segundo").innerHTML = "0" + s; else document.getElementById("segundo").innerHTML = s;
         if (m < 10) document.getElementById("minuto").innerHTML = "0" + m; else document.getElementById("minuto").innerHTML = m;
    s--;
    if ((h == 0) && (m == 0) && (s == 0) ) m=59;
  },1000);

}
window.onload=tempo;
body{ background: #20262E;}

/* CSS Contador */
.ContBoxContador{ width: 270px; margin: 0 auto; color: white; text-align: center; }
.ContBoxContador:after{ content: ""; display: table; clear: both; }
.ContBox001{ width: 80px; float: right; background-color: red; border-radius: 5px; }
.ContSubbox001{ width: 80px; }
.ContSubbox001 span{ font-size: 14pt; padding: 0; margin: 0;}
.ContSubText001{ font-size: 8pt; color: white; margin: 0; padding-bottom: 4px; font-weight: 500; font-family: open sans, sans-serif; }
.ContEntreBox{ width: 10px; float: right; margin: 0; padding: 0;}
.ContEntreBox h1{ font-size: 2em; color: white; font-weight: 100; margin: 0; padding: 0;}

        00

Segundos

:

    00

Minutos

:

      00

Horas

Comment: Amigo usa a sessionStorage ele vai guardar o seu valor até que a janela seja fechada.
Answer: Pode usar o localStorage para isso, mas saiba que ele funciona apenas na sessão do navegador onde a página foi aberta. Você pode fechar o navegador ou a aba que o localStorage é preservado, mas se abrir em outro navegador que não tenha aberto a página antes, o contador irá recomeçar.
No exemplo abaixo eu criei um objeto JSON no localStorage para guardar as variáveis h, m e s, que serão recuperadas com JSON.parse.
Não vou criar um exemplo executável aqui porque o localStorage não irá funcionar no servidor do SOpt. Segue o código com explicações nos comentários:
function tempo(op) {
  if (op == 1) {
    document.getElementById('parar').style.display = "block";
    document.getElementById('comeca').style.display = "none";
  }

  var ls = localStorage.getItem("tempo"); // chama o LS

  if(ls){ // verifica se o LS existe
     ls = JSON.parse(ls); // converte para JSON
     var s = ls.s; // pega os segundos
     var m = ls.m; // pega os minutos
     var h = ls.h; // pega as horas
  }else{
     var s = 59;
     var m = 1;
     var h = 1;
  }

  intervalo = window.setInterval(function() {

    localStorage.setItem("tempo", '{"h": '+h+', "m": '+m+', "s": '+s+'}'); // atualiza o LS

    if (s == 0) { m--; s = 59; }
        if (m == 0) { h--; m = 0; }
         if (h < 0) h = 0;
             if (h < 10) document.getElementById("hora").innerHTML = "0" + h; else document.getElementById("hora").innerHTML = h;
                if (s < 10) document.getElementById("segundo").innerHTML = "0" + s; else document.getElementById("segundo").innerHTML = s;
                      if (m < 10) document.getElementById("minuto").innerHTML = "0" + m; else document.getElementById("minuto").innerHTML = m;
    s--;
    if ((h == 0) && (m == 0) && (s == 0) ) m=59;
  },1000);

}
window.onload=tempo;

Comment: Era exatamente isso que eu precisava, muito obrigado a você e a todos que comentaram sobre Storage, pois eu não conhecia, estou estudando sobre.
Answer: Uma solução pode ser utilizar o localStorage para salvar o tempo do contador a cada atualização. É mais simples do que os cookies. Como você não quer a resposta direto, te recomendo dar uma olhada na documentação do localStorage.
Lembre-se que no primeiro acesso, o usuário não terá a informação do contador salvo no localStorage.


Is there a specific command to delete all elements of a list?

Question: I know that you can simply:
list = [a, b, c, d, e]

for index in list:
    list.remove(index)

but is there a faster way with a single command like:
list.remove(all)

or something along those lines?
Comment: Also http://stackoverflow.com/questions/1400608/how-to-empty-a-list-in-python
Comment: Searched and didn't find it. Sorry.
Answer: You can use del and Explain Python's slice notation:
>>> lst = [1, 2, 3, 4]
>>> del lst[:]
>>> lst
[]
>>>
>>> lst = [1, 2, 3, 4]
>>> id(lst)
34212720
>>> del lst[:]
>>> id(lst)  # Note that the list object remains the same
34212720
>>>

Answer: Yes, you can do del myList[:].  (Don't use list as a variable name, it blocks access to the builtin type called list.)
Answer: One way I can think of:
myList[:] = []

Or another way can be assigning None to the list, the garbage collector will free up the memory eventually.
("list" is not a good name for a list in python, it's already a type)


Proving if function is one to one?

Question: Let $f : (\mathbb{N} \times \mathbb{N}) \to \mathbb{N}$ be defined as:
\begin{equation}
    f(x, y) = \frac{(x + y)(x + y + 1)}{2} + y
\end{equation}
I know that $f(x,y) = f(x',y')$ in order to be a one to one.
So it'll be :
\begin{equation}
\frac{(x+y)(x+y+1)}{2}+ y = \frac{(x'+y')(x'+y'+1)}{2}+ y'
\end{equation}
but I don't know how to prove this exactly, the fraction is throwing me off.
Comment: Note that exactly one of $x+y$ and $x+y+1$ is a multiple of $2$.
Answer: We begin by noting that the sets $P_i = \{ x| \frac{i(i-1)}{2} < x \le \frac{i(i+1)}{2} \}$ are disjoint.
Now note that $\frac{(x+y)(x+y+1)}{2}+y$ is in the set $P_{x+y+1}$.
Similarly, we note that $\frac{(x'+y')(x'+y'+1)}{2}+y'$ is in the set $P_{x'+y'+1}$.
Therefore, we must have $x+y=x'+y'$. It follows that $x=x'$, $y=y'$.

Proving if function is one to one?


multiple image upload from frontend in wordpress

Question: I have a CPT "Annonce" which is supposed to have four attached images. Now I building a frontend form to allow users to submit posts with four image upload fields. When I try to submit the form with multiple images, only the last image appears as featured in the dashboard. I see the other images in Media section but not in the post edit page so I can change or delete theme.
I'm using this code in page-post.php:
        if ( $_FILES ) {
        $files = $_FILES['upload_attachment'];
        foreach ($files['name'] as $key => $value) {
            if ($files['name'][$key]) {
                $file = array(
                    'name'     => $files['name'][$key],
                    'type'     => $files['type'][$key],
                    'tmp_name' => $files['tmp_name'][$key],
                    'error'    => $files['error'][$key],
                    'size'     => $files['size'][$key]
                );

                $_FILES = array("upload_attachment" => $file);

                foreach ($_FILES as $file => $array) {
                    $newupload = insert_attachment($file,$post_id);
                }
            }
        }
    }
...

Photo 1 :
<input type="file" name="upload_attachment[]" id="postPhoto1">

Photo 2 :
<input type="file" name="upload_attachment[]" id="postPhoto2">

and in functions.php I have this function:
function insert_attachment($file_handler,$post_id,$setthumb='false') {

  // check to make sure its a successful upload
  if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

  require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  require_once(ABSPATH . "wp-admin" . '/includes/file.php');
  require_once(ABSPATH . "wp-admin" . '/includes/media.php');

  $attach_id = media_handle_upload( $file_handler, $post_id );

  if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
  return $attach_id;
}

Using this form the images are successfully uploaded but only last image get set as featured image, and I want to show other images in the post edit page too.
any help?
Answer: You can install advanced custom fields plugin,create as many image fields as you want,and then use it in frontend with the method described in documentation.
http://www.advancedcustomfields.com/resources/tutorials/creating-a-front-end-form/
This method is tested and working by me in wordpress 3.4.2, later editions had problems with uploading from frontend.
Answer: Try this
 < input type="file" id="attachment" name="attachment[]" multiple="multiple" >

Answer: i hope this code work for you
    if (!function_exists('wp_generate_attachment_metadata')) {
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        require_once(ABSPATH . "wp-admin" . '/includes/file.php');
        require_once(ABSPATH . "wp-admin" . '/includes/media.php');
    }
    $files = $_FILES['upload_attachment'];
    $attach_ids=array();
    foreach ($files['name'] as $key => $value) {
        if ($files['name'][$key]) {
            $file = array(
                'name'     => $files['name'][$key],
                'type'     => $files['type'][$key],
                'tmp_name' => $files['tmp_name'][$key],
                'error'    => $files['error'][$key],
                'size'     => $files['size'][$key]
            );
            $_FILES = array("upload_attachment" => $file);

            foreach ($_FILES as $file => $array) {
                $attach_id = media_handle_upload($file,$post_id);
                array_push($attach_ids , $attach_id);
            }
        }
    }
    update_post_meta($post_id, 'upload_attachment', $attach_ids);

html code :
        <input multiple type="file" name="upload_attachment[]"/>

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Staccato and legato on a violin simultaneously?

Question: Can anybody explain to me how it is possible, if possible at all, to play staccato and legato on a violin simultaneously?
Here is a score I stumbled upon on YouTube:

As far as I know, the dot above a note means that the player is supposed to play that note very shortly (staccato), while a curve above two or more than two notes means that the notes are to be played in a "mingled way", that is, smoothly transitioning from one to another.
But in the above-mentioned score I see these two opposite things denoted as to be performed at the same time!:

How is that physically possible?
Answer: In violin music the slur means means the bow direction does not change. Normally this results in legato. In your example the bow stops and restarts for each pair of notes, and the next pair of notes would be played with the bow moving in the opposite direction.
Comment: Thank you. You said, "In violin music the slur means the bow direction does not change" - So, that means that those notes in my example are all played in staccato and none of them are played in legato then. Am I correct?
Comment: No it's not staccato, it means notes are 'detached' rather than legato but with the bow moving in one direction per slur. The linked duplicate question has more info.


Equivalent vmin vmax matplotlib bokeh

Question: I am a new user of bokeh. Although the question is very simple I have not found the answer.
In the bokeh library, what is the equivalent of vmax and vmax of matplolib imshow?
For example, in Matplolib I use vmin and vmax with these values
im = ax.imshow(image_data, vmin = 0.1, vmax = 0.8, origin = 'lower')

However, If I use bokeh I get a different result,
p1 = figure(title="my_title",x_range=[min_x,image_data.shape[0]],y_range=[min_y, image_data.shape[1]], toolbar_location=None)
p1.image(image=[image_data], x=[min_x],y=[min_y],dw=[image_data.shape[0]],dh=[image_data.shape[1]], palette="Spectral11")
color_bar = ColorBar(color_mapper=color_mapper, ticker=LogTicker(),
                             label_standoff=12, border_line_color=None, location=(0,0))

imshow Vs bokeh result

What is my error? Thanks in advance
Answer: With this code it work:
from bokeh.plotting import figure
from bokeh.models.mappers import LogColorMapper
from bokeh.models import ColorBar, LogTicker

color_mapper = LogColorMapper(palette="Viridis256", low=0.1, high=0.8)

plot = figure(x_range=(0,image_data.shape[0]), y_range=(0,image_data.shape[1]),
              toolbar_location=None)
plot.image(image=[image], color_mapper=color_mapper,
           dh=[image_data.shape[0]], dw=[image_data.shape[1]], x=[0], y=[0])

color_bar = ColorBar(color_mapper=color_mapper, ticker=LogTicker(),
                     label_standoff=12, border_line_color=None, location=(0,0))
plot.add_layout(color_bar, 'right')

Comment: Hey, thanks for the example, but it's kinda incomplete.  Can someone point me to the import for `LogColorMapper`?
Comment: bokeh.models.mappers.LogColorMapper

Equivalent vmin vmax matplotlib bokeh


Delete from multiple SQL tables with C# command

Question: I want to delete from multiple SQL tables with a C# command but I get always error:

Invalid syntax near ",".

Here is code so far:
string connectionString = @"Data Source=" + System.IO.File.ReadAllText("Server.ini") + ";" + "Initial Catalog=" + "lin2world" + ";" + "User ID=" + System.IO.File.ReadAllText("User.ini") + ";" + "Password=" + System.IO.File.ReadAllText("Password.ini");
string sql = "DELETE FROM user_data, user_item, user_ActiveSkill, user_blocklist, user_deleted, user_friend, user_henna, user_history, user_log, user_macro, user_macroinfo, user_newbie, user_nobless, user_punish, user_recipe, user_skill, user_sociality, user_subjob WHERE char_id='" + textBox1.Text + "' ";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "char_id");
connection.Close();
MessageBox.Show("Character Deleted!!");

Comment: SQL Server has no syntax to delete from multiple tables in one statement.
Comment: try putting `test' GO DROP TABLE user_data GO` in textbox1
Comment: Write a stored procedure to clear the tables and call it. Also please look into parameterized queries, this is a sql injection vector **nightmare**.
Comment: That's not the correct syntax for DELETE.  It doesn't look like you even have a table name in there anywhere.  DELETE is used to delete rows from a table; are you trying to clear the values in certain columns but leave the row in the table?
Comment: http://stackoverflow.com/questions/1714545/delete-rows-from-multiple-tables-using-a-single-query-sql-express-2005-with-a
Comment: what I would do is put seperate deletions into a transaction. read this other answer http://stackoverflow.com/questions/783726/how-do-i-delete-from-multiple-tables-using-inner-join-in-sql-server
Comment: You can still do this with a cursor and a select based on your list of names, see below. Also yes as sawyer says, please, please, don't do this without using a parameterized query
Answer: You can only delete from one table in a delete statement.
Use multiple delete statements within a transaction to perform the deletes
In case your not familiar with transactions in C# here is an example
using (var Conn = new SqlConnection(_ConnectionString))
{
    SqlTransaction trans = null;
    try
    {
        Conn.Open();
        trans = Conn.BeginTransaction();

        using (SqlCommand Com = new SqlCommand(ComText, Conn, trans))
        {
            /* DB work */
        }
        trans.Commit();
    }
    catch (Exception Ex)
    {
        if (trans != null) trans.Rollback();
        return -1;
    }
}

Comment: You can also use triggers: http://stackoverflow.com/questions/9996643/sql-server-on-delete-trigger

Or some form of cascading delete if it's applicable.
Comment: Cascading delete makes the most sense here i'd say.
Comment: @Yablargo I agree only if the tables are truly relational, Since we don't know the table structure we can't really say that the id is set up as a foreign key in the other tables though.
Answer: If you want to do something similar to this, you can pass all tables as a list and still do what you want.
DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name IN ("user_data","user_item","user_ActiveSkill","user_blocklist","user_deleted","user_friend","user_henna","user_history","user_log","user_macro","user_macroinfo","user_newbie","user_nobless","user_punish","user_recipe","user_skill","user_sociality","user_subjob")  -- use these databases

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name

WHILE @@FETCH_STATUS = 0
BEGIN

       DELETE FROM @name WHERE char_id='whatever'

       FETCH NEXT FROM db_cursor INTO @name
END

Edit: It seems like these are all related tables -- if you have a proper relationship with cascade: delete, you should only have to delete the main record and its children will all take care of themselves
Answer: You cannot delete from multiple tables in one statement within SQL Server. You will need multiple statements, one for each table:
DELETE FROM user_data WHERE PersonID = '2';
DELETE FROM user_item WHERE PersonID = '2';

etc etc
And fire each one off individually, (making sure not to violate any FKs) or create a stored procedure and fire that off (to minimise open and closing of db connections).
My experience of using triggers tells me not to use triggers, at times they will not fire when they should!


Como criar multiplas rotas de erro no Angular 2

Question: Olá, estou trabalhando com o angular 2(v4+), onde minha aplicação tem a seguinte estrutura contendo 2 módulos que são carregados dinamicamente (via loadChildren):
Estrutura do diretório
app
 |-foo
 |  |- foo.module
 |  |- ... (foo components)
 |-bar
 |  |- bar.module
 |  |- ... (bar components)

AppRouting.ts

export const AppRoutes: Routes = [
    { path: '', loadChildren: './foo/foo.module#FooModule' },
    { path: 'bar', loadChildren: './bar/bar.module#BarModule' }
];

FooRouting.ts

export const FooRoutes: Routes = [
    { path: '', component: ManageComponent },
    { path: ':id', component: DetailsComponent },
    { path: 'list', component: ListComponent },
    { path: '**', component: FooErrorNotFoundComponent }
];

BarRouting.ts

export const BarRoutes: Routes = [
    { path: '', component: WorkspaceComponent },
    { path: 'view', component: ViewComponent },
    { path: 'another', component: AnotherComponent },
];

O meu problema é o seguinte:

Preciso que cada sub-módulo tenha sua própria tela de erro, porque os subcomponentes dela podem mudar como barras de navegação, etc...
Quando uso a estrutura acima e tento acessar a url localhost:300/bar/view o Angular está me direcionando para a pagina de erro de Foo, ou seja, ele não está respeitando inicialmente as rotas do AppRouting e indo direto para Foo.
Se removo a página de erro de Foo, ai sim o Angular me direciona para o submódulo Bar.

Como posso manter a página de erro do módulo Foo mas forçando o Angular a respeitar a estrutura inicial de roteamento de App?
Answer: Encontrei a solução quando resolvi ler mais a fundo a própria documentação do Angular 2 (aqui):

[...] The order of the routes in the configuration matters and this is by design. The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. In the configuration above, routes with a static path are listed first, followed by an empty path route, that matches the default route. The wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first. [...]

Conforme a especificação, para que o que eu preciso funcione, eu tenho que gerar as rotas com a ordenação das mais complexas para as mais simples, então meu AppRouting terá a sua estrutura invertida, assim:
AppRouting

export const AppRoutes: Routes = [
    { path: 'bar', loadChildren: './bar/bar.module#BarModule' },
    { path: '', loadChildren: './foo/foo.module#FooModule' }
];

Fazendo isso, mesmo que a rota não exista, a aplicação primeiro tentará encontrar em Bar uma página de erro, portanto posso ter 2 páginas de erro diferentes, e o que diferenciará será as rotas iniciais (ou '' ou 'bar').


How do you update your Java EE app in production?

Question: I've been trying to figure out what is happening in the world of Java EE production deployment and frankly it seems pretty scary. After speaking to over a 100 people these are my hypotheses:

Nobody uses redeployment in
production (as in the actual button
that does in-server update). It just
isn't reliable enough due to
OutOfMemoryError-s and other
failures.
The common way to update an
application is to:

Take all servers down at 2am and hope no one is using it.
Take servers down one at a time,
upgrade them and either drop or
migrate the user sessions.
Use weird hacks like copying one file at a time.

I'm also trying to find out how the update process happens, how hard it is and what does it cost in human measure (hours) and in soulless business measure (dollars).
I ask you to help me out and provide me with some semi-solid data I can use to better understand what's going on in reality. Hopefully you'll prove me wrong. I'm looking forward to you answers, but would also ask you to answer this survey to get some data: http://0t.ee/appupdq11
I know this is not the typical ServerFault question, as there isn't a right answer here, but by filling in the survey you'll help me a great deal and if you provide a longer answer here it will be just awesome.
Answer: Strongly depends on the application.
Most J2EE applications run on server cluster farms where a basic application upgrade can be done with a rolling upgrade. I.e. take one server out of the load balancer farm, wait for its work to finish, update the EAR deployment, test it, put it back in the lb farm, take the next out and repeat.
You may require an outage to do database schema upgrades, just to make sure consistency of data. Database software upgrades can usually be done without a major outage, Oracle is one good example.
Answer: in weblogic i use wlst (python on java - jython) to do deployments. you can make any logic you want with it.
the complicated part of all the deployments is when you do a database schema update ... which is not really a java problem but it affects the java systems.
on glassfish and tomcat is simpler ... tar up the directory install a fresh instance with the old configs and then deploy the war,ear file.
of course you can couple all this with a configuration management tool like cfengine, puppet or even fabric will do.


Clopper-Pearson for non mathematicians

Question: I was wondering if anyone can explain to me the intuition beyond the Clopper-Pearson CI for proportions.
As far as I know, every CI includes a variance in it. However, for proportions, even if my proportion is 0 or 1 (0% or 100%), the Clopper-Pearson CI can be calculated. I tried looking at the formulas, and I understand it has something with percentiles of the Binomial distribution and I understand that finding the CI involves iterations, but I wondered if anyone can explain the logic and rational in "simple words", or with minimum math ?
Answer: When you say you're used to confidence intervals containing an expression for variance, you're thinking of the Gaussian case, in which information about the two parameters characterizing the population—one its mean & the other its variance—is summarized by the sample mean & sample variance. The sample mean estimates the population mean, but the precision with which it does so depends on the population variance, estimated in turn by the sample variance. The binomial distribution, on the other hand,  has just one parameter—the probability of success on each individual trial—& all the information given by the sample about this parameter is summarized in the total no. successes out of so many independent trials. The population variance and mean are both determined by this parameter.
You can get a Clopper–Pearson 95% (say) confidence interval for the parameter $\pi$ working directly with the binomial probability mass function. Suppose you observe $x$ successes out of $n$ trials. The p.m.f. is
$$\Pr(X=x)= \binom{n}{x}\pi^x(1-\pi)^{n-x}$$
Increase $\pi$ until the probability of $x$ or fewer successes falls to 2.5%: that's your upper bound. Decrease $\pi$ until the probability of $x$ or more successes falls to to 2.5%: that's your lower bound. (I suggest you actually try doing this if it's not clear from reading about it.) What you're doing here is finding the values of $\pi$ that when taken as a null hypothesis would lead to its (only just) being rejected by a two-tailed test at a significance level of 5%. In the long run, bounds calculated this way cover the true value of $\pi$, whatever it is, at least 95% of the time.
Comment: @amoeba: Presumably you're thinking about small sample sizes: (1) You'd probably want something like Blaker-Spjotvoll CIs rather than CIs based on an equal-tail-area test. (2) The confidence distribution is rather choppy, which would make the width of any given interval unpleasantly sensitive to the coverage you stipulate.
Comment: +1. This might deserve a question on its own, but I will quickly ask here: for a particular application I would like to get a single uncertainty measure (something that behaves like standard error of the mean) for various proportions. I know that there is a number of binomial CI procedures, including Clopper-Pearson. Would it make sense to take a width of such a CI as an uncertainty measure? Or perhaps width/1.96/2 to make it yield exactly SEM in the Gaussian limit.

Clopper-Pearson for non mathematicians


Can I show public youtube live videos on my Android app?

Question: I have app which shows some live streams from youtube
I have taken permission for some channels to show their live streams on my app, but there are some other channells which I am not able to reach and they don't mention anything about copyright and else
If I show publicly open  Youtube Live Streams on my Android app would it cause to any problem?
If you inform me I will be glad
Thanks in advance
Answer: As long as the livestreams are public and you aren't making money off of the app you are making, (Ads, Paid apps, etc.) you are allowed to use the livestreams.
Comment: is it writing in youtube conditions and terms sheet ?
Comment: @ARKA what do you mean
Comment: I mean is it written in YouTube rules?
Comment: @ARKA Yes. Also, if my answer was good, please upvote it or mark it as a solution with the little checkmark icon.


Pegar script de uma DIV com JS

Question: É possivel pegar o SCRIPT de algum elemento.. EX:

Pegar apartir da 'class="box"'

pegar o código completo dentro da divisória id="form"? Que seria:

Pegar apartir da 'class="box"'

Answer: Se por "script" você quer dizer pegar todo o HTML dentro da div, faça assim:

var form = document.getElementById('form');
var conteudo = form.innerHTML;
alert(conteudo);

Pegar apartir da 'class="box"'

Comment: Brigadão mano ;)
Answer: Como a pergunta está na categoria "jQuery" vou dar a resposta em jQuery:
var div_form = $('#form');
var html = div_form.html();

se você fizer
console.log(html);

você verá o código html extraído do elemento #form.
Você pode usar a versão simplificada:
var html = $('#form').html();

Pegar script de uma DIV com JS


Can someone explain the @RestResource annotation for building a Rest resource?

Question: I am trying to create a RESTful web service.  Above the class there is the following  comment.
<code>/**
 * Represents entities as resources.
 *
 * @RestResource(
 *   id = "entity",
 *   label = @Translation("Entity"),
 *   serialization_class = "Drupal\Core\Entity\Entity",
 *   deriver = "Drupal\rest\Plugin\Deriver\EntityDeriver",
 *   uri_paths = {
 *     "canonical" = "/entity/{entity_type}/{entity}",
 *     "https://www.drupal.org/link-relations/create" = "/entity/{entity_type}"
 *   }
 * )
 *
 * @see \Drupal\rest\Plugin\Derivative\EntityDerivative
 */
</code>
What does this mean? What is it supposed to do?
I can't find anything useful about this, especially about the uri_paths array.
Answer: Annotations are used in Drupal 8 to provide meta data in the same location as the class definition. It was borrowed directly from Symfony which is used in the Drupal 8 core to take advantage of an existing framework. The meta data is contained from the lines between @RestResource( and the closing ). Everything else is treated as a normal php block comment. For example I have a custom REST resource for which the annotation is:
<code>/**
 * Provides a resource for database intermed table entries.
 *
 * @RestResource(
 *   id = "intermed",
 *   label = @Translation("Intermed content entity standard methods"),
 *   serialization_class = "Drupal\intermed\Entity\Intermed",
 *   uri_paths = {
 *     "canonical" = "/intermed/{intermed}",
 *     "http://drupal.org/link-relations/create" = "/entity/intermed"
 *   }
 * )
 */
</code>
So for this resource intermed is the id and is used in request operations. The canonical form /intermed/{intermed} will be used for operations other than POST which uses /entity/intermed
In the canonical setting the {intermed} denotes a parameter to be passed.
So if I was to send a GET request to site d8beta14.qetm.org as format HAL+JSON for the intermed table entry for which the id was 2:
GET http://d8beta14.qetm.org/intermed/2?_format=hal_json
This GET operation requires three headers: Authorization, Accept, Content-Type
Comment: The canonical path for PATCH and DELETE is exactly the same as GET. The path for POST needs /entity/ in front of entity id as mentioned above. The second uri which ends in create is a second uri path used in POST
Comment: Awesome thanks. I have my GET request working.  So what is the canonical path is just the path for  PATCH and DELETE?  then for POST I would need to use the other path?  What is the significance of the "http://drupal.org/link-relations/create" link?


Catch an exception thrown in Dataset foreachPartition() function on the driver in Spark?

Question: I'm trying to find a way to catch an exception thrown by a Spark inside a foreachPartition() method on its driver. When using foreachPartition() on a Dataset, I pass a lambda function that is carried out across the various workers. This process could potentially throw an exception. But I cannot figure out a way to catch this exception on the driver. It appears this is by design. Is there something I can do to change this? Here is an example of what I'm currently doing:
public static void driverClassExecute() {
    Dataset<ModelDTO> dataset = getSomeData();
    dataset.foreachPartition(AClass::methodCanThrowException);
    //How can I recover if the above throws an exception?
}
public static void methodCanThrowException(Iterator<ModelDTO> it) throws Exception {
    //do stuff. If bad, throw exception. This crashes the driver.
    throw new Exception("any exception");
}

I'm also using Eclipse Oxygen IDE in case the compiler matters.
Comment: Such facility is not available, are you trying to handle exception and avoid job stoppage?
Comment: @AbhishekN Thanks for confirming. And yes, this would be to avoid the job from stopping entirely.
Answer: In this case foreachPartition will throw an exception so you can wrap that call in a try-catch and handle as any other exception, although the spark job will already have failed. To avoid the job failing you would have to handle the exception in methodCanThrowException.
Comment: Yes this is due to a Java Vs Scala mismatch in how exceptions work.
Comment: I don't follow... If I handle the exception in methodCanThrowException(), it won't throw anything. But if I throw something from methodCanThrowException(), the job will fail and the foreachPartition() won't throw an exception (I don't think it can throw one anyway, making a try/catch useless around foreachPartition()). So I'm not sure what you're suggesting?
Comment: If you throw something from methodCanThrowException(), the job will fail and an exception IS thrown from foreachPartition.
Comment: More precisely it will get retried first and if it throws on retry then the job will fail. Do you mean you want to get the exceptions from  tasks that throw but succeed on retry?
Comment: Uhm, I'm not sure what this "retry" is that you're referring to unless it's something Spark is doing silently. In naive terms, I want to wrap the .foreachPartition() in a try/catch and if an exception is thrown from the method passed as an argument to  .foreachPartion(), catch it instead of having the application just halt immediately. I don't think something like this is possible without rewriting it in Scala.
Comment: Not sure exactly what the difficulty is, perhaps this is what you are looking for: try { dataset.foreachPartition(AClass::methodCanThrowException); } catch (Exception ex) { ... }
Comment: So it turns out this answer is actually 100% correct. It's kind of strange, but I had to wrap the logic using a base Exception class. Any other sub-class resulted in the compiler complaining that the exception was never thrown. This included RuntimeException.
Answer: I think you may be doing things a little differently but a typical execution for Spark partitioned DS would be done in following steps:

Create the Dataset ==> This is already done through getSomeData() function.
Iterate over partitions using dataset.foreachPartition() ==> keep in mind that this function does not give you single record, it gives you the whole partition which could have many records based on your splitting logic in getSomeData().
Next level Iteration through partition.forEachRemaining() to obtain individual records by the executor and run appropriate business logic.

When you run the #3 step, this is where you should pass each record your methodCanThrowException() like in Java -
partition.forEachRemaining(record -> {
      try {
        methodCanThrowException(record);
      } catch (Exception e){
        e.printStackTrace();
        Logger.info(<record-key> "etc for debugging or tracking");
      }
);

Obviously you can handle exceptions in several ways to write to audit file for correction etc. But your processing will not fail due to an exception in the processing method.


AutoHotKey doesn't start program out of Visual Studio Code + AutoHotkey Extension

Question: I want to make a script with Visual Studio Code and AHK that starts a certain program (automatically connect to a VPN ==> FortiClient).
If I double click directly on the script only containing that specific ahk run command in Windows Explorer, the client starts as desired. From Visual Studio code nothing happens.
I tried:

run, %programfiles%\Fortinet\FortiClient\FortiClient.exe

==> Works with double click from Windows explorer. Running from VS Code: nothing.

run, C:\Program Files\Fortinet\FortiClient\FortiClient.exe

==> Works with double click from Windows explorer. Running from VS Code: nothing.
I made a link to the exe an put that to a folder without a blank character in the directory name:

run, C:\Software_Checkout\AHK\FortiClient_Verknuepfung.lnk

==> Works with double click from Windows explorer. Running from VS Code: nothing.
What can be the reason for this?
Comment: Other commands like msgbox or send work from VS Code. Just the run command is not working (so far).
Comment: Is the script running?
Comment: Yes, the script runs and returns without error. But the run command is just doing nothing.
Answer: I am unable to reproduce, so I'll give a dumb suggestion. Complete shot in the dark, but make sure you're not starting VS Code from under WSL. I've made that mistake in the past, the head scratches were plentiful. Other than that, I don't know what could be the issue. Maybe a faulty debugger?
Example script that works for me from VS Code, with several debuggers:
<code>ProgramFilesX86 := A_ProgramFiles . (A_PtrSize=8 ? " (x86)" : "")
run %ProgramFilesX86%\Microsoft\Edge\Application\msedge.exe
</code>
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Bash/GitBash: Regex comparison doesn't work inside aliases

Question: As stated in Q-title, I have an alias setup for running multiple Git commands if the current directory in GitBash terminal is valid Git repository.
Now I am trying to do a regex comparison of User prompt's answer such that if User types y or Y then it must go ahead and run the command after the next && like below:
alias abc="([ `git rev-parse --git-dir` == \".git\" ] && git restore \"*lock*\" \"*mix-manifest*\" && git status && (read -p \"Run 'git diff'? \" && [[ $REPLY =~ ^[Yy]$ ]] && git diff))"

But this alias when called throws the following error:
bash: conditional binary operator expected
bash: syntax error near `^[Yy]$'

And from this bit-vague error message, I got that the problem is somewhere in [[ $REPLY =~ ^[Yy]$ ]] and maybe because I am using this comparison inside double-quotes of an alias. I already tried replacing ^[Yy]$ with '^[Yy]$' and \"^[Yy]$\", but in vain.
Can anyone assist in figuring out the problem in [[ $REPLY =~ ^[Yy]$ ]] and fix this ?
Comment: `$REPLY` is substituted before the alias is assigned, so you're effectively getting `[[ =~ ^[Yy]$ ]]` assuming REPLY is empty. Try replacing the alias with a function, it will be much easier to write the code you want without dealing with parsing rules.
Comment: What about create a bash file into your local bin dir and call it from your alias ?
Answer: With the help of nice suggestion by @tjm3772, I was able to fix this by converting the alias into function as below:
abc(){ ([ `git rev-parse --git-dir` == ".git" ] && git restore "*lock*" "*mix-manifest*" && git status && (read -p "Run 'git diff'? " && [[ $REPLY =~ ^[Yy]$ ]] && git diff)); }

And declaring this in .bashrc file, and it worked like charm.


How do i get information about types from an FSharp prompt

Question: I am working with FSharp and am trying to find out more information about the types i am consuming from the FSharp.Data library. For example, how can i go about find out if HttpMessageBody is a discriminated union etc from the FSharp interactive prompt?
Answer: You can use methods from Reflection.FSharpType to gain information:
For example
 static member IsUnion : Type * ?BindingFlags -> bool

will tell you if a type is a Union type.
More functions in the module are at MSDN
Comment: Wow. That seems like a pretty obtuse way of getting at the information. I was hoping for something like the python help function. Is there a way to view the type definitions?
Answer: I do not think there is a simple way to get the information directly from F# interactive (but, as mentioned by John Palmer, it would not be too hard to write a helper function that gets this information using F# reflection and prints it).
However, if you're using Visual Studio or MonoDevelop (Xamarin Studio), then you should see all the information you need in the tool tip that is displayed when you hover over the type name in the editor or find it in the autocomplete:
Comment: The primary usage pattern for fsi is writing the code in VS and sending it to fsi.  Thats why no further work was done on the intellisense and autocompletion features in fsi itself.
Answer: I believe Code Quotations is what you are looking for.


Understanding Ruby Code

Question: I need some help understanding the below ruby code.
counted = Hash.new(0)
parsed_reponse["result"]["data"].each { |h| counted[h["version"]] += 1 }
counted = Hash[counted.map {|k,v| [k,v.to_s] }]

I understand line 1 creats a hash which I believe is similar to a
dictionary in python.
Line 2 loops through my json data set a adds a
new key and value pair if none exits and increments the count if 1
does exist.
What does the 3rd line do?
Comment: [`Hash[ [ [key, value], ... ] ] → new_hash`](https://ruby-doc.org/core-2.4.2/Hash.html#method-c-5B-5D) -- Creates a new hash populated with the given objects.
Answer: Your last line just converts all values to String:
Hash[{a: 2, b: 3}.map {|k, v| [k, v.to_s]}]
#=> {:a=>"2", :b=>"3"}

I would refactor it to:
counted.transform_values!(&:to_s) # for ruby >= 2.4
#=> {:a=>"1", :b=>"2"}

Or for older versions:
counted.each { |k, v| counted[k] = v.to_s }

Because:

counted.map {|k,v| [k,v.to_s] } - creates new array of arrays
Hash[result] - creates new Hash object from result array.

Both steps are redundant, you can just modify existing hash.
Comment: Is there documentation for .map. method. I tried looking here, http://ruby-doc.org/core-2.3.1/Hash.html, but found nothing.
Comment: In recent Ruby versions you could write `counted.transform_values!(&:to_s)`

Understanding Ruby Code


Existence of homogeneous non-unit non-zero divisor in a particular graded ring.

Question: Let $R$ be a finitely generated $k$-algebra of dimension greater than $1$, let $Q$ be any maximal ideal of $R$. It is claimed by my lecturer that one can find a homogeneous, non-unit, non-zero divisor in the associated graded ring gr$R$ corresponding to the $Q$-adic filtration of $R$. Explicitly gr$R$=$\bigoplus_{i\geq 0} Q^i/Q^{i+1}$. I do not see why this is the case.
In particular I tried to show $(Q,x+Q^2,Q^3,..)$ in gr$R$ has these properties where $x\in Q-Q^2$. Note that $Q\neq Q^2$ else gr$R$ is a field which is a contradiction since know dim(gr$R$)$=$dim($R)\gt1$. For this example to work I really want something of the form that if $x.y\in Q^n $ where $y\in Q^{n-2}$ then $y\in Q^{n-1}$. This is true for $n=2$ by using $R/Q$ field.
Another thing is that this result is a step to prove another result which implied $Q^i \neq Q^{i+1}$ for all $i$. It is clear that what I claimed in the last paragraph would be false without this.
Answer: I might be mixing up things, but intuitively I think you need stronger assumptions on $R$: The dimension of $R$ concerns the minimal primes of $R$ (geometrically, the irreducible components of $\text{Spec}(R)$) while the (non-)presence of zero-divisors concerns the associated primes of $R$ (geometrically, the 'virtual' irreducible components of $\text{Spec}(R)$), not all of which need to be minimal.
Example: Begin with the $n$-plane $S=k[x_1,...,x_n]$ and build $R$ from $S$ by adding an infinitesimal line at the origin, i.e. $R := S[t]/(t^2, tx_1,...,tx_n)$. Then $R$ stil has dimension $n$, but any homogeneous element of positive degreee annihilates $t$, hence is a zero-divisor. So, in the associated graded of $R$ with respect to ${\mathfrak m} = (t,x_1,...,x_n)$, any homogeneous non-unit is a zero-divisor.


Find the convergence radius for $\sum_{n=1}^{\infty}\frac{2^{n-1}x^{2n-1}}{(4n-3)^2}$

Question:
Find the convergence radius for $\sum_{n=1}^{\infty}\frac{2^{n-1}x^{2n-1}}{(4n-3)^2}$

I'm trying to understand why this solution is wrong:
We can look at this as a power series with $a_n = \begin{cases}
 & \frac{2^{n-1}}{(4n-3)^2} \text{ if power of } x \text{ is odd} \\
 & 0 \text{ if power of } x \text{ is even}
\end{cases}$
And then using Cauchy–Hadamard we would get $R=\frac{1}{2}$.
On the other hand, if we substitute $t=x^2$ we get that the radius is $R=\frac{1}{2}$ for t, meaning $R=\frac{1}{\sqrt{2}}$ for x. Which is actually the correct solution.
I don't get why the first solution is wrong, explanation will be appreciated.
Answer: You gave the formula for $a_{2n-1}$, not $a_n$. You need $t=x^2$ to convert the series into a form Cauchy-Hadamard addresses.
Answer: In the first method your formula for $a_n$ is not correct. To find $a_n$, the coefficient of $x^{n}$, where $n$ is odd, write $n=2m-1$ or $m=\frac {n+1} 2$. Then you get $a_n=\frac {2^{m-1}} {(4m-3)^{2}}=\frac {2^{(n-1)/2}}{ (2n-1)^{2}}$


Install RSClientPrint for Reporting Services 2012 using .bat file and still be able to use 2005

Question: I have a Reporting Services 2005 server that when users accessed it and tried to print reports would get a message asking them to install the print control, which they could not do because of lack of permission.  A work around I had found at the time was to copy the .dll and .rll files to their computer on startup via group policy and then register it.  Now we are upgrading to Reporting Services 2012 and the print control has changed and I need to do this again.
I have 3 questions.
I can't locate the .dll and .rll files on my computer to put in a share.  Where should I look for them.
I have a mix of 32 bit and 64 bit machines.  Will this make a difference in what files I need?
Will the script below otherwise still work?
if not exist %windir%\system32\rsver3.txt goto ADD

GOTO END

:ADD
regsvr32.exe /u /s rsclientprint.dll
copy \\server\share\RSClientPrint.dll %windir%\system32
copy \\server\share\RSClientPrint_1028.rll %windir%\system32
copy \\server\share\RSClientPrint_1031.rll %windir%\system32
copy \\server\share\RSClientPrint_1033.rll %windir%\system32
copy \\server\share\RSClientPrint_1036.rll %windir%\system32
copy \\server\share\RSClientPrint_1040.rll %windir%\system32
copy \\server\share\RSClientPrint_1041.rll %windir%\system32
copy \\server\share\RSClientPrint_1042.rll %windir%\system32
copy \\server\share\RSClientPrint_1043.rll %windir%\system32
copy \\server\share\RSClientPrint_1046.rll %windir%\system32
copy \\server\share\RSClientPrint_1053.rll %windir%\system32
copy \\server\share\RSClientPrint_2052.rll %windir%\system32
copy \\server\share\RSClientPrint_3082.rll %windir%\system32
copy \\server\share\gdiplus.dll %windir%\system32
copy \\server\share\rsver3.txt %windir%\system32
regsvr32.exe /s  %windir%\system32\rsclientprint.dll
:END

Update
I modified the above script to the following and placed the x86 and 64 files in different folders.
These files were extracted from the c:\Program Files\Microsoft SQL Server\MSRS11.MSSQLSERVER\Reporting Services\ReportServer\bin\RSClientPrint-x64.cab and c:\Program Files\Microsoft SQL Server\MSRS11.MSSQLSERVER\Reporting Services\ReportServer\bin\RSClientPrint-x86.cab and placed in the appropriate folders
and it appears to work on 32 bit and 64 bit systems, however, it no longer allows you to print from Reporting Services 2005 on the 32 bit machines.  It prompts to install the print control.  The 64 bit machines can print from both Reporting Services 2005 and 2012 after running this script.
if exist %windir%\SysWOW64\nul goto X64
GOTO X86

:X86
if not exist %windir%\system32\rsver5.txt goto ADD86

GOTO END

:ADD86

regsvr32.exe /u /s %windir%\system32\rsclientprint.dll
copy /Y \\server\share\x86\RSClientPrint.dll %windir%\system32
copy /Y \\server\share\x86\RSClientPrint_1028.rll %windir%\system32
copy /Y \\server\share\x86\RSClientPrint_1031.rll %windir%\system32
copy /Y \\server\share\x86\RSClientPrint_1033.rll %windir%\system32
copy /Y \\server\share\x86\RSClientPrint_1036.rll %windir%\system32
copy /Y \\server\share\x86\RSClientPrint_1040.rll %windir%\system32
copy /Y \\server\share\x86\RSClientPrint_1041.rll %windir%\system32
copy /Y \\server\share\x86\RSClientPrint_1042.rll %windir%\system32
copy /Y \\server\share\x86\RSClientPrint_1046.rll %windir%\system32
copy /Y \\server\share\x86\RSClientPrint_1049.rll %windir%\system32
copy /Y \\server\share\x86\RSClientPrint_2052.rll %windir%\system32
copy /Y \\server\share\x86\RSClientPrint_3082.rll %windir%\system32
copy /Y \\server\share\gdiplus.dll %windir%\system32
copy /Y \\server\share\rsver5.txt %windir%\system32
regsvr32.exe /s %windir%\system32\rsclientprint.dll

GOTO FINISH

:X64

if not exist %systemroot%\SysWoW64\rsver5.txt goto ADD64

GOTO END

:ADD64

 %systemroot%\SysWoW64\regsvr32.exe /u /s %systemroot%\SysWoW64\rsclientprint64.dll
 %systemroot%\SysWoW64\regsvr32.exe /u /s %systemroot%\SysWoW64\rsclientprint.dll

copy /Y \\server\share\64\RSClientPrint64.dll %systemroot%\SysWoW64
copy /Y \\server\share\64\RSClientPrint64_1028.rll %systemroot%\SysWoW64
copy /Y \\server\share\64\RSClientPrint64_1031.rll %systemroot%\SysWoW64
copy /Y \\server\share\64\RSClientPrint64_1033.rll %systemroot%\SysWoW64
copy /Y \\server\share\64\RSClientPrint64_1036.rll %systemroot%\SysWoW64
copy /Y \\server\share\64\RSClientPrint64_1040.rll %systemroot%\SysWoW64
copy /Y \\server\share\64\RSClientPrint64_1041.rll %systemroot%\SysWoW64
copy /Y \\server\share\64\RSClientPrint64_1042.rll %systemroot%\SysWoW64
copy /Y \\server\share\64\RSClientPrint64_1046.rll %systemroot%\SysWoW64
copy /Y \\server\share\64\RSClientPrint64_1049.rll %systemroot%\SysWoW64
copy /Y \\server\share\64\RSClientPrint64_2052.rll %systemroot%\SysWoW64
copy /Y \\server\share\64\RSClientPrint64_3082.rll %systemroot%\SysWoW64

copy /Y \\server\share\x86\RSClientPrint.dll %systemroot%\SysWoW64
copy /Y \\server\share\x86\RSClientPrint_1028.rll %systemroot%\SysWoW64
copy /Y \\server\share\x86\RSClientPrint_1031.rll %systemroot%\SysWoW64
copy /Y \\server\share\x86\RSClientPrint_1033.rll %systemroot%\SysWoW64
copy /Y \\server\share\x86\RSClientPrint_1036.rll%systemroot%\SysWoW64
copy /Y \\server\share\x86\RSClientPrint_1040.rll %systemroot%\SysWoW64
copy /Y \\server\share\x86\RSClientPrint_1041.rll %systemroot%\SysWoW64
copy /Y \\server\share\x86\RSClientPrint_1042.rll %systemroot%\SysWoW64
copy /Y \\server\share\x86\RSClientPrint_1046.rll %systemroot%\SysWoW64
copy /Y \\server\share\x86\RSClientPrint_1049.rll %systemroot%\SysWoW64
copy /Y \\server\share\x86\RSClientPrint_2052.rll %systemroot%\SysWoW64
copy /Y \\server\share\x86\RSClientPrint_3082.rll %systemroot%\SysWoW64

copy /Y \\server\share\gdiplus.dll %systemroot%\SysWoW64
copy /Y \\server\share\rsver5.txt %systemroot%\SysWoW64

%systemroot%\SysWoW64\regsvr32.exe  /s %systemroot%\SysWoW64\rsclientprint64.dll
%systemroot%\SysWoW64\regsvr32.exe  /s %systemroot%\SysWoW64\rsclientprint.dll

GOTO FINISH

:FINISH

:END

Answer: Hey just for future reference you got this the wrong way around. the 32bit DLL files should go to SysWOW64 and the 64bit should go in system32.
Confusing but that is the way it works with DLL's is SysWOW64 contains the 32bit emulated DLL files and system32 contains the native 64 bit ones.
Hope this helps someone.
Answer: The Rsclientprint.inf file is missing.


What's my voice type

Question: I know that classifying a voice type isn't something I should focus on but I'm just curious about what I would be labeled as.
My speaking range is from G2/Ab2-D3/E3 (this is just when I speak, I tend to reach G2 when I'm tired or sick)
I am untrained and have never taken a singing class, but the highest my chest voice can push if I try is D4 and maybe F4. I don't try and use head or falsetto since I don't want to damage my chords since I'm not a trained singer but I feel in mixed and in head voice I could reach higher notes. Again, I know voice classification shouldn't matter and that everyone has their own unique voice but I am curious what I would be labeled.
Answer: I think you probably would be a tenor voice at the moment.
In 4 part voices, here is a possible voice range
Soprano - C4 to A5
Alto - F3 to C5
Tenor - A2 to F4
Bass - F2 to C4

What’s my voice type