Calculus question from Howard Anton

Question: Let $y=f(x)$ and $dy/dx=e^y+2y+x$. I wish to prove that the critical points are only relative minima.
I am stuck with this problem from the book which needs expert help. I have no idea how to proceed.
Comment: Btw, it is not forbidden to accept answers.
Comment: If you don't accept answers, it does not motivate people to answer your questions. Just a hint-for free.
Comment: It is "encouraged" to accept Answers , to be more Precise , @callculus42 , though I know what you want to convey here.
Answer: We are given $dy/dx = Z+x$ where $Z$ involves $y$.
When $dy/dx = 0$ AND $d^2y/dx^2$ is Negative , we have Critical Maxima Point.
When $dy/dx = 0$ AND $d^2y/dx^2$ is Positive , we have Critical Minima Point.
We can see that $d^2y/dx^2 = W dy/dx + 1$ , where $W$ corresponds to $Z$ & $1$ corresponds to $x$.
Here , when-ever $dy/dx = 0$ , we get $d^2y/dx^2 = W \times 0 + 1 = 1$ , which is Positive & not Negative.
Hence , at all the Critical Points , $d^2y/dx^2$ Positive indicates relative Minima.
Comment: The second derivative will be negative *or zero* at a local maximum, positive *or zero* at a local minimum. You are wanting the converses of your statements.
Comment: Thank you , @TedShifrin , I have updated that Point now !

Calculus question from Howard Anton


Is there a way to find which IP I am connected to?

Question: Let's say my eth0 interface has multiple IP addresses and I can connect with SSH to any of these.  Is there a way to find out which of those I am connected to?
(The background is that certain operations, like removing an IP from the host, is better not done from the given IP address.  To avoid this, I want to check this first, before I am closing myself out.)
Comment: I'm a little confused. When you connect via ssh, you do something like "ssh user@IP_ADDRESS" right? Or are you looking for the source of the connection?
Comment: @barrycarter The example mentioned in the question makes it quite clear why he is interested in the server IP rather than the client IP. If you connect using a hostname, which resolves to multiple IPs, you won't automatically know, which one you are connected to.
Comment: @kasperd OK, but then why not connect to "ssh user@IP_ADDRESS" instead? Seems much easier?
Comment: @barrycarter If you find the need to know in the middle of a session, it is easier to type `echo "$SSH_CONNECTION"` than to log out and start a new ssh connection.
Answer: You can simply type:
echo "$SSH_CONNECTION"

Or if you want only the server IP address and not the other fields:
echo "$SSH_CONNECTION" | cut -f3 -d' '

If you are using screen and reconnect to a previously started screen session, notice that running these commands inside screen will show the connection from which screen was started and not the session where you reconnected to screen.
Comment: Or `echo "$SSH_CONNECTION" | awk '{print $1}'` if you prefer `awk` over `cut`.
Comment: @ThoriumBR That would have to be `$3`.
Comment: Thanks, especially for mentioning `screen` - sometimes we do exactly that.
Answer: The easiest way would be to use netstat and check for connections in there.
user@host:~$ sudo netstat -ntp
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp      128      0 220.127.116.11:50212         18.104.22.168:22            ESTABLISHED 16774/ssh
[more stuff removed]

Comment: In my case, this boils down to `netstat -ntp | grep :22`.


Clogit and no variation in strata

Question: Suppose that I want to identify a causal effect with panel data. The dependent variable is dichotomous so I use a conditional logit with survival::clogit in R, with clusters for each individual. If an individual is always treated, my understanding is that the fixed effects model drops the observation. But how do I see how many observations are dropped? In the regression output I do not get any information on this (and the number of observations equals the number of rows in my dataframe).
Answer: If you mean the clogit function in the survival package, strata with no variation in the predictor are not dropped; they just end up not contributing any information to the estimator.  The function does not keep track of which strata contribute information, so if you want to know how many strata have variation in a particular variable you'll have to just compute that directly from the data.
Comment: Yes, I mean `survival::clogit`; thank you!

Clogit and no variation in strata


Bootstrap grid rows with no top or bottom padding?

Question: Having an issue getting my grid rows to be "tight" against the adjacent rows, with no vertical space between them. As of now, it is placing something like 20px between every row.
<code>    .container {width: 640px;}

    .row {width: 640px; spacing: 0px; padding: 0px;}

    .grid{
    margin: 0px;
    width: 640px;
    }

    .thumbnail {
    position:relative;
    overflow:hidden;
    }

    .col-xs-3{
    width: 210px;padding: 2px;}
</code>
Comment: Did you check the margins?
Comment: you have put 2px of padding on your cols top and bottom. I wouldn't recommend missing with the Bootstrap grid rows and cols - you are making a responsive framework unresponsive....
Comment: The 2px padding on the col-xs-3 is mainly for the horizontal spacing between the rows. There still seems to be a 20px vertical margin between rows with or without the 2px
Comment: Also, I'm fairly new to this! Thank you all for your help so far...
Answer: Few things.
1) This line of CSS
   <code>.row {width: 640px; spacing: 0px; padding: 0px;}</code>
spacing is not a CSS attribute
2) This has to deal with specificity
3) How to override
<code>.no-spacing {
    margin: 0; padding:0;
}
</code>
Add this to your CSS file and link it after bootstrap. Then add the class to the elements you want not to use bootstrap's spacing.
Answer: You write in your question about the vertical spacing so I think that you are addressing the gap between the columns and not below the rows. Bootstrap is adding a 15px right and left padding to each column.
You can overwrite this in your custom CSS:
<code>.row {
    margin-left: 0;
    margin-right: 0;
}
.col-xs-3 {
    padding-left: 0;
    padding-right: 0;
}
</code>
But you must do this for each col-* class then.
And as written in the first answer there is no "spacing" CSS rule.
Comment: Thank you... I am actually addressing the space below the rows, not the space between the columns
Comment: However Bootstrap does not define spacing there by default.


nodejs upgrade causing stack trace

Question: I just upgraded to node v6. Everything is running fine, but I am getting the following stacktrace noting that something is being deprecated:
<code>(node) v8::ObjectTemplate::Set() with non-primitive values is deprecated
(node) and will stop working in the next major release.

==== JS stack trace =========================================

Security context: 0x18c48b3c9fa9 <JS Object>#0#
    1: .node [module.js:568] [pc=0x14a2e95935a4] (this=0x3e1b399e54e9 <an Object with map 0x31db83e17be1>#1#,module=0x1b9e891a8351 <a Module with map 0x31db83e181b9>#2#,filename=0x1b9e891a8319 <String[114]: /Users/alexanderray/WebstormProjects/skillx/node_modules/dtrace-provider/build/Release/DTraceProviderBindings.node>)
    2: load [module.js:456] [pc=0x14a2e9438e72] (this=0x1b9e891a8351 <a Module with map 0x31db83e181b9>#2#,filename=0x1b9e891a8319 <String[114]: /Users/alexanderray/WebstormProjects/skillx/node_modules/dtrace-provider/build/Release/DTraceProviderBindings.node>)
    3: tryModuleLoad(aka tryModuleLoad) [module.js:415] [pc=0x14a2e943899d] (this=0x18c48b304189 <undefined>,module=0x1b9e891a8351 <a Module with map 0x31db83e181b9>#2#,filename=0x1b9e891a8319 <String[114]: /Users/alexanderray/WebstormProjects/skillx/node_modules/dtrace-provider/build/Release/DTraceProviderBindings.nod 1: v8::Template::Set(v8::Local<v8::Name>, v8::Local<v8::Data>, v8::PropertyAttribute)
 2: node::DTraceProvider::Initialize(v8::Local<v8::Object>)
 3: node::DLOpen(v8::FunctionCallbackInfo<v8::Value> const&)
 4: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&))
 5: v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::(anonymous namespace)::BuiltinArguments<(v8::internal::BuiltinExtraArguments)1>)
 6: v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*)
 7: 0x14a2e930961b
 8: 0x14a2e95935a4
</code>
I understand that this won't be a breaking change until the next release, but does anyone know what package this is coming from and where I should be looking for a fix? Also is there a way to suppress this?
Comment: Yeah, got the same thing with node-sass here.
Answer: Issues have been open over various projects (including nodejs) and some PRs have already been submitted; e.g.

strongloop/fsevents #127, Using deprecated APIs in node v6
nodejs/citgm #124, List of modules broken by node v6
nodejs/node #6277, v8: warn in Template::Set() on improper use.

We may just have to wait for v6.0.1.
Comment: Awesome thanks. I searched the node github repo but obviously not hard enough. Not a huge deal. Just makes my test output look ugly
Comment: Here's another one to add to the list: https://github.com/tugrul/node-mcrypt/issues/54
Answer: I had the same error in some projects, and I solved all of them, updating dependencies.
I know that probably you will  not agree to update all dependencies in some circurstances, so you can edit the packake.json file, and change one by one each dependency to "latest".
And then execute npm install to update all dependencies to the latest release
for instance, this is my package.json of one of my projects:
<code>
  "dependencies": {
    "body-parser": "latest",
    "eris-contracts": "latest",
    "express": "latest",
    "mongodb": "latest",
    "promise": "latest",
    "rootpath": "latest"
  }
</code>

nodejs upgrade causing stack trace


Mocking a class with generic parameter function inside Swift

Question: I am trying to unit test simple HttpClient behaviour. For that I have created an GenericHttpClientInterface protocol and concrete class GenericHttpClient that implements this protocol.
protocol GenericHttpClientInterface {
    func makeRequest<T: Decodable>(request: URLRequest) -> Observable<T>
}

class GenericHttpClient: GenericHttpClientInterface {
    func makeRequest<T: Decodable>(request: URLRequest) -> Observable<T> {
        return URLSession.shared.rx.data(request: request).jsonDecode(to: T.self)
    }
}

What I wanted to achieve is to mock that class :
class MockHttpClient: GenericHttpClientInterface {
    var invokedMakeRequestCount = 0
    var invokedMakeRequestParameters: (request: URLRequest, Void)?
    var stubbedMakeRequestResult: Observable<Any>!
    func makeRequest<T: Decodable>(request: URLRequest) -> Observable<T> {
        invokedMakeRequestCount += 1
        invokedMakeRequestParameters = (request, ())
        return stubbedMakeRequestResult as! Observable<T>;
    }
}

What gives ma a problem is that the method I am mocking has generic parameter T inside which is a class that the request will be decoded to. I don't know this parameter until I call this function so basically in MockHttpClient class for a property that stores stub data for makeRequest I've created:
stubbedMakeRequestResult: Observable<Any>
and after returning it I'm trying to cast that to result type Observable. This gives me an warning
Cast from 'Observable<Any>?' to unrelated type 'Observable<T>' always fails

and in consequence
Thread 1: signal SIGABRT.

Any idea how to stub that data?
Example test that creates SIGABRT:
class GenericHttpTest: XCTestCase {

    var sut: Repository!
    var mockHttpClient: MockHttpClient!

    override func setUp() {
        mockHttpClient = MockHttpClient()
        sut = Repository(httpClient: mockHttpClient)
    }

    let test_mocked_data_stub = DataModelStruct(args: DataModelStruct.InsideModelStruct(foo1: "bar"))

    func test_should_return_mocked_data_from_mock_http_client() {
        mockHttpClient.stubbedMakeRequestResult = Observable.just(test_mocked_data_stub)

        let response = try! sut.getFooBar().toBlocking().first()

        XCTAssertEqual(response, test_mocked_data_stub)
    }
}

Comment: You seem to understand the error - your stubbed type is different than the return type of `makeRequest`. So, you either need to create the stubbed data within `makeRequest` and check for the type. or you maybe overload `makeRequest` for the type that you are stubbing with
Answer: Due to the fact that generics are invariant in Swift, Observable<Any> will never ever be convertible to Observable<T>, unless T is Any. This is what cause your crash, as when you assign the value to stubbedMakeRequestResult, the concrete Observable is converted to Observable<Any>, and there's no turning point from here.
What you can do to avoid this is to make stubbedMakeRequestResult an Any, as this will not make any conversions behind the scenes. A small problem is that you loose the type safety and inference, but you can fix this stubbing via a function:
class MockHttpClient: GenericHttpClientInterface {
    ...
    var stubbedMakeRequestResult: Any!

    func stubMakeRequestResult<T>(_ result: Observable<T>) {
        stubbedMakeRequestResult = result
    }
    ...
}

Comment: A bit shocked I'm the second person that wants to know this?


Leading Bass note

Question: I'm having trouble understanding whether there is such a term as a leading bass note.
Suppose there are three instruments: piano, bass and guitar.

The piano plays A in bass and A,E,G in right hand.
The bass plays F note below piano A.
The guitar plays an FM7: F,A,C,E chord.

In result we get notes F,A,C,E,G but what chord is that if piano plays one bass note and bass guitar plays another?
Comment: The lowest sounding note is special. I doesn't matter which instrument is playing the lowest sounding note. Of all the notes being played at the same time by all the instruments, the one that has the lowest fundamental frequency is the note that would be considered the "bass note" for music theory purposes.
Comment: This is a fairly hypothetical question, but if the pianist voiced the chord like that, I would be looking for another pianist!
Comment: @alephzero Why is that? I often voice a harmony that way, if someone is playing say a C chord I might play an inverted Em chord to add the Maj7 and add colour to the harmony.
Comment: Root and 5th are the best notes to have in a lower register. Thus, the pianist's left hand should be doubling the F or playing a C. The A will sound murky and a bit dissonant.
Answer: Well, first of all, FACE is not an F7 chord, it's an Fmaj7.  To be F7 the E would have to be flatted.
Secondly, if the intended harmony at that point is either F7 or Fmaj7, then the bass note of F is the primary bass note, and the low A in the piano is a harmony note.
Thirdly, I would avoid using the word "leading" in this context, because a "leading note" is the seventh tone of a major scale, and at the next change moves up to the tonic, hence is thought of as "leading" to the tonic, which is of course not what you meant!
I should also add that the G in the mix is simply an added Second in the chord.  (If it resolves downward eventually to the F, then it is a Suspended Second.)
Comment: Sus 2s are generally regarded as taking the place of the 3rd. So, since there's an A (3rd) in there already, the G will make it Fmaj9. Without the E (maj7), it would be called Fadd9.
Comment: I forgot to add the big M. Sorry. At firat I thought this to be an Am7 chord with F, but if the Bass player is playing F then I suspect it should be an FM7 with G. Am I right?
Answer: FACEG gives F major 9, whichever note is wherever. More often than not, the lowest note will probably be F - the root, but could be voiced so that it's any of those.With an F at the very bottom, it's going to be Fmaj9 in root position.
Answer: There is always a danger of musicians treading on one another's toes whenever you have 2 instruments that both play chords playing together. Usually the guitar and piano take turns supplying the chords by prior arrangement. Or, one will provide the rhythm whilst the other supports this with punches and stabs.
Anyway, one possibility for your hypothetical scenario is that the complete chord is an Fmaj9. It really depends on function and where that G is in the mix (is it a 2nd or a 9th?) The result is the same. In this case it would probably sound like a dog's breakfast.
Comment: I often like to arrange my instruments in such a way in which they will play complex chord harmony but won't repeat each other. For instance I have a piece where the guitar constantly plays a sequence CGC-CG-CGBb-EbF, the bass plays C, then Ab in 4 bars, then F in 4 bars and Bb in 4 bars, afterward back to C, while I play above all this, when the Bass plays F, I play Ab chord. That's an intro to a song.

Leading Bass note


get points out of two lines where y distance is given value

Question: there are two lines form 3 point like so

Point 1 (1,2)
Point 2 (5,6)
Point 3 (7,1)

Lines are from

1 to 2

and from

1 to 3

what i need are the points on each line where the y (vertical) distance is at a given value
(as an example  2)
from constracting this figure i've got on Line 1 to 2 an approximate Point (2.8,3.8) and on Line 1 to 3 an approximate Point (2.8,0.8)
is there a mathematically to solve this, I will need this for a given x value as well?
Answer: Let the co-ordinates of two points be $A(x_1, y_1)$ and $B(x_2, y_2)$. The equation of the line AB is given by the "two point form", which is:-
$\dfrac {y – y_1}{x – x_1} = \dfrac {y_2 – y_1}{x_2 – x_1}$; where (x, y) represents any particular point on that line.
That equation can somehow be reduced to a form say ax + by + c = 0; where a, b, c will be some numeric values.
If D(h, k) is a point on that line and is the point you are interested in (with the value of k known as given), then the value of h can be found by solving for h from the equation a(h) + b(k) + c = 0.
The process will be the same for finding n of E(m, n) if m is known.


gradle exclude group from compile

Question: I am getting this duplicate error when building my app:

addJar(...facebookadapter-4.0.3.jar): entry
  duplicate entry: com/facebook/ads/AbstractAdListener.class

The reason I am getting this is that my app compiles Facebook modules one belongs to an adapter and one to its original SDK:

compile ('com.ironsource.adapters:facebookadapter:4.0.3@jar')
  compile 'com.facebook.android:audience-network-sdk:4.27.0'
      compile 'com.google.ads.mediation:facebook:220.127.116.11'

So as a solution, I am trying to exclude this group from the module which contains the adapter jar compile statement:
compile ('com.ironsource.adapters:facebookadapter:4.0.3@jar') {
    exclude (group: 'com/facebook/ads')
}

But, when I build my app again it fails to state the same reason from the same adapter
Any idea why the classes are not being excluded?
Comment: use `gradlew :app:dependencyInsight --configuration compile --dependency com.facebook.ads` to check where the dependency comes from
Answer: Looks like the exclude block syntax is incorrect. Try
compile ('com.ironsource.adapters:facebookadapter:4.0.3@jar') {
  exclude group: 'com.facebook.ads'
}

Update
So it looks like the facebookadapter contains this class inside. You can not exclude a class from a jar file, exclusion only works on per-dependency level.
If you absolutely need to have this adapter, you can try to exclude facebook ads transitive dependency from all the other dependencies.
configurations {
    all*.exclude group: 'com.facebook.ads'
}

Comment: Each dependecy declaration in Gradle defines a subtree:not only the actual library (a single jar file), but all the dependencies of this library as well (transitive dependencies, multiple jar files). The `exclude` directive allows you to exclude some of *transitive dependencies* (exclude several jar files).
In case of `com.ironsource.adapters:facebookadapter:4.0.3@jar` the `com/facebook/ads/AbstractAdListener.class` is a part of library, not a transitive dependency, you can not exclude it this way
Comment: That was my first try, both syntaxes give the same result
Comment: oh, so the class is inside the jar. That makes problem tricker, please see my update
Comment: Thanks, can you please elaborate on this line "You can not exclude a class from a jar file, exclusion only works on per-dependency level"

gradle exclude group from compile


GKE Dataplane v2 NetworkPolicies not working

Question: I am currently trying to move my calico based clusters to the new Dataplane V2, which is basically a managed Cilium offering.
For local testing, I am running k3d with open source cilium installed, and created a set of NetworkPolicies (k8s native ones, not CiliumPolicies), which lock down the desired namespaces.
My current issue is, that when porting the same Policies on a GKE cluster (with DataPlane enabled), those same policies don't work.
As an example let's take a look into the connection between some app and a database:
---
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: db-server.db-client
  namespace: BAR
spec:
  podSelector:
    matchLabels:
      policy.ory.sh/db: server
  policyTypes:
    - Ingress
  ingress:
    - ports: []
      from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: FOO
          podSelector:
            matchLabels:
              policy.ory.sh/db: client
---
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: db-client.db-server
  namespace: FOO
spec:
  podSelector:
    matchLabels:
      policy.ory.sh/db: client
  policyTypes:
    - Egress
  egress:
    - ports:
        - port: 26257
          protocol: TCP
      to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: BAR
          podSelector:
            matchLabels:
              policy.ory.sh/db: server

Moreover, using GCP monitoring tools we can see the expected and actual effect the policies have on connectivity:
Expected:

Actual:

And logs from the application trying to connect to the DB, and getting denied:
{
  "insertId": "FOO",
  "jsonPayload": {
    "count": 3,
    "connection": {
      "dest_port": 26257,
      "src_port": 44506,
      "dest_ip": "172.19.0.19",
      "src_ip": "172.19.1.85",
      "protocol": "tcp",
      "direction": "egress"
    },
    "disposition": "deny",
    "node_name": "FOO",
    "src": {
      "pod_name": "backoffice-automigrate-hwmhv",
      "workload_kind": "Job",
      "pod_namespace": "FOO",
      "namespace": "FOO",
      "workload_name": "backoffice-automigrate"
    },
    "dest": {
      "namespace": "FOO",
      "pod_namespace": "FOO",
      "pod_name": "cockroachdb-0"
    }
  },
  "resource": {
    "type": "k8s_node",
    "labels": {
      "project_id": "FOO",
      "node_name": "FOO",
      "location": "FOO",
      "cluster_name": "FOO"
    }
  },
  "timestamp": "FOO",
  "logName": "projects/FOO/logs/policy-action",
  "receiveTimestamp": "FOO"
}

EDIT:
My local env is a k3d cluster created via:
k3d cluster create --image ${K3SIMAGE} --registry-use k3d-localhost -p "9090:30080@server:0" \
            -p "9091:30443@server:0" foobar \
            --k3s-arg=--kube-apiserver-arg="enable-admission-plugins=PodSecurityPolicy,NodeRestriction,ServiceAccount@server:0" \
            --k3s-arg="--disable=traefik@server:0" \
            --k3s-arg="--disable-network-policy@server:0" \
            --k3s-arg="--flannel-backend=none@server:0" \
            --k3s-arg=feature-gates="NamespaceDefaultLabelName=true@server:0"

docker exec k3d-server-0 sh -c "mount bpffs /sys/fs/bpf -t bpf && mount --make-shared /sys/fs/bpf"
kubectl taint nodes k3d-ory-cloud-server-0 node.cilium.io/agent-not-ready=true:NoSchedule --overwrite=true
skaffold run --cache-artifacts=true -p cilium --skip-tests=true --status-check=false
docker exec k3d-server-0 sh -c "mount --make-shared /run/cilium/cgroupv2"

Where cilium itself is being installed by skaffold, via helm with the following parameters:
name: cilium
remoteChart: cilium/cilium
namespace: kube-system
version: 1.11.0
upgradeOnChange: true
wait: false
setValues:
  externalIPs.enabled: true
  nodePort.enabled: true
  hostPort.enabled: true
  hubble.relay.enabled: true
  hubble.ui.enabled: true

UPDATE:
I have setup a third environment: a GKE cluster using the old calico CNI (Legacy dataplane) and installed cilium manually as shown here. Cilium is working fine, even hubble is working out of the box (unlike with the dataplane v2...) and I found something interesting. The rules behave the same as with the GKE managed cilium, but with hubble working I was able to see this:

For some reason cilium/hubble cannot identify the db pod and decipher its labels. And since the labels don't work, the policies that rely on those labels, also don't work.
Another proof of this would be the trace log from hubble:

Here the destination app is only identified via an IP, and not labels.
The question now is why is this happening?
Any idea how to debug this problem? What could be difference coming from? Do the policies need some tuning for the managed Cilium, or is a bug in GKE?
Any help/feedback/suggestion appreciated!
Comment: Please provide more details about your first environment and your corrent env. So at first you had local cluster on K3d and then you moved to GKE and created new cluster with `Dataplane V2` enabled? Did you follow any documentation? Are you using `default GCE Service Account` for GKE VMs? Did you try to check [this troubleshooting guide](https://cloud.google.com/kubernetes-engine/docs/how-to/dataplane- v2)? Could you also confirm if your environment/setup don't hit any of the limitations [form here](https://cloud.google.com/kubernetes-engine/docs/concepts/dataplane-v2#limitations)?
Comment: Is your db pod still listening on port 26257?
Also, maybe just an issue with you masking the namespaces in the policy you posted, but are the ingress and egress policies targeting the same or different namespaces?  The policy has different namespaces but the error shows the same.
Comment: @PjoterS thanks for the response, I have added my k3d setup to the issue. Yes, the clusters are created from scratch with dataplaneV2, I see no errors in anted pods, and some policies (like DNS) work, while others do not.
Comment: @GariSingh: Yes, the app is listening on that port. What do you mean by masking? I am using the [AutoLabel](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/#automatic-labelling) feature as policies operate on labels and not namespace names. The db server is in namespace BAR and client in FOO
Comment: @Demonsthere - I just assumed the labels matched the namespaces.  I could be reading things wrong, but looks like the policy allows Egress to BAR and Ingress from FOO but the error message seemed to show that both src and dest were in FOO?
Comment: @GariSingh yes, the `db-server.db-client` policy is in the BAR ns, and allow ingress connections from the FOO ns for all pods with the label `policy.ory.sh/db: client`.
Likewise, the `db-client.db-server` policy is in the BAR namespace, and allows all pods with the label `policy.ory.sh/db: client` to connect to namespace FOO, pods with the `policy.ory.sh/db: server` label on port `26257`

In the GKE log we can see that the connection is being block on the egress route of the connection, so client -> server
Comment: What GKE version are you using? Did you try to deploy cilium using Helm? Could you share all your steps how did you create Cluster, deployed cilium? I've tried docs but it seems like its outdated. Do you have any pod with name `anetd-` in your cluster?
Comment: Hello, how did you see those monitoring resources? I am having a very similar problem, but not using ArgoCD
Comment: @SachinMeier With the help of [Hubble GKE exporter](https://github.com/rueian/gke-hubble-export) ;)
Answer: Update: I was able to solve the mystery and it was ArgoCD all along. Cilium is creating an Endpoint and Identity for each object in the namespace, and Argo was deleting them after deploying the applications.
For anyone who stumbles on this, the solution is to add this exclusion to ArgoCD:
  resource.exclusions: |
    - apiGroups:
      - cilium.io
      kinds:
      - CiliumIdentity
      - CiliumEndpoint
      clusters:
      - "*"

Comment: This is also a solution for anyone on DigitalOcean, which has cilium.io enabled on their managed Kubernetes clusters. You'll need to add the above to argocd-cm file. Learn more on https://argo-cd.readthedocs.io/en/stable/operator-manual/declarative-setup/ and see example on https://github.com/argoproj/argo-cd/blob/master/docs/operator-manual/argocd-cm.yaml


How to calculate individual moments of a 2-dimensional distribution via Monte Carlo Integration

Question: I've recently been using Monte Carlo integration to calculate a particular integrals which I can do fine but I've hit a problem where I can't calculate the individual moments of my distribution for each dimension, and I'm not entirely sure what to do.
For example, let's say I have a unnormalised 2-dimensional Gaussian centred at (3,3) with a standard deviation of (1,1), i.e. the covariance is the identity matrix. This can be described by,
$$ f(x,y) =  e^{-0.5((x-3)^2+(y-3)^2)}$$
and to calculate the integral, $I$, via Monte Carlo can be done by,
$$I = \int_{-\infty}^{\infty} f(x,y) \ dx \ dy = \int_{-\infty}^{\infty} \frac{f(x,y)}{p(x,y)}p(x,y) \ dx \ dy = \langle f(x,y) \rangle _{x,y \sim p(x,y)} \approx \frac{1}{N} \sum_{i}^{N} \frac{f(x_{i},y_{i})}{p(x_{i},y_{i})}$$
and by the law of large numbers this will equal the integral, $I$, as $N \rightarrow \infty$.
Now, in order to calculate the moments of my distribution I essentially repeat the same process but with a factor of $x^{a}$ or $y^{a}$ where $a$ is the order of the moment of the distribution. In the case of $a = 1$ for x would be the centre of x, and would be calculated by,
$$I = \int_{-\infty}^{\infty} x f(x,y) \ dx \ dy = \int_{-\infty}^{\infty} \frac{x f(x,y)}{p(x,y)}p(x,y) \ dx \ dy = \langle x f(x,y) \rangle _{x,y \sim p(x,y)} \approx \frac{1}{N} \sum_{i}^{N} \frac{x_{i} f(x_{i},y_{i})}{p(x_{i},y_{i})}$$.
But the thing is, when I calculate this I get the answer to be 9, instead of 3 which is the centre for x. Interestingly enough, this method seems to give the product of the centres. As in, I changed the centre to be (3,2) and the answer is 6 in this case. For reference, the samples of x and y are drawn from a model probability distribution which approximates f(x,y). This is because the probability distribution with minimal variance is proportional to the function you're integrating.
Has anyone calculated moments of distributions via Monte Carlo Integration? If so, how can one integrate just purely along $x$ or $y$ when the function returns just $f(x,y)$. Do I need to times the expression by p(y) and assume p(x,y) can be approximated by $p(x,y) \propto p_x(x) p_y(y)$. If that's the case I'm not sure how to do that as the function for p(x,y) returns just a scalar value for the joint probability at that point in the xy-plane.
Many thanks in advance for the help!
Answer: Monte Carlo is a very broad set of techniques, what you are doing is importance sampling. And unless you make adjustments, importance sampling requires access to probability densities and not just regular unnormalized functions. Are you making this adjustment? If not, your true density is
$$\hat f(x,y) = \frac{f(x,y)}{Z}, $$
where $Z$ is the normalizing constant. If you don't have access to the normalized density, you should adjust for it via
$$\sum_{i}^N \frac{x_i \frac{f(x_i, y_i)}{p(x_i, y_i)}}{\sum_j^N \frac{f(x_j, y_j)}{p(x_j, y_j)}}.$$
In this way, the numerator and denominator both contain the ratio of normalizing constants, and they subsequently cancel.
But if you are doing things correctly, it should work. You are estimating the mean of the function $g(x,y): \mathbb R^2 \rightarrow \mathbb R$ given by $g(x,y) = x$ under your distribution. By Fubini's theorem, you can therefore just switch the order of the integrals and
$$\int g(x,y) \hat f(x,y)dx dy = \int x \left (\int \hat f(x,y) dy \right )dx = \int x \hat f(x), $$
where I by $\hat f$ denote the normalized density (not that it matters for Fubini's theorem to be applicable here.) Thus it is legal to estimate the mean of $g(x,y)$ just by looking at the marginal. In practice, we can just discard samples from the dimensions we do not care about and just directly use the remaining.
Comment: The split was more to underscore the legality of your approach. but yes, in your  particular case you don't even need to simulate $y$, per the fact that a marginal of a Gaussian is just a Gaussian again with the mean and covariance corresponding to the restricted mean and covariance.
Comment: Right, thanks for the help! It turns out I can also just plug a x factor and integrate like before. So, $\langle x \rangle \approx \frac{1}{N} \sum_{i}^{N} \frac{x_{i}f(x_{i},y_{i})}{p(x_{i},y_{i})}$ and likewise for y and higher order moments for the distribution!
Comment: Thanks for quick response, @Forgottenscience! I'm sure my probability density is normalised because when I calculate the expectation of function, i.e. the integral, I get the correct results within the error of the standard deviation. So, with the last comment if I'm to calculate the first moment for X I need to split f(x,y) and p(x,y) into two forms of f(x,y) $\propto$ f_x(x)f_y(y) and likewise for p(x,y) as I stated above? Then just do $\frac{1}{N} \sum_i (x_i f_x(x_i)/p_x(x_i))$?
Comment: So, $p_x(x) \approx f_x(x) = e^{-0.5((x-3)^2)}$ and do $\frac{1}{N} \sum_{i}^{N} \frac{x_i f_x(x_i)}{p_x(x_i)}$ to calculate the 1st-order moment for x (likewise for y, and for higher order moments)


I have a script for tkinter but need to save the user's input and store it in a variable

Question: I found this script that creates a window with numerous buttons and a text box but I'm wondering if anyone can help me gather the user's input after selecting a button or pressing the enter key after typing in the text box
#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of the Tkinter frame
win.geometry("750x250")

#Define a function to update the entry widget
def entry_update(text):
    entry.delete(0,END)
    entry.insert(0,text)

#Create an Entry Widget
entry= Entry(win, width= 30, bg= "white")
entry.pack(pady=10)

#Create Multiple Buttons with different commands
button_dict={}
option= ["button 1", "Button 2", "Button 3", "Button 4","button 5","button 6"]

for i in option:
    def func(x=i):
        return entry_update(x)

button_dict[i]=ttk.Button(win, text=i, command= func)
button_dict[i].pack()

win.mainloop()

I tried to edit the "entry" portion of the code and store it as a variable but other than that I'm completely clueless on how to use the Tkinter module
Answer: You can just declare a variable to store the input using global, store the text in your entry box into that variable whenever the button is clicked, and print it out.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of the Tkinter frame
win.geometry("750x250")

#Define a function to update the entry widget
def entry_update(text):
   entry.delete(0,END)
   entry.insert(0,text)

#Create an Entry Widget
entry= Entry(win, width= 30, bg= "white")
entry.pack(pady=10)

#Create Multiple Buttons with different commands
button_dict={}
option= ["button 1", "Button 2", "Button 3", "Button 4","button 5","button 6"]

for i in option:
   def func(x=i):
      global input_text #declare variable
      input_text = entry.get() #get data from box
      print(input_text) #print the data
      return entry_update(x)

   button_dict[i]=ttk.Button(win, text=i, command= func)
   button_dict[i].pack()

win.mainloop()

Comment: Thank you, it really helped, sorry for the late response bu8t it worked excellently, thank you for the input


How to grant access to a user to all content created by certain users?

Question: I've been looking all the options commented on Controlling Acces to Content Overview but I don't see any that allow one particular user to access all content created by other particular users.
Something like: User A have permissions to see all nodes created by users B, C and D.
(No need to include a reference or a taxonomy term to each node).
Any insights?
Thank you so much!
Answer: Sorry telling you that as far as I know there is nothing like this out of box.
Maybe if you mention the requirement we will be able to help you.
For now don't think about users and think about roles. if you want to make it more flexible I suggest using workbench access so the created content will have a section (Taxonomy term) and the section will be accesed by user A and B only.
Hope that help
Comment: Thanks for your answer! About what you say about thinking about roles, not users, it is possible to grant access to one role to all the nodes another rol can access? Rol A has access to all nodes created by users with rol B?
What I'd like is that one specific user can see what a group of users do, another specific user can see what another group of users do and so on.


Tessitura of a piece

Question: How do you find the tessitura of a piece? I know you're looking for the lowest and highest notes but where exactly are you looking for them? Are you looking for the lowest and highest notes in a particular place like the melody or harmony? Or are you looking for the lowest and highest notes in the entire peice?
Answer: You're not neccesarily looking for just the highest or lowest notes. If the song has a lot of high notes it's said to have a high tessitura. This doesn't mean that it contains notes that are too high or nearly too high to sing comfortably, but that the voice will be singing towards the top of its range for a fair bit of the song. The same goes for a low tessitura.As far as what proportion of the song - don't know!
Comment: It's too early yet to say accepted answer - there may be better ones after the weekend, when everyone's back at work with nothing else to do!
Answer: The tessitura of an aria/song is where the majority of the notes lie within the range of the Aria/song.  The range is the highest and lowest note.  If the Aria's highest note is A5 (middle C is C4) and the lowest note is A3, that makes the Aria 2 octaves.  That is within a soprano or a mezzo range.  How to tell if the aira belongs to the soprano rep or a mezzo rep?  Look at the tessitura of the aria.  If most of the notes are from A4 to A5 then it is soprano aria with some low notes.  If most of the notes tessitura are between A4 and A3 then it is a mezzo aria with high notes.
Aristo Vocal Performance Studio
Answer: I have not found a good operational definition of tessitura. However, the first thing that comes to mind is to compute (for a piece or collection of pieces) the pitch times the duration of each note. Then the cumulative distribution from lowest to highest notes can be plotted (or tabulated). Next take the 25%-75% sub range (which contains at least half of the note durations) and use that as the basis for the tessitura. Measures within that sub range could be the mean, or median, or mode. (Arithmetic average or midpoint or most common note*duration value respectively.)
The above suggestion is a bit crude in that some pieces may have sections centered around a low note and another section around a high note. Such pieces should probably have two separate measurements. That's a musical not a mathematical judgement.
Likewise, my suggested 25%-75% range may not be best; perhaps 10%-90% or something else. (Again a musical, not a mathematical judgement.)
Comment: I guess 'mode' is closest to what this is. Not heard of duration of notes, only frequency ( as in how often they occur!)
Comment: The little I did find researching automatic tessitura evaluation took durations. The idea is that singing note for 8 beats should count more than singing one for 1 beat. One could weight things differently say by the square root of durations or something.
Answer: There's range and there's tessitura.  You know what range is.  Tessitura is more subtle, it's sort of the centre of gravity of the piece.  Like the composer knew where a singer's 'best notes' were and made full use of them.

Tessitura of a piece


Definição na IDE phpstorm

Question: Uso a IDE phpstorm para programar eu já procurei e não consegui tirar tipo um traço que aparece no meu código que me faz confusão ao programar.

Quero tirar o traço que que aparece sempre em maior parte do código, quero tirar isso para o código aparecer limpo indicando erros quando os houver.
E possível ?
E queria também se alguém souber eu usei o tema Material através do seguinte site https://laravel-news.com/material-theme-for-phpstorm.
No site a imagem do tema as cores do código são diferentes ao que tenho na minha IDE depois de instalado o tema não ficou com as cores da imagem do site do tema.
Queria saber como posso por as cores como tem na imagem do site do tema que indiquei acima
Answer: O que gera isso é a Inspection chamada Typo, porque suas variáveis estão em português.
Você pode desabilitar ou mudar as configurações dele dentro das opções do PHPStorm, em Editor > Inspections > Spelling > Typo.

Definição na IDE phpstorm


hide element in another parent

Question: How would i go about hiding or showing an element that is contained in a container, based on another container's hover state?
Here's what i have so far, as an example:
HTML5

                    Find an Application

                <input type="text" value="Enter app name here" onclick="Clear(this, 'Enter app name here');" onblur="Reset(this, 'Enter app name here');" />

CSS3
div.left-menu-container {
    float: left;
    width: 19%;
    padding-right: 1%;
}

div.left-menu-inner-container {
    width: 100%;
}
div.left-menu-item-container
{
    width:100%;
}

div.left-menu-item-first {
    width: 93%;
    border: 1px solid #999;
    -webkit-border-top-right-radius: 10px;
    -moz-border-radius-topright: 10px;
    border-top-right-radius: 10px;
    transition: 0.15s ease-in-out;
    color: black;
    min-height: 26px;
    padding-left: 1%;
}

    div.left-menu-item-first:hover {
        width: 97%;
        border: 1px solid #999;
        color: white;
        background-image: linear-gradient(rgb(44,119,208),rgb(27,90,159));
        padding-left: 3%;
    }

div.left-menu-item-container .sub-menu {
    width: 97%;
    border: 1px solid #999;
    color: white;
    background-image: linear-gradient(rgb(44,119,208),rgb(27,90,159));
    padding-left: 3%;
    display: none;

}

div.left-menu-item-first:hover left-menu-item-container.sub-menu {
    position:absolute;
    width: 80%;
    border: 1px solid #999;
    color: white;
    background-image: linear-gradient(rgb(44,119,208),rgb(27,90,159));
    float:left;
    display: block;
    z-index: 1000;
    float: left;
}

However, that simply does not work. Hovering over the left-menu-item-first div does not show the submenu contained in the left-menu-item-container parent. Do they really and absolutely must be children of the parent for this to work with Pure CSS? I can and already had a JQuery version setup and going but i wanted to do it via CSS only if possible.
Comment: There is no parent selector in Css.
Comment: @SpencerMay that does not help op though, altering another element using css alone is only possible for child and sibling elements. never a different independent one...
Answer: Since there is no CSS parent selector, try altering your html such that the hovered item is a sibling of left-menu-item-container.sub-menu
Try using a CSS sibling selector:
Change:
div.left-menu-item-first:hover left-menu-item-container.sub-menu

to
div.left-menu-item-first:hover + left-menu-item-container.sub-menu

Or
Change:
div.left-menu-item-first:hover left-menu-item-container.sub-menu

to
.left-menu-link:hover + left-menu-item-container.sub-menu

Comment: You are right MaxOvrdv - You will need to make the hovered element a sibling.
Answer: You can only alter child elements and sibling elements on hover, never a completely different element.
if you put the submenu right after the first menu element, you can use the sibling selector + as follows:

div.left-menu-container {
    float: left;
    width: 19%;
    padding-right: 1%;
}

div.left-menu-inner-container {
    width: 100%;
}
div.left-menu-item-container
{
    width:100%;
}

div.left-menu-item-first {
    width: 93%;
    border: 1px solid #999;
    -webkit-border-top-right-radius: 10px;
    -moz-border-radius-topright: 10px;
    border-top-right-radius: 10px;
    transition: 0.15s ease-in-out;
    color: black;
    min-height: 26px;
    padding-left: 1%;
}

    div.left-menu-item-first:hover {
        width: 97%;
        border: 1px solid #999;
        color: white;
        background-image: linear-gradient(rgb(44,119,208),rgb(27,90,159));
        padding-left: 3%;
    }

div.left-menu-item-container .sub-menu {
    width: 97%;
    border: 1px solid #999;
    color: white;
    background-image: linear-gradient(rgb(44,119,208),rgb(27,90,159));
    padding-left: 3%;
    display: none;

}

.left-menu-link:hover + .sub-menu {
    position:absolute;
    width: 80%;
    border: 1px solid #999;
    color: white;
    background-image: linear-gradient(rgb(44,119,208),rgb(27,90,159));
    float:left;
    display: block;
    z-index: 1000;
    float: left;
}

                    Find an Application

                <input type="text" value="Enter app name here" onclick="Clear(this, 'Enter app name here');" onblur="Reset(this, 'Enter app name here');" />

Comment: @MaxOvrdrv correct, but you can work around that as well. simply attach the hover to the link
Comment: that would be great. But the problem i have and don't want to have is that the link should only cover the first div, not the submenu, which means that they are no longer siblings, correct?
Comment: @MaxOvrdrv i have updated the answer, see if its more convenient to implement
Comment: thank you... changing the hovering CSS to use the link as well as the div, and then using the sibling clause, it works!

hide element in another parent


R cv.glm returns NaN for stepwise-generated regression model

Question: I'm trying to run K-fold cross-validation on a multiple regression model that was generated via the step function in R. However, the call to cv.glm returns NaN.
Here is a simplified script that replicates the problem:
# this works just fine
library(boot)
data(mammals, package="MASS")
mammals.glm <- glm(log(brain) ~ log(body), data = mammals)
cv.glm(mammals, mammals.glm, K=5)$delta

# but when I use the step function...
mammals.simple <- lm(("brain ~ 1"), data=mammals)
mammals.glm <- step(mammals.simple, direction="forward", test="F", scope="brain ~ body")
# it returns NaN
cv.glm(mammals, mammals.glm, K=5)$delta

Is this due to some fundamental misunderstanding, where it doesn't make sense to cross-validate a stepwise-generated model?
I'm using R v3.0.1 (but 3.1.0 has the same problem).
Comment: Velcome to our site!
Comment: Thanks :) hope this question isn't a misuse. It seems like there's a blurry line between stackoverflow and crossvalidated...
Answer: I was running into the same problem but figured out that I was using lm to build the model rather than glm.
From your code above:
mammals.simple <- glm(("brain ~ 1"), data=mammals)
mammals.glm <- step(mammals.simple, direction="forward", test="F", scope="brain ~ body")
it returns NaN
cv.glm(mammals, mammals.glm, K=5)$delta
Using your code with glm rather than lm I get:

cv.glm(mammals, mammals.glm, K=5)$delta
  [1] 155504.4 146724.9


writing image data to text file to creat BMP file

Question: I have 1x1 pixel image in BMP. I opened it in notepad. Select ALL and paste the whole data over Serial port monitor, to see what exactly character are in the file..whatever...
  I simply copy the data of BMP file opened in notepad and paste it in another text file, save it as .BMP extension. But no IMAGE is formed. as invalid BMP file.
   when I check the properties of both images (original image and   the image i created by copying the data to new file) by right clicking on it, there is difference in advance information. whats the problem? how can I do that.
  I have image data in my Controller and want to save it on SD-card as bmp image....
Answer: cp ./image.bmp ./image-copy.bmp
This will allow you to copy a bitmap to another file which contains a valid copy of the original bitmap on Unix-like operating systems. In Windows, use copy file.bmp file-copy.bmp.
What you're looking for is a hex editor, if you want to view the actual binary data of the file. Notepad represents certain unprintable characters as completely different printable characters. When you open any binary data file into Notepad and copy its contents to the clipboard, you are not actually copying the binary data. You are copying Notepad's attempt to translate unprintable data into viewable data.


Why did we let z = k for this equation & How it has infinite solutions?

Question: $A=\left(\begin{array}{ccc}1 & 3 & -2 \\ 0 & -7 & -8 \\ 0 & 0 & 0\end{array}\right)$
This is the equation which written in its linear equation form becomes
$\begin{cases}X + 3Y -2Z = 0 \\
-7Y + 8Z = 0 \end{cases}$
According to videos on youtube to this question and online , where they write:
Let Z = K i.e always
Q1: My question is why ? Why not just go with Z ?
Going on to next step:
$Y = \frac{8K}{7}$
Therefore ,
$X + \frac{8K}{7} -2Z = 0 $
In end we will get $x = -8z $
Q2: Now , My question is: How is that infinite solutions.
Comment: Q1: You can indeed stay with Z. "Y = $\frac{8K}{7}$
": no, $y=\color{red}-\frac{8K}7.$
"X + $\frac{8K}{7}$ -2Z = 0 In end we will get x = -8z": no. $x+3(-\frac{8K}7)+2z=0$ and we get $x=\frac{24K}7+2z=\frac{38z}7$ (but this does not fundamentally affect your questions) Q2: the solutions are $(x,y,z)=(38z/7,-8z/7,z)$ for *every* possible value of $z$. e.g. $(x,y,z)=(38,-8,7)$ or $(38\pi,-8\pi,7\pi).$
Comment: "*How is that infinite solutions*" $\;-\;$ Because you get a different solution for each $k$, where $k$ is any arbitrary number you choose.
Comment: For this particular solution we can comprehend what you mean. However, it will benefit you in the long run if you learn to phrase your question systematically and ensure you include all necessary information.
Comment: @dxiv I didnt get what u mean.
Comment: @RezhaAdrianTanuharja K. Could you also tell me what more info should I share. I will surely next time.
Comment: @S.M.T Calculate $x,y,z$ for $k=1$, that's one solution. Calculate $x,y,z$ for $k=2$, that's another solution. Calculate $x,y,z$ for $k=\pi^2 + \frac{1}{e}$, that's yet another solution. Should be pretty obvious that there is infinitely many of them.
Comment: @dxiv There is no difference in k or z ? So , youre actually saying to calculate x,y for z = 1. I am not able to understand what you meant here sir?
Comment: @dxiv The next thing is that x = -8z. So , it actually means to say is that x is -8 times value of z.
Comment: @dxiv The question is. How can we assume any value for z ? We cant say any value of k or z we can assume is what i think. Could u explain more as to what you meant
Comment: @S.M.T Not sure what you mean. For a simpler example, suppose you had just one equation in two variables $x+y=0$. This has infinitely many solutions of the form $(x,y)=(k,-k)$ where $k$ is any real number, because each such pair satisifies the equation $k+(-k)=0$. Your case is entirely similar, except with two equations in three variables.
Comment: In general, to specify a system of equations in three variables we need more than just a $3\times3$ matrix. This and the errors pointed out in a previous comment suggest that there are vital parts of this problem you have omitted. It might help if you include a link in the question to the place where you found this problem; that is, don't just write "as per videos on youtube to this question and online", give us links so we can look it up.
Answer: (1) Background in social terms , which may aid a little :
Imagine looking some Image having 2 young girls with a woman in the middle.
You ask : "Who is that woman ?" , Answer : "Oh , She is the mother of the 2 young girls !"
You : "Ok , Who is the girl on the right ?" , Answer : "She is the younger sister of the girl on the left !"
You : "hmmm , Who is the girl on the left ?" , Answer : "She is the Daughter of the woman in the middle !"
Did we get some information out of the Questions & Answers ? No , we got answers to unknown items in terms of unknown items.
If at least 1 Question had been answered in terms of known items , we would know everything.
Eg : You ask : "who is that woman ?" , Answer : "oh , she is Michelle Obama !"
We can make out that the girl on the left is Malia , the girl on the right is Sasha.
(2) Background in algebraic terms :
You ask : "what is x ?" , Answer : "x is twice y".
You ask : "ok , what is y ?" , Answer : "y is thrice z".
You ask : "hmmm , what is z ?" , Answer : "z is z itself".
Did we get some information out of the Questions & Answers ? No , we got answers to unknown items in terms of unknown items.
If at least 1 Question had been answered in terms of known items , we would know everything.
Eg : You ask : "what is z ?" , Answer : "z is 6"
We can make out that y is 18 , x is 36.
In Math/arithmetic/algebra Questions , we may be given (or get though analysis) unknowns in terms of other unknowns. We may be tasked with finding (or want to know) the values of those unknowns.
We should avoid giving Solutions where we list the unknowns in terms of other unknowns in the Answers.
We should try to give the Solution in terms of known values.
(3) Coming to given Equations :
The matrix $A$ multiplied by a vector of unknowns gives the $0$ vector.
That gives these Equations :
$ X + 3Y  -2Z = 0$
$0X - 7Y + 8Z = 0$
$0X + 0Y + 0Z = 0$
When there are no Solutions , we can simply say that & more on.
When there is one Unique Solution , we can simply list that & more on.
In given Case , we see that there are unlimited Solutions ( you can check Simultaneous Equations or Advanced Matrix theory to know more ) , hence we say that we will introduce a "free" variable $k$ , which is "known" to us , because we can assign to it whatever value we want.
Then we say that the Solution ( for each value of $k$ ) is :
$z=k$
$y=8k/7$
$x=-2k/7$
All unknowns are in terms of knowns.
This answers your Q1.
When $k=0$ , we have $(x,y,z)=(0,0,0)$.
When $k=70$ , we have $(x,y,z)=(-20,80,70)$.
When $k=-70$ , we have $(x,y,z)=(20,-80,-70)$.
Every value of $k$ gives a Solution , hence there are infinite number of Solutions here.
This answers your Q2.
When we do not use $k$ , & give Solution in terms of $z$ , then it is weird. We might assign a value to $z$ which is invalid , which is not there in Current Case , but can happen in other Case where $z$ is larger than some number , or other Case where $z$ is not larger than 100 , or other Case where $z$ is Even , Etc.
When we use $k$ , we can assign which-ever value we want , without concerns about invalid values.
(4) Example where new variable is very much necessary :
When we are given $x^2+y^2-4=0$ , we should avoid giving the Solutions like $(x,y)=(x,\sqrt{4-x^2})$ , where we are giving the unknown in terms of the unknown.
We can not even let $x=10,-10,100,-100$ & try to get $y$ , which will be Complex or Imaginary.
Parametric Solution is better :
$(x,y)=(2\sin{\theta},2\cos{\theta})$ , where we introduce new variable $\theta$ which is in our control.
Every value of $\theta$ gives a Solution.
In this Case , the Solutions will repeat , though there are Cases where Solutions do not repeat.
Comment: The moment you write $z=k$ you confirm that $z$ is just as good a free variable as $k$. How do you know it is OK to write $z=k$ if $k$ could be any value and you are not sure that $z$ can be any value?
Comment: That is a little beyond the Scope of this Question , @DavidK , OP wants to know (Q1) why $k$ was used , when Solution can be in terms of $z$ itself (Q2) Why we say there are infinite number of Solutions. I have covered both Points in Section (3). We can plug-in the Solution to check that it works for all $k$. My Section (4) is beyond that Scope to give Examples where new variable is necessary.
Comment: What I was trying to illustrate in my comment was why your Section 3 fails to answer Q1. You cite disadvantages of using $z$ but each one of them applies equally to $k$. There are some actual advantages to using a new variable, but you didn't mention any of them (and in my opinion, it is "weird" to use $k$ in particular as the new variable).
Comment: Maybe your Comment "There are some actual advantages to using a new variable" should be elaborated & converted into Answer format , @DavidK , which may throw more Insight on this. I used the words "avoid" & "weird" , in a loose way. I may not want somebody to claim to know the Exact value of $\pi$ & then give that Exact value in terms Square of $\sqrt{\pi}$ which is not wrong. Like-wise , I may not want to know $(x,y,z)$ in terms of $z$ , though it is not wrong. Some Authors are ok with $z$ , some Authors avoid that & choose $k$ , I myself am ok with either , provided the usage is Consistent !
Comment: I have not posted an answer because the question itself is improperly asked. I am waiting for OP to provide the missing information so that I will know what the question really is.
Comment: I can see the 2 Doubts/Questions OP gave & I have attempted to Answer/Explain Both , in general terms , @DavidK , When OP gives more Details , we might add some thoughts on the Particular Exact Case , though the generality will still be valid.


Preciso de uma mascara que sempre coloque o sinal de negativo na frente do valor digitado

Question: Preciso que fique da seguinte forma:
-20,00
Comment: Publique os código que você já tentou e as dificuldades enfrentadas e justifique o porque de não ter conseguido fazer a mascara.
Comment: Olá Marcos Ricardo, bem-vindo! Leia esse post para que não fechem ou negativem suas perguntas https://pt.stackoverflow.com/help/mcve
Comment: Interessante também marcar a resposta que lhe serviu  como aceita, veja como e porque nesse post https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Comment: Obrigado à todos, consegui tirar minha duvida com as duas respostas obtidas e tirei total proveito de uma delas. Sou iniciante no stack!
Answer: Uma implementação bem simples para esse problema:

$('#mask').keyup(function(){
  if((this.value.search('-') == -1 && this.value.length > 0 )){
    $(this).val('-' + this.value);
  }
})

<input type="text"  id="mask" >Máscara
Comment: Obrigado amigo! Resolveu muito bem.
Answer: Basta concatenar o sinal - (menos) ao valor retornado

$('input').change(function(){
 var input = "-" + ($('#numInput').val());

 console.log(input);

});

<input id="numInput">

Para utilizar em cálculos matemáticos requer transformar a virgula em ponto

$('input').keyup(function(){
var input = "-" + $($(this)).val().replace(',','.');

 var result = ((100+parseFloat(input)).toFixed(2));

 console.log(result);

 var resultVirgula = result.replace('.',',');

 console.log(resultVirgula);

});

<input id="numInput">


Declaration of template specialization on a template function

Question: I'm getting undefined reference to ´long long fromBigEndin<long long>(unsigned char*)´ for a template specialization.
See code here: https://onlinegdb.com/AagKTQJ2B
I have this structure:
util.h
template <class T>
T fromBigEndin(uint8_t *buf);

template <>
int64_t fromBigEndin<int64_t>(uint8_t *buf);
template <>
long long fromBigEndin<long long>(unsigned char *buf);

util.cpp
template<class T>
T fromBigEndin(uint8_t *buf) {
    T number = 0;
    uint8_t nBytes = sizeof(T);
    uint8_t i;

    for (i = 0; i < nBytes; i += 1) {
        number += buf[i] << (16 * (nBytes - i - 1));
    }

    return number;
}

headerImpl.h
#include "util.h"

void handleOpenSession(uint8_t *data) {
    uint8_t *uid = (uint8_t *)malloc(8);
    memcpy(uid, data + 1, 8);
    int64_t uidNbr = fromBigEndin<int64_t>(uid);
}

From @AnoopRana response, putting the implementation in header file works, I would like to know if it is possible to put the implementation in a separate file.
Any idea on how could I force the compilation of fromBigEndin<int64_t>()?
I've also tried to move the specializations to util.cpp but doesn't work either.
The code itself works when in a single file and with different declarations:

https://www.mycompiler.io/view/9YRi89BnZa0
https://www.mycompiler.io/view/HvvI1H6RUWi
Comment: Seems for classes it it possible: https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file, what I'm asking is if it is possible to do it with functions
Comment: Method 2 works now. I have updated the example. Earlier i made small typo in method 2 so that's why it were' working. See [demo method 2](https://onlinegdb.com/wiuwROG4f)
Answer: Method 1
You need to put the implementation of the function template into the header file itself. So it would look something like:
util.h
#pragma once  //include guard added
template <class T>
T fromBigEndin(uint8_t *buf);

//definition
template <> int64_t fromBigEndin<int64_t>(uint8_t *buf)
{
    return 53;
}
//definition
template <> long long fromBigEndin<long long>(unsigned char *buf)
{
    return 54;
}

//implementation in header file itself
template<class T>
T fromBigEndin(uint8_t *buf) {
    T number = 0;
    uint8_t nBytes = sizeof(T);
    uint8_t i;

    for (i = 0; i < nBytes; i += 1) {
        number += buf[i] << (16 * (nBytes - i - 1));
    }

    return number;
}

headerImpl.h
#pragma once
#include "util.h"

void handleOpenSession(uint8_t *data) {
    //add code here
}

main.cpp
#include <iostream>
#include "util.h"
int main()
{

    return 0;
}

Working demo
Method 2
Here we make use of explicit template instantiations.
util.h
#pragma once
#include <cstdint>
template <class T>
T fromBigEndin(uint8_t *buf);

headerImpl.h
#pragma once
#include "util.h"

void handleOpenSession(uint8_t *data) {
    uint8_t *uid = (uint8_t *)malloc(8);
    memcpy(uid, data + 1, 8);
    int64_t uidNbr = fromBigEndin<int64_t>(uid);
}

util.cpp
#include "util.h"

template<class T>
T fromBigEndin(uint8_t *buf) {
    T number = 0;
    uint8_t nBytes = sizeof(T);
    uint8_t i;

    for (i = 0; i < nBytes; i += 1) {
        number += buf[i] << (16 * (nBytes - i - 1));
    }

    return number;
}

//no angle brackets used here
template int64_t fromBigEndin<int64_t>(uint8_t *buf);
template long long fromBigEndin<long long>(unsigned char *buf);

main.cpp

#include <iostream>

#include "util.h"
int main()
{

    return 0;
}

Working demo
Comment: Yes, this works, but I'm trying to put the implementation on a cpp separate file. From what I've seen it seems possible to put it separated, if it is not, I will accept this solution
Comment: This is the question, when I try method 2, it fails with `undefined reference`
Comment: If you try it, it does not work
Comment: I have the demo, but cannot save (don't have an account) I will save in brief
Comment: Check method 2 error here: https://onlinegdb.com/AagKTQJ2B
Comment: @Miquel I made a small typo while writing method 2. [Here](https://onlinegdb.com/hYABMh6eS) is the updated link. Note there should be no angle brackets as commented in my demo example.


Using generating functions, Find a closed formula to next expression: $\sum_{k=0}^m{k(k+2)}$

Question: Using generating functions, Find a closed formula to next expression:
$\sum_{k=0}^m{k(k+2)}$
If i use calculus power series rules, The question is fairly simple. But how can i find the proper relation with generating functions?
Comment: Hint: given two power series $f,g$, what are the coefficients of the product $fg$ in terms of the coefficients of $f$ and $g$ ?
Answer: First note that
$$\sum_{k=0}^nk(k+2)x^k=\sum_{k=0}^n(k+1)^2x^k-\sum_{k=0}^nx^k\;.$$
The last summation is a geometric series, so you know a closed form for it. Next, check that
$$\sum_{k=0}^n(k+1)^2x^k=\sum_{k=1}^{n+1}k^2x^{k-1}=\left(\sum_{k=1}^{n+1}kx^k\right)'=\left(\sum_{k=0}^{n+1}kx^k\right)'\;.$$
If you can find a closed form for $\displaystyle\sum_{k=0}^{n+1}kx^k$, you can differentiate it to get one for $\displaystyle\sum_{k=0}^n(k+1)^2x^k$. And
$$\sum_{k=0}^{n+1}kx^k=\sum_{k=1}^{n+1}kx^k=x\sum_{k=1}^{n+1}kx^{k-1}=x\left(\sum_{k=1}^{n+1}x^k\right)'=x\left(\sum_{k=0}^{n+1}x^k\right)'\;,$$
for which you can easily find a closed form.
Answer: Hint: Consider the function
$$
u_m(x)=\sum_{k=0}^mx^k=\frac{1-x^{m+1}}{1-x},
$$
then
$$
u'_m(x)=\sum_{k=0}^mkx^{k-1},\quad
u''_m(x)=\sum_{k=0}^mk(k-1)x^{k-2},
$$
hence
$$
\sum_{k=0}^mk(k+2)=u''_m(1)+3u'_m(1).
$$
Can you compute $u'_m(1)$ and $u''_m(1)$?
Answer: Let the desired sum be given by
\begin{align}
S_{m} = \sum_{k=0}^{m} k(k+2).
\end{align}
Using the generating function method it is seen that the expression to calculate is
\begin{align}
\sum_{m=0}^{\infty} S_{m} \, t^{m}.
\end{align}
The calculation of this series is as follows.
\begin{align}
\sum_{m=0}^{\infty} S_{m} \, t^{m} &= \sum_{m=0}^{\infty} \sum_{k=0}^{m} k(k+2) t^{m} \nonumber\\
&= \sum_{m=0}^{\infty} \sum_{k=0}^{\infty} k(k+2) t^{m+k} \nonumber\\
&= \sum_{m=0}^{\infty} t^{m} \cdot \sum_{k=0}^{\infty} k(k+2) t^{k}
= \frac{1}{t(1-t)} \sum_{k=0}^{\infty} k(k+2) t^{k+1} \nonumber\\
&= \frac{1}{t(1-t)} \partial_{t} \, \sum_{k=0}^{\infty} k \, t^{k+2}
= \frac{1}{t(1-t)} \partial_{t} \left[ t^{3} \sum_{k=0}^{\infty} k t^{k-1} \right] \\
&= \frac{1}{t(1-t)} \partial_{t} \left[ t^{3} \partial_{t} \sum_{k=0}^{\infty}
t^{k} \right]
= \frac{1}{t(1-t)} \partial_{t} \left[ t^{3} \partial_{t} \left( \frac{1}{1-t} \right) \right] \\
&= \frac{1}{t(1-t)} \left[ \frac{2 t^{3}}{(1-t)^{3}} + \frac{3 t^{2}}{(1-t)^{2}} \right] =  \frac{2t^{2}}{(1-t)^{4}} + \frac{3 t}{(1-t)^{3}}. \\
\end{align}
Since $t = 1-(1-t)$ and $t^{2} =1-2(1-t) + (1-t)^{2}$ then the last result becomes
\begin{align}
\sum_{m=0}^{\infty} S_{m} t^{m} = \frac{2}{(1-t)^{4}} - \frac{1}{(1-t)^{3}} - \frac{1}{(1-t)^{2}}.
\end{align}
Now using the standard series
\begin{align}
\frac{1}{(1-t)^{2}} &= \sum_{m=0}^{\infty} (m+1) t^{m} \\
\frac{1}{(1-t)^{3}} &= \frac{1}{2} \sum_{m=0}^{\infty} (m+1)(m+2) t^{m} \\
\frac{1}{(1-t)^{4}} &= \frac{1}{6} \sum_{m=0}^{\infty} (m+1)(m+2)(m+3) t^{m}
\end{align}
then
\begin{align}
\sum_{m=0}^{\infty} S_{m} t^{m} &= \sum_{m=0}^{\infty} (m+1) \left[ \frac{1}{6}
(m+2)(m+3) - \frac{1}{2} (m+2) - 1 \right] t^{m} \\
&= \sum_{m=0}^{\infty} \left[ \frac{m(m+1)(2m+7)}{6} \right] \, t^{m}
\end{align}
and upon equating the coefficients of both sides it is seen that
\begin{align}
S_{m} = \sum_{k=0}^{m} k(k+2) = \frac{m(m+1)(2m+7)}{6} = \frac{1}{6} (2m^{3}+ 9m^{2} +7m).
\end{align}
This result may be verified by combining the two series,
\begin{align}
\sum_{k=0}^{n} k &= \frac{1}{2}(n^{2} +n) \\
\sum_{k=0}^{n} k^{2} &= \frac{1}{6}(2n^{3}+3n^{2}+n),
\end{align}
in the desired way. This provides
\begin{align}
\sum_{k=0}^{n} k(k+2) = \frac{1}{6} ( 2n^{3}+9n^{2}+7n ).
\end{align}
This example shows that the generating function method yields the desired result.


Churn prediction on a highly passive and imbalance dataset

Question: I'm trying to create a model to predict churn in the insurance industry. The objective will be to ' predict the probability of each member that will churn next month' i created a one row per member per month dataset where every member has one row for every month he has been active, the demographical information during that month, the household info, the claims made that month, the premiums paid and the calls made to the customer contact center. Below is the sample of what the dataset might look like
Id  Year    Month   product.x product.y claim prem calls
x   2017     8        1           0      250  180   1
x   2017     9        1           0      270  180   0
x   2017     10       1           0      0    180   0
x   2017     11       1           0      250  180   0
Now to the question: I'm trying to predict who is going to churn next month. the test dataset is the active members at the end of this month. the training dataset is the rest of the data, which also has the same members + few members that churned. Since the members in the test dataset are also present in train dataset without any variation across months( in the insurance industry, there is no major change in the activity of individual across months. they pay the same premium as last month, most buy regular drugs-hence regular claims and the demographics change rarely), the model always results that all members will be active.
How do I go about solving this issue? Am I making a mistake in the split of dataset?
Any thoughts will be highly appreciated
update for mkl:
you're right. the data is far from perfect. but we are getting there by incorporating more variables. Currently, I tried the following:
•   Performed k fold cross-validation on the entire dataset with tree ensemble learner and random forest (predicts all customers to be active. Zero kappa score)
•    I made a split on the one row per member per month dataset in such a way that I have a designated test dataset consisting of all the members that are active at the beginning of the month. The remaining is the training dataset. So, the training dataset contains the termed members and each member has multiple rows for every month till they terminated. Now the training dataset is quite small (the terminated members in a year are very few compared to the active members in the training dataset). Did oversampling of train data and used GBM. Still no results
Comment: Based on the comments that have emerged, I think that the time-scale of analysis might be potentially inappropriate. I fully appreciate what you say about potentially low information in your sample but that might mean you need to reassess the question you are asking. Something like "zero kappa" is so bad that it is almost unusual and hints to the irrelevancy of a train/test dataset rather than difficulty of prediction.
Answer: Don't predict yes/no. Instead, predict a probability that someone will churn. Then base any actions (e.g., calling them, offering a discount, whatever) on that probability and the costs of correct/wrong actions.
This earlier thread may be helpful.
Comment: well I can aim at predicting probability. when the ML algorithm tends to encounter the same row in the test dataset as in the training dataset, it ends up predicting that the customer would stay because there are 24 instances of the same customer record in the train dataset that states he is active
Comment: Are you sure that is an issue?  If you have the customer represented 20 times for different periods (where they churned in the final period), and the model says there is a 1/20th probability that they will leave, then the model was as right as it can be.
Answer: The questions is whether the data you collected can explain churn at all. The model can learn some weights / thresholds but it will not extract knowledge / rules that are outside your data.
E.g. if the most influential factor is (change of) income and you don't have it in your data, your predictions will be far from perfect.
Assuming positive answer - i.e. that observing your features can give you a reasonable answer about probability of the churn - how do you predict the churn? What is your model / approach?
Do you use some aggregates over the features and their combinations, like 'sum of claims > sum of premiums over last 6 months', 'number of calls is increasing in every month through last 3 months'?
Comment: please see updated que for answer. ive added some aggregates over features such as call increase, percentage of claims paid as opposed to overall claimed amt
Comment: Any progress? Sorry for silence, holiday break :)

With your update it's a bit clearer what is the problem. So starting from prediction moment (after training a model that I will discuss in a sec), you will have some past data about all current and past customers (a number of months) and you want to predict the status of the current ones in next month. So the features to be used needs to cover a number of past months (or somehow all of them, for each customer varying number). There is a number of ways to handle varying number of features: fixing 'look behind window', aggregates, RNNs. [tbc]
Comment: Now when talking about training, obviously we need to use the same features. So for a given customer one data point will be e.g. 10 month worth of the oldest data plus status in 11th month. Then next data point will be 11 month worth of data plus status in 12th (or months 2-11 if you decide for fixed look behind window). You can stop it anywhere you choose and use rest of data for testing, again shifting window appropriatel - this way creating a split train/test.
Answer: Why don't you assign observations to Train and Test based on ID?
create a column that is ID mod 10, then use if/then logic to assign.  Then you won't have the same policyholder in both data sets.
I would also add I would define a fold column based on ID.  You've likely got the same person in all of your folds.
Is this insurance bought through an employer or is it direct?  Are there variations by time of year?
Comment: thank you! I did a subject wise split already. poor prediction! features dont seem to be strong enough


Zero divisor in R[x] for a commutative ring R

Question: Given a commutative ring $R$ and a polynomial $f(x)=a_0+\cdots+a_nx^n, \ a_n\neq 0_R$ which is a zero divisor in $R[x]$, I am supposed to show that $a_n$ is a zero divisor in $R$. Now there exists a polynomial $g(x)=b_0+\cdots+b_mx^m, \ b_m\neq 0_R$ such that $f(x)g(x)=0_R$ or $g(x)f(x)=0_R$. In fact, since $R$ is commutative, so is $R[x]$, and so these two are equivalent. Suppose however, they were not. Then in the first case, by considering the coefficient of $x^{n+m}$, I would conclude that $a_nb_m=0_R$. In the second case, I would similarly get $b_ma_n=0_R$. Either way, $b_m$ is a zero divisor of $a_n$. So why do I need commutativity?
Thanks!
Answer: You really don't. It's just that in a non-commutative ring one has to make a distinction between a left zero-divisor and a right zero-divisor. Here you have if $f(x)$ is a right (resp. left) zero-divisor, $a_n$ is also a right (resp. left) zero divisor. The correct statement becomes a little more complicated, that's all.
Comment: Alright, thanks!
Answer: To be really annoying, one could say that the statement $R$ commutative $\Rightarrow$ $R[t]$ commutative (or even the equivalence))  is not always true. In fact, considering the theory of Ore extensions of $R$ it follows that
$$tr \neq rt,~~\forall r\in R$$
in general. The "usual" polynomial ring $R[t]$ in which the coefficients and the indeterminate $t$ commute is just a particular case of the Ore extension construction (the one with $\sigma=1$ and $d=0$).
On the other hand, in a commutative ring a zero divisor is a left divisor and a right divisor, so the distinction does not play any role.
Answer: I think it's more an issue of wanting $R$ to be commutative so that you can talk about polynomials over $R$.
True, if $R$ is non-commutative, one could still define an analog to the usual polynomial ring as you were doing (by insisting $x$ commute with all coefficients), but that seems like a weird thing to do, and I don't think I've ever seen it done in my (admittedly little) experience with noncommutative algebra.
Your argument would not work as is for the noncommutative polynomial ring $R\langle x\rangle$, simply because most polynomials do not have the form you assume. For example, in $\mathbb{C}\langle x \rangle$, $xix \neq ix^2$.
Comment: I see. In the book I am using, it is required that $x$ commute with all elements of the underlying ring.


For all even integers $n$, $(-1)^n = 1$

Question: Suppose that $n$ is an even integer.
Then $n = 2r$ for some $r \in\mathbb{Z}$.
Hence $(−1)^n =(−1)^{2r} = 1$ because $2r$ is even.
Therefore $(−1)^n = 1$ for any even integer $n$
Verification?
Comment: Basically, you need to write $(-1)^n=(-1)^{2r}=((-1)^2)^r=(+1)^r=1$.
Comment: This is completely circular.  Why does $(-1)^{2r} = 1$?  You say it is because $2r$ is even.  That's what you are trying to prove!  You can't use what you are trying to prove to prove it!
Comment: @barakmanos $\sqrt{a}=a^{\frac{1}{2}}$, while $a^{-2}=\frac{1}{a^2}$
Comment: @edm: Ooops, long hours :)
Comment: Prove all numbers are  less than 523.  Let $n$ be a number.  Let $n =r+1$.  $r+1 < 253$ because it is a number.  Therefore all $n < 253$.  What is wrong with my proof?  My proof is **exactly** the same reasoning as your proof.
Answer: You didn't prove anything yet. I am sorry, but your current "solution" is worth $0$ points.
Why?

You say

$(-1)^{2r} = 1$ because $2r$ is even.

But how do you know that if $2r$ is even, $(-1)^{2r} = 1$?
You cannot just assume the conclusion!

That's not how mathematical proofs work. Remember that what you want to prove is the statement:

If $n$ is even, then $(-1)^n=1$.

In your current "proof", you basically say,

I already know that  if $2r$ is even, then $(-1)^n=1$.

But you don't know that because that is exactly what you want to prove.

Hint:
For the actual solution, remember that ${\left(a^b\right)}^c = a^{bc}$.
Answer: You know
$$(-1)^2=1$$, therefore $$(-1)^{2r} = ((-1)^{2})^r = 1^{r} = 1 $$
for any r.
Answer: $$ (-1)^2 = (-1) \times (-1) = 1 $$
hence
$$\forall r \in \mathbb{R}, \qquad (-1)^{2r} = \left((-1)^2\right)^r = 1^r = 1.$$

For all even integers $n$, $(-1)^n = 1$


Django inline model formset with 2 models

Question: First of all, please forgive for my newbie questions. I did copy most of the code, and try to understand from Django documents.
Code as below:
models.py
class Order(models.Model):
  ORDER_CHOICES = (
      ('import', 'IMPORT'),
      ('export', 'EXPORT')
  )

  storage = models.ForeignKey(Storage, on_delete=models.PROTECT)
  order_type = models.CharField(max_length=6, choices=ORDER_CHOICES)
  created_at = models.DateTimeField(auto_now_add=True)
  updated_at = models.DateTimeField(auto_now_add=True)

class Item(models.Model):
  def random_barcode():
      return str(random.randint(10000000, 99999999))

  type = models.ForeignKey(Type, on_delete=models.CASCADE)
  order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True)
  brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
  item_name = models.CharField(max_length=50, help_text='Name of goods, max 50 characters')
  barcode = models.CharField(max_length=8, default=random_barcode, unique=True)
  production_date = models.DateField()
  expired_date = models.DateField()

  def __str__(self):
      return self.item_type

forms.py
class ItemForm(ModelForm):
  class Meta:
      model = Item
      exclude = ['order',]
      fields = ['type', 'brand', 'item_name', 'production_date', 'expired_date']
ItemFormSet = inlineformset_factory(Order, Item, form=ItemForm, extra=1)

views.py
class CreatePO(CreateView):
  model = Order
  context_object_name = 'orders'
  template_name = 'storages/create_po.html'
  fields = ['order_type', 'storage',]
  *#dun't know how to write below code....*

1st question: how to use inline formset to write the CreatePO view?
2nd question: I need my create PO template as below picture, how to add a "Quantity" field?
This kind of template need Javascript, right? Any alternative solution? I have no knowledge with javascript.
Answer: First of all, move the def random_barcode(): before def __str__(self): it looks so ugly formated code.
Then let's have a look in your pic, if you haven't proper experience with Javascript you can use Admin Views from Django, it's much more simple and supported by Django 2.1. Read more if you would like to give permission to everyone in a admin-views page https://docs.djangoproject.com/el/2.1/releases/2.1/#model-view-permission
So quantity will be just added inside Item class
quantity = models.PositiveSmallIntegerField(default=1)

Also for your form, in my opinion, you need modelform_factory, so I suggest to read this one https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#modelform-factory-function


Are the graphs I sketched of the derivative of a function and the function correct?

Question:

I know that when the function is increasing, the derivative is positive. What I am confused about for the first one is that when I am sketching the derivative, I don't know what direction it goes (even though i know it is positive). What I am thinking is that where the graph has a min or max, then the derivative must have an x-intercept there. That is how I came up with my graph for the first two questions.
For the third question, I tried doing the opposite. So the derivative is positive thus the function is increasing and vice versa. Where the derivative has an x-intercept, the function has a min or max but the question is still a little confusing to me.
Answer: I think it would be helpful for you to discretize your graph along X axis and calculate the derivative using some finite differences formula.
Comment: it has to be a sketch. i do not have time on a test to do finite differences formula
Comment: So in this case, focus on the extreme values of the function f, the derivative there must be zero. Then consider the curvature as well, the more the function is convex, the more the derivative increases rapidly.
Comment: i mentioned in my question that i did that. i want to know if my answers are correct and if not then how can i fix it
Comment: Could you please post your answer using a paper with markers so as we can see the correspondences?
Comment: okay i will do that
Comment: i just updated it, sorry it took so long
Comment: i don't have a paper with markers but i drew dashed lines for min/max so you can see better what i am doing
Comment: i don't know how to flip the image so that it is right side up
Comment: i think i am correct
Comment: looking at the position of the zeros of the derivative, yoi are correct. You can have more accuracy by setting the derivative to the maximum where the function changes convexity.


Calculating the probability of at least one of $X_i \subset X$ using Inclusion-Exclusion

Question:
The Problem statement and the solution is mentioned in the image provided. Please explain me how the set is constructed and how do we get the probability in the form of the provided function $f(x)$ using Inclusion-Exclusion.
Answer: Supposing  that  we  have  $q$  of   these  sets  $X_j$  we  start  by
constructing the poset  for use with PIE. The nodes  $Q$ of this poset
are  subsets of  $[q]$  and  represent subsets  $T  \subseteq S$  that
contain the  elements of $X_j$  with $j\in  Q$ plus possibly  more, so
they could contain the elements of an $X_k$ with $k\notin Q.$ A subset
$T$ is represented by the term $z^{|T|}$  so that we will not be using
the cardinality  of the set of  subsets $T$ of $S$  represented at $Q$
but rather  a refinement,  namely an  ordinary generating  function of
these sets by the number of elements.
We now ask about the generating function  in $z$ of the subsets of $S$
that do not contain any of the $X_j$ as a subset. The weight of a node
$Q$ of the poset is $(-1)^{|Q|}.$ There  are two cases for $T.$ If $T$
does not contain any of the $X_j$ as a subset it will be included only
at the  base node $Q=\emptyset$  getting total weight  $z^{|T|} \times
(-1)^{|\emptyset|}  = z^{|T|}.$  On  the other  hand  if $T$  contains
exactly the  elements of the $X_j$  with $j\in P$ (plus  possibly some
others that  do not  contribute to  form a  different $X_j$)  for some
$P\subseteq  [q]$ where  $P\ne\emptyset$ then  it is  included in  all
nodes $Q$ that represent subsets of $P$ for a total weight of
$$z^{|T|} \sum_{Q\subseteq P} (-1)^{|Q|}
= z^{|T|} \sum_{k=0}^{|P|} {|P|\choose k} (-1)^k = 0.$$
We  see that  indeed the  only non-zero  contribution originates  with
those $T$ not containing any $X_j.$  We may now apply PIE knowing that
the generating function at $Q$ is
$$z^{|\bigcup_{j\in Q} X_j|} (1+z)^{|S|-|\bigcup_{j\in Q} X_j|}
= (1+z)^{|S|} \left(\frac{z}{1+z}\right)^{|\bigcup_{j\in Q} X_j|}.$$
We thus  have for the  generating function  $Y(z)$ of the  subsets not
containing any of the $X_j$ by PIE the closed form
$$Y(z) = (1+z)^{|S|}
\sum_{Q\subseteq [q]} (-1)^{|Q|}
\left(\frac{z}{1+z}\right)^{|\bigcup_{j\in Q} X_j|}.$$
Now  a  set $T$  with  $|T|$  elements  represented by  $z^{|T|}$  has
probability $(1-p)^{|S|-|T|} p^{|T|}$ hence the desired probability
is given by
$$(1-p)^{|S|} Y(p/(1-p)) \\ =
(1-p)^{|S|} (1+p/(1-p))^{|S|}
\sum_{Q\subseteq [q]} (-1)^{|Q|}
\left(\frac{p/(1-p)}{1+p/(1-p)}\right)^{|\bigcup_{j\in Q} X_j|}
\\ = \sum_{Q\subseteq [q]} (-1)^{|Q|} p^{|\bigcup_{j\in Q} X_j|}.$$
We now know  the probability of none  of the $X_j$ being  a subset and
hence the probability of at least one being a subset is
$$1 - \sum_{Q\subseteq [q]} (-1)^{|Q|} p^{|\bigcup_{j\in Q} X_j|}
= - \sum_{Q\subseteq [q], Q\ne\emptyset}
(-1)^{|Q|} p^{|\bigcup_{j\in Q} X_j|}.$$
This is
$$\bbox[5px,border:2px solid #00A000]{
\sum_{Q\subseteq [q], Q\ne\emptyset}
(-1)^{|Q|+1} p^{|\bigcup_{j\in Q} X_j|}.}$$
precisely as in the problem statement and we may conclude the argument
observing that increasing $p$ will  indeed increase the probability of
an $X_j$ appearing in $X.$
 Remark. We can check the correctness of the formula for $Y(z)$
by comparing  the result of  enumeration to  the closed form.  This is
shown below, which also includes a plot.

with(combinat);

YX :=
proc(XL)
local XJ, S, q, Q, Y;
option remember;

    S := `union`(op(XL));
    q := nops(XL);

    Y := 0;

    for Q in powerset(q) do
        XJ := `union`(seq(XL[p], p in Q));

        Y := Y + (-1)^nops(Q)
        * (z/(1+z))^nops(XJ);
    od;

    expand(simplify(Y*(1+z)^nops(S)));
end;

YENUM :=
proc(XL)
local S, Y, T, idx;
option remember;

    S := `union`(op(XL));
    Y := 0;

    for T in powerset(S) do
        for idx to nops(XL) do
            if XL[idx] subset T then
                break;
            fi;
        od;

        if idx = nops(XL) + 1 then
            Y := Y + z^nops(T);
        fi;
    od;

    Y;
end;

YPLOT :=
proc(XL)
local S, f;
    S := `union`(op(XL));

    f := expand(simplify(subs(z=p/(1-p), YX(XL))
                         *(1-p)^nops(S)));
    plot(1-f, p=0..1);
end;

Some examples that were tested are:

> YENUM([{1,2,3}, {1,2,3}, {2,5}]);
                           3      2
                          z  + 5 z  + 4 z + 1

> YX([{1,2,3}, {1,2,3}, {2,5}]);
                           3      2
                          z  + 5 z  + 4 z + 1

> YENUM([{1,2,3}, {1,2,3}, {4,5,6}, {2,5}]);
                       4       3       2
                    5 z  + 14 z  + 14 z  + 6 z + 1

> YX([{1,2,3}, {1,2,3}, {4,5,6}, {2,5}]);
                       4       3       2
                    5 z  + 14 z  + 14 z  + 6 z + 1

> YENUM([{1,2,3}, {4,5,6}, {7,8}]);
                    5       4       3       2
                18 z  + 45 z  + 48 z  + 27 z  + 8 z + 1

> YX([{1,2,3}, {4,5,6}, {7,8}]);
                    5       4       3       2
                18 z  + 45 z  + 48 z  + 27 z  + 8 z + 1

Here is a sample plot.

> YPLOT([{1,2,3}, {1,2,3}, {4,5,6}, {2,5}]);

1 +                                                            HHHHHH
  +                                                        HHHHH
  +                                                      HHH
  +                                                   HHH
0.8                                                 HHH
  +                                               HHH
  +                                             HH
  +                                           HH
0.6                                         HH
  +                                      HHH
  +                                    HHH
  +                                  HHH
0.4                                HHH
  +                              HHH
  +                            HHH
  +                         HHH
0.2                      HHHH
  +                   HHHH
  +               HHHHH
  +         HHHHHH
  **********+--+--+-+--+--+-+--+--+-+--+--+-+--+--+-+--+--+-+--+--+-+
0             0.2          0.4           0.6          0.8           1


IIS application creation by using Microsoft.Web.Administration library creates two application instead of one

Question: I'm trying to automate IIS application creation and for this I'm using Microsoft.Web.Administration library. Here is part of code I'm using:
IISHelper.cs
public static void CreateApplicationPool(string applicationPoolName)
{
    using (ServerManager serverManager = new ServerManager())
    {
        if (serverManager.ApplicationPools[applicationPoolName] != null)
            return;
        ApplicationPool newPool = serverManager.ApplicationPools.Add(applicationPoolName);
        newPool.ManagedRuntimeVersion = "v4.0";
        serverManager.CommitChanges();
    }
}

public static void CreateSite(string siteName, string path)
{
    using (ServerManager serverManager = new ServerManager())
    {
        var sites = serverManager.Sites;
        if (sites[siteName] == null)
        {
            sites.Add(siteName, "http", "*:80:", path);
            serverManager.CommitChanges();
        }
    }
}

public static void CreateApplication(string siteName, string applicationName, string path)
{
    using (ServerManager serverManager = new ServerManager())
    {
        var site = GetSite(serverManager, siteName);
        var applications = site.Applications;
        if (applications["/" + applicationName] == null)
        {
            applications.Add("/" + applicationName, path);
            serverManager.CommitChanges();
        }
    }
}

public static void CreateVirtualDirectory(string siteName, string applicationName, string virtualDirectoryName, string path)
{
    using (ServerManager serverManager = new ServerManager())
    {
        var application = GetApplication(serverManager, siteName, applicationName);
        application.VirtualDirectories.Add("/" + virtualDirectoryName, path);
        serverManager.CommitChanges();
    }
}

public static void SetApplicationApplicationPool(string siteName, string applicationPoolName)
{
    using (ServerManager serverManager = new ServerManager())
    {
        var site = GetSite(serverManager, siteName);
        if (site != null)
        {
            foreach (Application app in site.Applications)
            {
                app.ApplicationPoolName = applicationPoolName;
            }
        }
        serverManager.CommitChanges();
    }
}

And here is main code which calls methods from above mentioned IISHelper class
string siteName = "TestSite";
string applicationName = "TestApp";
string virtualDirectoryName = "TestVirtualDirectory";
string applicationPoolName = "TestAppPool";
string physicalPath = @"C:\inetpub\mynewsite";

IISHelper.CreateApplicationPool(applicationPoolName);
IISHelper.CreateSite(siteName, physicalPath);
IISHelper.CreateApplication(siteName, applicationName, physicalPath);
IISHelper.CreateVirtualDirectory(siteName, applicationName, virtualDirectoryName, physicalPath);
IISHelper.SetApplicationApplicationPool(siteName, applicationPoolName);

After execution of this code I'm getting successfully created application with site and appropriate application pool under the IIS, but when I'm selecting "View Application" in the menu of newly created application pool I'm seeing there two application, but I'm sure there must be only one application. I'm working on this to avoid two application creation but can't find a way. Here is a picture illustrating that:

So here is my question: Why after the above mentioned code execution two applications are created and how to modify the code to avoid that issue?
Comment: Where are GetSite & GetApplication referenced?
Comment: public static Site GetSite(ServerManager serverManager, string siteName)
        {
            return serverManager.Sites.FirstOrDefault(x => x.Name == siteName);
        }

        private static Application GetApplication(
            ServerManager serverManager,
            string siteName,
            string applicationName)
        {
            return serverManager.Sites
                .FirstOrDefault(x => x.Name == siteName)?.Applications
                .FirstOrDefault(x => x.Path == "/" + applicationName);
        }
Answer: Every site must include a "Root Application" which is what you are seeing as the second app. Basically when you request your site above as 'http://example.com/' (or whatever host name you set in the bindings) you will be requesting from that root app, in addition you are creating /TestApp which will be requested when calling 'http://example.com/TestApp'. When you create the Site and you provide the physical path it internally creates a root app "/" for it.
To see this you can open %windir%\system32\inetsrv\applicationHost.config.
So technically what you are seeing is correct, but you might not actually want a new app? and only need the root app? Do you really need /TestApp to be in the URL?


Como manter sessão PHP durante upload longo

Question: Olá, tenho um sistema básico de autenticação usando session pra um sistema de file-upload
Porém, quando algum usuário com internet lenta coloca muitos arquivos na fila de upload (10 ou mais arquivos), sendo que cada arquivo demoraria 1 hora pra ser upado, ele acaba sendo desconectado depois de 1 ou mais horas
Eu já tentei resolver esse problema usando as diretivas
session.gc_maxlifetime
session.cookie_lifetime
E também a função session_set_cookie_params.
Porém, mesmo usando elas, o usuário continua sendo deslogado após 1 hora ou um pouco mais e nunca conseguindo completar o restante dos seus uploads
(Já que a sessão é destruída por inatividade na página, apesar dele continuar upando o arquivo)
Answer: Você pode usar o session_cache_expire() ele aumenta ou diminui o tempo de expiração de uma sessão. Recebe como parâmetro o tempo em minutos para expiração da sessão. Precisamos declarar essa função antes de session_start(). Veja um exemplo dessa função:
<code><?php
//INICIO A SESSÃO COM UM TEMPO DE EXPIRAÇÃO DE 10 MINUTOS
session_cache_expire(10);
session_start();
?>
</code>
Você também pode usar como alternativa:
Criar um Cookie onde você tem que usar os Cookie para manter, caso as sessions estejam apagadas, então você busca nos cookies e resete as sessions.


Editing contents of custom block referenced in paragraph type, doesn't reflect changes in node where displayed

Question: So, I have a Custom Block type, let's call it Sidebar Links Block. In an Article, we have a Sidebar paragraph type that allows quite a few different entities, one of which is the Article Sidebar Links paragraph type.
The Article Sidebar Links ¶ type (which is one of the fields of our Article type) contains a single entity reference to a Custom Block type, the aforementioned Sidebar Links Block.
If I change, say, the Title of the Sidebar Links Block, that change is not reflected in the paragraph type's output. In other words, when viewing an Article where we changed the contents of one of the referenced Custom Block types, it still shows the old contents, before the change.
Even clearing the Drupal caches in the usual way, does nothing. What I have to do, instead, is:

Edit the Article
Move any ¶ type up or down, then move it back (this triggers the form's JS that detects changes, allowing you to re-save with essentially no real changes)
Re-save the Article

This finally causes the Title to update in the Article Sidebar Links ¶ type where the Sidebar Links Block is referenced and displayed.
Is there any way around this? Currently, whenever we update a Custom Block, we have to apply this manual fix to every single Article where it's referenced. I have a hunch that it has something to do with cache tags, but I don't know enough to be able to investigate. Does anybody have any ideas as to how this can be fixed?
Comment: Yes, it should, but block content is not a normal entity, because it has no template of its own and this breaks the bubbling of cache tags. Try the suggested module to reference the block content because it has a solution for the problem. Or you need to implement similar code in a paragraph preprocess hook to merge the cache tags, see https://drupal.stackexchange.com/questions/225548/block-cache-not-clearing-on-save
Comment: Obviously the block content cache tag is not merged into the paragraph. So it isn't enough to resave the node, you need that trick to resave the paragraph, too. I don't know how you referenced the block content, but try the Block Field module and this patch https://www.drupal.org/project/block_field/issues/2999660
Comment: The custom block is referenced via paragraph type, which contains an entity reference to custom blocks. In other words, Article has a field "Sidebar Contents", which can point to any number of paragraph types, including "Article Sidebar Links". When you add that para. type, you can select which Custom Block it will reference (via autocomplete). These blocks can be shared across multiple Articles, so changing the contents of the custom block should update all Articles containing the block (through paragraph type).
Answer: So the way that I ended up fixing this, was to use Twig Tweak to output the content block directly, like so:
<code>{{ drupal_entity('block_content', content_block_id) }}
</code>
This ends up bypassing Drupal cache. Barring a better fix, this is the one I'm going with.


What does "variability" mean in statistics?

Question: I'm using an introductory statistics textbook and it mentioned this:
"Describing the data with reference to the spread is called "variability". The variability in data depends upon the method by which the outcomes are obtained; for example, by measuring or by random sampling"
Comment: Thank you so much!
Comment: Welcome to Mathematics Stack Exchange.  Roughly speaking, variability tells how much the data points are spread from the mean
Answer: Welcome to Mathematics Stack Exchange.
Roughly speaking, in statistics, variability tells how much the data points are spread from the mean.