Gamma distribution what is scale and rate

Question: I have question regarding the gamma distribution when using
alpha <- 3
beta <- 3
x <- rgamma(n = 100, shape = alpha, scale = 1/beta)

fitdistr(x,"gamma"

I get shape to 3.9 and rate to  3.4.
Are the rate=beta or is the rate=theta? What is the difference between scale and rate?
Note: I did not understood what they said on Wiki
Comment: These are defined in the [documentation](https://stat.ethz.ch/R-manual/R-devel/library/stats/html/GammaDist.html)
Answer: If you consider the notations on wiki, there $\theta$ is the scale parameter.
So, $1/\theta$ is the rate. That means $1/\theta$ corresponds to $\beta$.
Comment: How can I then get the Beta estimate out of the rate estimate?
Comment: In your output you have rate. That means rate = $\beta$
Answer: It may be worthwhile having an extended discussion on what a scale parameter is, what a rate parameter is with respect to an exponential random variable, and how the exponential relates to the Gamma.
The TL;DR is this:

The gamma can be viewed as the sum of iid $n$ exponential random variables.  Exponential random variables have a rate parameter, so it makes sense for the Gamma to inherit a rate parameterization.  The rate parameter also happens to be related to a scale parameter, so it makes sense for the Gamma to have a scale parameterization.

Let's break this down a little more.
What is a Scale Parameter?
According to wiki, a scale parameter is a parameter $s$ for which the density of a random variable satisfies
$$ f_s(x) = f(x/s)/s$$
Let's take a look at the Gamma distribution,
$$ f(x) = \dfrac{\beta^\alpha}{\Gamma (\alpha)} x^{\alpha-1} e^{-\beta x}$$
and try to identify the scale parameter.  After some thinking, you might say that the scale parameter is $1/\beta$.  Do verify this, we need to show that the first equation in my answer is satisfied.  Let's start by setting our proposed scale parameter to 1 (so $\beta=1$) and then manipulate $f(x/s)/s$ to see what we get.
$$ f(x/s)/s = \dfrac{1}{s} \times \dfrac{1}{\Gamma(\alpha)}\left(\dfrac{x}{s}\right)^{\alpha-1} e^{-x/s} $$
Now, we proposed $s=1/\beta$.  After some algebra, you find that this expression is equivalent to
$$ = \beta \times \dfrac{\beta^{\alpha -1}}{\Gamma(\alpha)} x^{\alpha-1} e^{-\beta x} $$
Which is $f_s(x)$.  So we've proved that $1/\beta$ satisfies the requirements for being a scale parameter.
What is a Rate Parameter for an Exponential Random Variable?
The exponential distribution is often used in modelling failure times for various things.  If the failure time $T \sim \operatorname{Exponential}(\beta)$ then we should expect $\beta$ failures per unit time.  This makes sense too when you think about the expected value for an exponential random variable (if I get $\beta$ failures per unit time, then on average I should expect to wait $1/ \beta$ units of time per failure).
How are The Gamma and Exponential Related
Now, I'm not a historian of statistics, but I anticipate that the shape and rate parameterizations for the Gamma could be viewed as coming from the following relationship:

The sum of $n$ iid exponential random variables with rate parameter $\beta$ has gamma distribution with shape parameter $n$ and rate parameter $\beta$.

Various proofs of this are found on this site and on Wikipedia, but you can easily simulate this in R or something to verify it empirically
n <- 12
beta <- 1.2

rvs <- replicate(1000, {

  sum(rexp(n, beta))
})

hist(rvs, freq = F)
curve(dgamma(x, shape = n, rate = beta),, col='red', add=T)

Answer: The "scale" and "rate" are essentially multipliers/divisors of a unit-scale gamma
The notation we use for the parameters of the distribution is somewhat arbitrary, though there are common conventions.  Conventionally, we use $\theta$ to denote the scale parameter of the gamma distribution and we use $\beta$ to denote the rate parameter of the gamma distribution.  These are related by $\beta = 1/\theta$.
A useful way to remember the meaning of the parameters is that the "scale" is essentially just a multiplier of the random variable and the "rate" is the corresponding divisor.  If $X \sim \text{Gamma}(\alpha, 1)$ then we have:
$$\begin{align}
\theta X &\sim \text{Gamma}(\text{Shape} = \alpha, \text{Scale} = \theta), \\[6pt]
\frac{X}{\beta} &\sim \text{Gamma}(\text{Shape} = \alpha, \text{Rate} = \beta). \\[6pt]
\end{align}$$
From these results we can see that one way to think of a gamma random variable as a scaled version of an underlying unit-scale gamma random variable.


How to add facial recognition based login in ubuntu/linux?

Question: I have written a code (in python) to detect my face. Now I want to add this feature for login in my Ubuntu system. I searched over internet but cannot find suitable answers.
I want to display an option/icon to select facial recognition and on clicking that, my facial recognition code starts running in background. How I can achieve it? Please explain exactly where I need to make changes in ubuntu system for enabling and using such option?
Comment: X is a little bit complex, we have around 5 programs interacting while we get a login. One of them is the tool which puts the "login/password" box. It is started by the "x display manager", their name ends with "dm", light "xdm", "mdm" and so on. The display manager has a configuration, you need to switch in its config into your face recognization tool.
Comment: I think your thing is interesting, I think I could help more, but not in the SO framework. Come into the chat ( https://chat.stackoverflow.com )
Comment: @peterh are you available?
Answer: You will want to use Linux-PAM to allow you to Su/Sudo using facial recognition. I have done this with python + a bash script here: https://github.com/lambrou/susentry
I have taken part of my README and will explain it to you with the context of your question.
The first thing you will need to do is make a bash script that calls your python script.
#!/bin/bash

# You must change the value /path/to/susentry.py to the path of your
# python file.
export DISPLAY=:0.0
xhost +local:
python3 /path/to/susentry.py -l # run the python script for facial recognition
exit_status=$? # This grabs the exit status of the python script we just ran
if [ "${exit_status}" -ne 0 ]; # checks to see if exit status is anything other than 0
then
    echo "exit ${exit_status}"
    exit 1 # exit status 1 on python script fail (exit 1)
fi
echo "EXIT 0"
exit 0 # exit 0 if we get to this line

What this script does is sets the display to your display, as the PAM module will be calling the script from a different userspace we will need to tell it where your display is, and what xhost you are using. Then, it grabs the exit status of your python script (make sure on facial recognition fail it exits 1, pass it exits 0) and passes it to PAM to let it know whether or not the script passed or failed.
Find this line:
python3 /path/to/susentry.py -l
And change /path/to/susentry.py to the full path of your python script. Then, place this file in /usr/local/bin folder.
Next, we modify the PAM common-auth file:
gksudo gedit /etc/pam.d/common-auth

Find this line in your common-auth file:
auth [success=1 default=ignore]     pam_unix.so nullok_secure

This line calls the module that asks the user for a password. If the module returns success (password correct), it skips the next line (success=1 means skip one line). The goal is to skip the following line if authentication is successful:
auth    requisite           pam_deny.so

As this line denies the user access to privileges.
So, if you want to use su/sudo, but instead of entering your password you use facial comparison, put this above the line above:
auth [success=2 default=ignore]     pam_exec.so debug log=/path/to/pamlogs.txt /usr/local/bin/susentry

Make sure you change /path/to/pamlogs.txt to where you want the PAM output to be saved. (This ouput is error output and stdin output from your PAM, your bash script, and your python script)
Lets break this down.
auth [success=2 default=ignore]
Means "If this program returns success (exit 0), then skip the next 2 lines. (Password prompt line, authentication fail line)
pam_exec.so debug log=/path/to/pamlogs.txt
This part says "use pam_exec to execute the bash script, and send all the error logs/stdin logs to /path/to/pamlogs.txt
/usr/local/bin/susentry
This part is the location of the bash script. This is what PAM exec runs and waits for an exit code for.
If the facial recognition script fails it should fall back to asking for a password.
Please note that you need to be careful when editing /etc/pam.d/common-auth as you can break your sudo. You may want to open a new terminal with root privileges while you mess with this stuff so you can revert back the changes.
Comment: Yes, you need to use sys.exit(1) or 0 as this tells the bash script how the python script exited. The bash script exits the same way, and sends the exit code to PAM.
You do not need an if statement or loop, the PAM modules run in a loop - remember how when you enter your password, you get multiple attempts?
As long as you put the line
`auth [success=2 default=ignore]     pam_exec.so debug log=/path/to/pamlogs.txt /usr/local/bin/susentry` above the line that is already there, it will run exactly how you want it. (It will fall back to password auth if facial recognition fails)
Comment: so how does PAM and bash script is passing information with each other?   specifically, how does PAM know the location of bash script and also how bash script is passing exit status of python script to PAM?
Comment: @abhi I edited the answer to answer your questions. Namely by adding more comments to the bash script and breaking down the line we add to PAM. Let me know if you need me to explain anything else.
Comment: Thanks for the explanation. Just I need to know two more things. 1. Do I need to use `sys.exit(0)` and `sys.exit(1)` on success and failure from my python script? 2. On unsuccessful face detection, I want to use password-based authentication. So some kind of `if else` statement or `loop` is required which asks for a password from the user. How I can do it here?
Comment: After system bootup, in the login window, I have obtained the following error using above-mentioned shell script: **xhost:  unable to open display ":0.0"
: cannot connect to X server :0.0**. After the login using password, everything worked perfect (in the terminal, software store, etc.). How to remove this error after system boots up and first login screen is displayed?
Comment: Are you using susentry.py, or your own script? If you are using susentry.py, do you have verbose set to True or False?
If you are using your own, are you having any GUI windows pop up in your script?
Comment: I am using the same script file you have provided with the only change to the python file path. I have not made any change to the verbose setting. What should I do next?


Experimental Design for Equivalence Testing

Question: I'm working on setting up a study that will test how quickly users click on various icons appearing on a computer screen using three different prototype mouse types.  Subjects will visit on three three days and perform the test twice each visit (two recorded time measurements per visit).
I want to show there is no difference in time within subjects and between mouse devices via equivalence testing.
Let's say I have 135 subjects.  I could assign 45 subjects to a specific mouse device and only have them use that particular device each visit.  Or I could assign them a different mouse device each visit.
Which design would be better?  I believe it depends on the variability between mouse devices.  Also, how would I analyze the equivalence testing in one model that takes into account the user effect and mouse device effect?
Comment: These numbers are quite low for equivalence testing. I suggest you prepare in advance two sets of methods - one based on equivalence and one on significance (with indifference region), which should suffice.
Comment: @Spätzle Could you expand on significance with indifference region?  I updated the question to 135 subjects as I want the question to focus on study design and analysis, not sample size.
Comment: I would recommend using uniformly most powerful tests for equivalence, *a la* Wellek's textbook: definitely more powerful than TOST.
Comment: @Alexis do you have an online reference?
Comment: @Glen Wellek's is the only textbook I have seen, and it pulls not only from his experience, but from a widely distributed literature. I found it digitally accessible from my local public library, and from my university library, which also had a print copy if I recall correctly. However, you might also try Inter-Library Loan if your local library participates in that exchange (which, during COVID-19 realities, may or may not be happening for physical volumes).
Comment: Wellek, S. (2010). *Testing Statistical Hypotheses of Equivalence and Noninferiority* (Second Edition). Chapman and Hall/CRC Press.
Answer: "Usual" significance testing uses null hypothesis $H_0:|\mu_A-\mu_B|=0$. That is, we assume no effect exists. The "acceptance region" (AR, the region in
which we do not reject the null) size shrinks as sample size grows. This leads to a super sensitive test, which will reject the null for tiny differences in large sample size.
Using indifference region is a somewhat more "realistic" approach: we acknowledge the possibility that some effect with exist, but we decide to ignore it up to a point, say we ignore effects smaller than $\epsilon$. A relevant null hypothesis would be $H_0:|\mu_A-\mu_B|<\epsilon$. It does help us achieve a more stable approach (in terms of false rejection of the null), but a large enough sample size would eventually lead to rejecting the null. See Section 4.3 of Bickel & Doksum for more details. Do note that the ignorable effect size should be determined before you conduct the test itself - it should be based on results of previous experiments, known measuring error, relevant literature and so on.
Equivalence testing is "flipping" the direction of the hypotheses, i.e $H_0:|\mu_A-\mu_b|\ge\epsilon$. the result is an AR which grows with sample size (up to a bound). The so called "problem" is that it requires a large enough sample size in order to have a large enough AR. Note that for ET, "acceptance" means that we do reject the relevant null htpothesis.
For example, consider the following problem: we have $n$ measurements of $X_A\sim N(\mu_A,1),X_B\sim N(\mu_B,1)$ and we hypothesize the difference of means $\mu_A-\mu_B$. The null hypotheses are as follows:
$$H_0^{sig}:|\mu_A-\mu_B|=0,\qquad H_0^{indiff}:|\mu_A-\mu_B|<\epsilon,\qquad H_0^{equiv}:|\mu_A-\mu_B|>\epsilon$$
We take a vector of size 100, $X\sim N_{100}(0, I)$ and repeat it $2^k$ times. See how the AR size changes:

(This plot is taken from the background section of my MA thesis).
For your case, I believe that ET wouldn't be very helpful as the sample size isn't that large. Try using indifference region and see how it goes.


How to get the expression for this partial sum

Question: I was asked to calculate what the sum of the following series is $$\sum_{n=1}^\infty\frac{2}{4n^2-1}$$ I split up the fraction into $$\frac{1}{2n-1}-\frac{1}{2n+1}$$ From here I wasn't sure what to do so I checked the answers which said that from this we can see that the partial sum up to $m$ is given by $$\sum_{n=1}^{m}\frac{2}{4n^2-1}=1-\frac{1}{2m+1}\tag{1}$$ and that this converges to $1$ as $m\to\infty$. I don't understand how $\frac{1}{2m+1}\to0$ and how they came to the equation in $(1)$.
EDIT: The question on why $\frac{1}{2m+1}\to0$ was in reference to why the series $\sum_{n=1}^{m}\frac{2}{4n^2-1}$ doesn't tend to $0$ because both sequences $\frac{1}{2n-1}$ and $\frac{1}{2n+1}$ tend to zero. I accidently overlooked the difference.
Comment: Write out the first few terms in $$\sum\left({1\over2n-1}-{1\over2n+1}\right)$$ and see what you get. As for how $1/(2m+1)\to0$, if you don't understand that, then what do you understand about limits?
Comment: https://en.wikipedia.org/wiki/Telescoping_series
Comment: If you don't understand how $\frac{1}{2m+1} \to 0$ when $m \to \infty$ I suggest you go back to the **very basics** of Calculus before trying to evaluate series likes the one in this question.
Answer: Note that\begin{align}\require{cancel}\sum_{n=1}^m\left(\frac1{2n-1}-\frac1{2n+1}\right)&=1-\cancel{\frac13}+\cancel{\frac13}-\cdots-\cancel{\frac1{2m-1}}+\cancel{\frac1{2m-1}}-\frac1{2m+1}\\&=1-\frac1{2m+1}.\end{align}
Comment: How couldn't I understand that there of numbers have to be got cancelled from some point of series. Nice! $\to +1$


Views: get the raw data

Question: I am building a module where I would like to use the fields from a user generated view.
So let's say the user create a view with 3 fields: Class, Subject, & Nid. I run views_get_view_result() on the view, but that returns entire node objects.
How do I get the simple values like this: {"1 grade", "English", 54} as an array perhaps?
Remember I don't know beforehand what fields have been selected by the user, so I have to get the raw data like that, or be able to see what fields have been selected and in what order.
Just did a print_r on $view->result[1].

stdClass Object
(
    [node_title] => "The Trial" by Franz Kafka
    [nid] => 52
    [node_created] => 1334720754
    [field_data_field_subject_node_entity_type] => node
    [_field_data] => Array
        (
            [nid] => Array
                (
                    [entity_type] => node
                    [entity] => stdClass Object
                        (
                            [vid] => 52
                            [uid] => 1
                            [title] => "The Trial" by Franz Kafka
                            [log] =>
                            [status] => 1
                            [comment] => 2
                            [promote] => 1
                            [sticky] => 0
                            [nid] => 52
                            [type] => assignment
                            [language] => und
                            [created] => 1334720754
                            [changed] => 1334733704
                            [tnid] => 0
                            [translate] => 0
                            [revision_timestamp] => 1334733704
                            [revision_uid] => 1
                            [body] => Array
                                (
                                    [und] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [value] => Many attempts have been made to examine Kafka's legal background and the role of law in his fiction. These attempts remain relatively few in number compared to the vast collection of literature devoted to the study of his life and works, and marginal to legal scholarship. Mainstream studies of Kafka's works normally present his fiction as an engagement with absurdity, a critique of bureaucracy or a search for redemption, failing to account for the images of law and legality which constitute an important part of "the horizon of meaning" in his fiction.

However, James Hawes argues many of Kafka's descriptions of the legal proceedings in The Trial – metaphysical, absurd, bewildering and "Kafkaesque" as they might appear – are, in fact, based on accurate and informed (although exaggerated) descriptions of German and Austrian criminal proceedings of the time, not well understood by many British or American people, who were familiar with an adversarial rather than inquisitorial system of justice. Similarly, the requirement for the traveller to register with the authorities in The Castle to stay a night seems repressive and odd to Britons and Americans, whereas in the present-day Germans (and most continental Europeans) are required to register their address (and hoteliers their guests) with the local authorities.

The significance of law in Kafka's fiction is also neglected within legal scholarship, for as Richard Posner pointed out, most lawyers do not consider writings about law in the form of fiction of any relevance to the understanding or the practice of law. Regardless of the concerns of mainstream studies of Kafka with redemption and absurdity, and what jurists such as Judge Posner might think relevant to law and legal practice, the fact remains that Kafka was an insurance lawyer who, besides being involved in litigation, was also "keenly aware of the legal debates of his day" (Ziolkowski, 2003, p. 224).

In a recent study which uses Kafka's office writings as its point of departure, Reza Banakar argues that "legal images in Kafka's fiction are worthy of examination, not only because of their bewildering, enigmatic, bizarre, profane and alienating effects, or because of the deeper theological or existential meaning they suggest, but also as a particular concept of law and legality which operates paradoxically as an integral part of the human condition under modernity. To explore this point Kafka's conception of law is placed in the context of his overall writing as a search for Heimat which takes us beyond the instrumental understanding of law advocated by various schools of legal positivism and allows us to grasp law as a form of experience"
                                                    [summary] =>
                                                    [format] => filtered_html
                                                    [safe_value] => Many attempts have been made to examine Kafka's legal background and the role of law in his fiction. These attempts remain relatively few in number compared to the vast collection of literature devoted to the study of his life and works, and marginal to legal scholarship. Mainstream studies of Kafka's works normally present his fiction as an engagement with absurdity, a critique of bureaucracy or a search for redemption, failing to account for the images of law and legality which constitute an important part of "the horizon of meaning" in his fiction.
However, James Hawes argues many of Kafka's descriptions of the legal proceedings in The Trial – metaphysical, absurd, bewildering and "Kafkaesque" as they might appear – are, in fact, based on accurate and informed (although exaggerated) descriptions of German and Austrian criminal proceedings of the time, not well understood by many British or American people, who were familiar with an adversarial rather than inquisitorial system of justice. Similarly, the requirement for the traveller to register with the authorities in The Castle to stay a night seems repressive and odd to Britons and Americans, whereas in the present-day Germans (and most continental Europeans) are required to register their address (and hoteliers their guests) with the local authorities.
The significance of law in Kafka's fiction is also neglected within legal scholarship, for as Richard Posner pointed out, most lawyers do not consider writings about law in the form of fiction of any relevance to the understanding or the practice of law. Regardless of the concerns of mainstream studies of Kafka with redemption and absurdity, and what jurists such as Judge Posner might think relevant to law and legal practice, the fact remains that Kafka was an insurance lawyer who, besides being involved in litigation, was also "keenly aware of the legal debates of his day" (Ziolkowski, 2003, p. 224).
In a recent study which uses Kafka's office writings as its point of departure, Reza Banakar argues that "legal images in Kafka's fiction are worthy of examination, not only because of their bewildering, enigmatic, bizarre, profane and alienating effects, or because of the deeper theological or existential meaning they suggest, but also as a particular concept of law and legality which operates paradoxically as an integral part of the human condition under modernity. To explore this point Kafka's conception of law is placed in the context of his overall writing as a search for Heimat which takes us beyond the instrumental understanding of law advocated by various schools of legal positivism and allows us to grasp law as a form of experience"

                                                    [safe_summary] =>
                                                )

                                        )

                                )

                            [field_files] => Array
                                (
                                    [und] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [fid] => 16
                                                    [display] => 1
                                                    [description] =>
                                                    [uid] => 1
                                                    [filename] => Franz Kafka - The Trial.pdf
                                                    [uri] => public://Franz Kafka - The Trial.pdf
                                                    [filemime] => application/pdf
                                                    [filesize] => 977591
                                                    [status] => 1
                                                    [timestamp] => 1334720754
                                                    [rdf_mapping] => Array
                                                        (
                                                        )

                                                )

                                        )

                                )

                            [field_submissions] => Array
                                (
                                )

                            [field_class] => Array
                                (
                                    [und] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [value] => 9B
                                                )

                                        )

                                )

                            [field_subject] => Array
                                (
                                    [und] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [value] => English
                                                )

                                        )

                                )

                            [rdf_mapping] => Array
                                (
                                    [rdftype] => Array
                                        (
                                            [0] => sioc:Item
                                            [1] => foaf:Document
                                        )

                                    [title] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => dc:title
                                                )

                                        )

                                    [created] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => dc:date
                                                    [1] => dc:created
                                                )

                                            [datatype] => xsd:dateTime
                                            [callback] => date_iso8601
                                        )

                                    [changed] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => dc:modified
                                                )

                                            [datatype] => xsd:dateTime
                                            [callback] => date_iso8601
                                        )

                                    [body] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => content:encoded
                                                )

                                        )

                                    [uid] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => sioc:has_creator
                                                )

                                            [type] => rel
                                        )

                                    [name] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => foaf:name
                                                )

                                        )

                                    [comment_count] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => sioc:num_replies
                                                )

                                            [datatype] => xsd:integer
                                        )

                                    [last_activity] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => sioc:last_activity_date
                                                )

                                            [datatype] => xsd:dateTime
                                            [callback] => date_iso8601
                                        )

                                )

                            [cid] => 0
                            [last_comment_timestamp] => 1334720754
                            [last_comment_name] =>
                            [last_comment_uid] => 1
                            [comment_count] => 0
                            [name] => admin
                            [picture] => 0
                            [data] => a:1:{s:7:"overlay";i:1;}
                        )

                )

        )

    [field_field_subject] => Array
        (
            [0] => Array
                (
                    [rendered] => Array
                        (
                            [#markup] => English
                            [#access] => 1
                        )

                    [raw] => Array
                        (
                            [value] => English
                        )

                )

        )

)

In the view I have selected:
Content: Title
Content: Subject (Subject)
Content: Nid (Nid)

Solution:

    $view_fields = $view->style_plugin->options['columns'];
    foreach ($view->result as $index => $row) {
        $view->row_index = $index;

        foreach($view_fields as $field){
            $field_output = $view->style_plugin->get_field_value($index, $field);
            error_log($field.": ".$field_output."\n", 3, "debug.log");
        }
    }

Instead of the error_log build an array instead or whatever you need
Comment: if you could edit your question and include the print_r of what you are getting here, that might help track down your issue..
Answer: EDIT:
Sorry, didn't quite read this exactly.  $view=views_get_view_result() returns that result array.  If you want them in array form, you can cast them, eg, $row0=(array) $view[0]; and now you would have a keyed array of the views results for the first row along with some views housekeeping information like the nid if present, etc.  I should also mention that at times when dealing with nodes, Views only returns the id, or nid, and it's in the render stage that this is turned into a link or body, etc.
ORIGINAL:
Within the $view object, you have $view->result which is an array of values, eg, $view->result[0] contains all the raw data for the first row, $view->result[1] contains all the raw data for the second row, etc.
MORE INFORMATION:
I created a view here that has my 'tagline' field in it, and the result looks like this:
    Array
    (
        [0] => stdClass Object
            (
                [node_data_field_tagline_field_tagline_value] => The Dirty Dirty Duval
                [node_type] => area
                [nid] => 1
                [node_vid] => 1
            )

        [1] => stdClass Object
            (
                [node_data_field_tagline_field_tagline_value] => Atlanta GA is in the house...
                [node_type] => area
                [nid] => 18
                [node_vid] => 18
            )

so I see my tagline field up in there (along with other views housekeeping info) so I am not sure what you are seeing unless your view row style is node instead of fields, but then all you would see is the nid at this point...
Comment: Thanks for the reply :-), however I just did a grep -r "views_get_result" * in the views directory. There is no function called views_get_result() or am I misunderstanding something?
Comment: sorry, that was a typo on my part...I meant to repeat your `views_get_view_result()` (which is a slick wrapper around `views_get_view()` that returns `$view->result`)
Comment: yeah, that's the one I have been using. The problem with that is that you get the entire node object, and no information regarding what fields have been selected by the user and the order of those fields. I have opened an issue on the views project on drupal.org.

It seems a bit strange that this function is not commonly used/known, since I would assume that other module developers would need this functionality. Hopefully MerlinOfChaos will respond to my post. But thanks anyway :)
Comment: Maybe I am not understanding your question/comment, but $view->result is an array of objects that describes each row returned by views, and as such includes each and every field there.
Comment: When I do a print_r on the result of views_get_view_result(). I get the entire node object, not the field selected. So if I have a field in my node called Subject, and I only select subject in my view. I would expect to get an array that consists of only the subject field. not the body, title etc.
Comment: I got this from dawehner( One of the guys behind views ):

Well views_get_view_result returns the raw database result, and yes there are entities involved there. That's "simply"
how d7 has to work.

You might want to try $view->style_plugin->get_field($row_index, 'field') to get the rendered field.

I will look into his and your suggestions. Thanks a LOT guys! :-)
Comment: Good luck!  I've added drupal 7 to the tags so as to avoid further confusion.
Comment: The thing is if i use the above code I am getting a result row like this:
`Array
(
    [0] => stdClass Object
        (
            [nid_1] => 516248
            [nid] => 516248
            [node_data_field_filter_company_name_field_filter_company_nam] => CBRE
            [node_type] => page
            [node_vid] => 516248
            [users_uid] => 646
            [users_name] => testuser
            [users_mail] => email@example.com
        )`
actually I only select user_id, username, and email fields to diply in views dsplay, but here it comng all felds that come in qry. How can I prevnt that?
Comment: @ARUN if you could ask this in a new question with more information about your View, perhaps a screen shot of the Views UI page etc, I would be glad to help out.
Answer: This probably piggybacks on the Jimajamma's post above, but this was some code that I pulled from somewhere (I forget where, it was in the Views queue) for dealing with a similar kind of situation.
$view = views_get_view('view_machine_name');
$view->set_display('view_display_name');
$view->pre_execute();
$view->execute('view_display_name');
foreach ($view->result as $result) {
  // do something with your results
  // print_r() or dsm() from the devel module would be helpful here.
  // dsm($result);
}

Comment: true true, in fact, up until your `foreach`, that's pretty much the guts of `views_get_view_result()` :)
Comment: Good to know. Would be great to get things a little more succinct. :)

Views: get the raw data


Show that $\lim_{n\to \infty}\int_{[0,\infty]}\left(1+\dfrac{x}{n}\right)^n\exp(-ax)=\dfrac{1}{a-1}$

Question: Establish the following limits:

$\lim_{n\to \infty}\int_{[0,1]}\dfrac{n^2x^2}{\exp(nx)}=0$
$\lim_{n\to \infty}\int_{[0,1]}\dfrac{1+nx}{(1+x)^n}=0$
$\lim_{n\to
    \infty}\int_{[0,\infty]}\left(1+\dfrac{x}{n}\right)^n\exp(-ax)=\dfrac{1}{a-1}$
(In the last part, assume $a>1$.)

The first two were relatively simple to do. Just do tabular integration for each and then take the limit and you are done.
However the third one is giving me a hard time to show that the statement is true. I first integrated and found this large complex expansion. But this seems too complicated.
Can I get some suggestions?
Comment: If you know the MCT, you may switch limit and integration.
Comment: Did you know that $\exp(c):=\lim_{n\rightarrow \infty} (1+c/n)^n$ and that further, this sequence is increasing?
Comment: Yes. So I should move the lim inside the integral?
Comment: Yes, you can justify this using the squeeze theorem. MCT is a good way too
Comment: So I have done the switching for the first two problems?
Answer: Note that
$$\left(1+\frac xn\right)^n\le e^x$$
for $x>0$ and $n\ge 0$.  Therefore, the Dominated Convergence Theorem guarantees that we have
$$\lim_{n\to \infty}\int_0^\infty \left(1+\frac xn\right)^n\,e^{-ax}\,dx=\int_0^\infty \,e^{-(a-1)x}\,dx=\frac{1}{a-1}$$
for $a>1$.
Answer: Using Bernoulli's Inequality,
$$
\begin{align}
\frac{\left(1+\frac{x}{n+1}\right)^{n+1}}{\left(1+\frac{x}n\right)^n}
&=\left(\frac{(n+x+1)n}{(n+x)(n+1)}\right)^{n+1}\left(1+\frac xn\right)\\
&=\left(1-\frac x{(n+x)(n+1)}\right)^{n+1}\frac{n+x}n\\[6pt]
&\ge\left(1-\frac x{n+x}\right)\frac{n+x}n\\[12pt]
&=1
\end{align}
$$
That is, $\left(1+\frac xn\right)^n$ is increasing in $n$.
Thus, by Monotone Convergence,
$$
\begin{align}
\lim_{n\to\infty}\int_0^\infty\left(1+\frac xn\right)^n\,e^{-ax}\,\mathrm{d}x
&=\int_0^\infty\lim_{n\to\infty}\left(1+\frac xn\right)^n\,e^{-ax}\,\mathrm{d}x\\
&=\int_0^\infty e^x\,e^{-ax}\,\mathrm{d}x\\[3pt]
&=\frac1{a-1}
\end{align}
$$


Como INFORMAR o nome de um objeto contido em Arrays?

Question: estou praticando um pouco com Arrays essa semana e ao criar o script abaixo eu pensei 'será que posso retornar o NOME do objeto contido no array ao invés de apenar retornar seu índice numérico?'.
O seguinte script faz uma análise rápida nos objetos da minha Array, e em seguida retorna no console se foi ou não encontrado, como posso escrever o nome do objeto que buscamos no resultado de sucesso?

let lista_frutas = ['Banana', 'Uva', 'Morango']
 let auxiliar = lista_frutas.indexOf('Morango')

if (auxiliar === -1){
  console.log('Não encontramos essa fruta')
} else {
  console.log('Sua fruta está bem aqui no índice No. ' + lista_frutas.indexOf('Morango'))
// queria exibir bem aqui, no console, algo como 'Sua fruta está bem aqui, encontramos seu MORANGO'
}
Comment: `indexOf` retorna o índice do elemento, então basta fazer `lista_frutas[auxiliar]`. Mas vc já sabe que está buscando por "Morango", afinal vc faz `lista_frutas.indexOf('Morango')`, então o resultado só pode ser "Morango", bastava imprimir a palavra diretamente...
Comment: Se bem que no seu caso, vc só quer ver se o array contém a string "Morango", então bastava fazer `if (lista_frutas.includes("Morango")) { encontrado } else { não encontrado }`
Answer: Existe o método find(), que retorna o valor do primeiro elemento do array que satisfaça a condição, exemplo:
let lista_frutas = ['Banana', 'Uva', 'Morango'];
let auxiliar = 'Morango';
if (!lista_frutas.find((a) => a === auxiliar)) {
console.log('Não encontramos essa fruta')
} else {
console.log('A sua fruta é', auxiliar)
}

O que esse código está fazendo é: No primeiro if a denotação ! significa que ele espera que dê false para entrar neste primeiro bloco, ou seja, caso não encontre a fruta Morango, retorno aquele bloco, se não, ele exibe a fruta.
Essa é uma das maneiras que pode se fazer, sugiro você ler neste link sobre esse método find() que é bem interessante.
Comment: Nesse trecho 'if (!lista_frutas.find((a) => a === auxiliar))' vejo muitas pessoas usando coisas semelhantes, mas ainda não aprendi como exatamente deveria 'ler' esse tipo de bloco. Aquele (a) ali é justamente a letra inicial da minha variável 'auxiliar'? Se sim, deve ser sempre a primeira letra da variável selecionada ou posso definir um 'i' como já vi fazerem? Mas em suma, muito obrigado <3
Comment: @Kazbonfim `(a) => a === auxiliar` é uma função que recebe um parâmetro (que no caso foi chamado de `a`), e retorna se ele é igual ao valor de `auxiliar` (que é a string que vc está buscando). O que `find` faz é chamar essa função para cada elemento do array (ou seja, vai chamar várias vezes, e a cada vez o `a` será um dos elementos), e se retornar `true`, ele retorna o elemento.
Comment: O if ele espero que o que está entre os parênteses seja verdadeiro, ou seja, if (condição verdadeira) {...executa o código aqui}, então quando coloca a denotação !, ele espera que a condição dentro dos parênteses seja falsa.

O a é um parâmetro genérico, poderia ser qualquer coisa ali dentro. Indico novamente ler sobre o método find( ) e após, ler também sobre callbacks e funções anônimas e esse trecho de código acredita que começará a ficar mais claro. Bons Estudos!


Assume $g$ is defined on $(a,c)$ and uniformly continuous on $(a,b]$ and $[b,c)$ with $a<b<c$

Question:
Problem:
Assume $g$ is defined on $(a,c)$ and uniformly continuous on $(a,b]$ and $[b,c)$ with $a<b<c$.
Show that $g$ is uniformly continuous on $(a,c)$

I think only case we have to consider is when $x$ in $(a,b]$ and $y$ in $[b,c)$ since if $x,y \in (a,b]$ (or the other) then we are done.
How can I prove this using epsilon and delta ?
Answer: Hint: If you find a $\delta$ that works with tolerance $\epsilon/2$ for both $(a,b]$ and $[b,c)$, then...
Answer: WLOG assume $x<y$. Since $f$ is uniformly continuous on $(a,b]$ and $[b,c)$, given $\epsilon>0$, there is a $\delta>0$, for any $x<y\in (a,b]$ and $|x-y|<\delta$, as well as any $x<y\in [b,c)$ and $|x-y|<\delta$, there is $|f(x)-f(y)|<\epsilon$.
If $x\in(a,b]$ and $y\in[b,c)$ that $|x-y|<\delta$, then $|x-b|<\delta$ and $|y-b|<\delta$. So $|f(x)-f(b)|<\epsilon$ and $|f(y)-f(b)|<\epsilon$. Thus
$$
|f(x)-f(y)|=|f(x)-f(b)+f(b)-f(y)|\leqslant |f(x)-f(b)|+|f(b)-f(y)|<2\epsilon
$$
i.e. $f$ is uniformly continuous on $(a,c)$.


how i can get data query cake php in array var_dump?

Question: i have a query in cake php
$sql ="select menu from ms_menu";
$result=advancedQuery($sql);
foreach ($result as $data ){
    echo $data[0];
}

the case is :
the $data[0] show nothing ...
i try to
var_dump $result;

and the result is
output
array(1) { [0]=> array(1) { [0]=> array(1) { ["NAMA_MENU"]=> string(6)  "Report" } } }

i need to get "Report" to my variabel..
anyone knows the problem ?? please help
Comment: There is nothing Cake about this.
Answer: First of all, var_dump(); is a function and you should use it like this : var_dump($result);
Here is your information hierarchy :
- $data
-- $data[0]
--- $data[0][0]
---- $data[0][0]['NAMA_MENU']

Here, you are trying to echo an array ($data[0]). It's not possible.
You can :
— Create a double recursive foreach :
foreach ($result as $data ){
    foreach ($data[0] as $innerData ){
        echo $innerData['NAMA_MENU'];
    }
}

— Get directly your needed value inside the first foreach :
foreach ($result as $data ){
    echo $data[0][0]['NAMA_MENU'];
}


Don't understand proof of minimum modulus principle

Question:
Minimum modulus principle: If $f$ is a non-constant holomorphic function a bounded region $G$ and continuous on $\bar{G}$, then either $f$ has a zero in $G$ or $|f|$ assumes its minimum value on $\partial G$.

1) Why does $f$ has to be continuous on $\bar{G}$ and not just $G$?

Proof: Let $F(z) = e^{f(z)}$. Then $|F(z)| = |e^{f(z)}| = e^{Re(f(z))} \geq e^{Re(f(a))}$ on $B(a, r)$.

2) Why is $e^{Re(f(z))} \geq e^{Re(f(a))}$ on $B(a, r)$? How do we know that the real part of $f(z)$ has a minimum in $B(a, r)$?

Proof (cont'd): Then $F(a) = 0$ or $F(z)$ is constant on $B(a,r)$.

3) How do we know that $F(a) = 0$ or $F(z)$ is constant on $B(a,r)$?

Proof (cont'd): $F(z) \neq 0$ so $F(z)$ is constant on $B(a,r)$, thus $f(z)$ is constant on $B(a,r)$ and by the Identity theorem, $f(z)$ is constant on $G$.

(I understand this last part.)
Comment: Ok I have post an answer, it took me a little bit long than I expected but I hope is clear enough, let me know if have trouble with anything.
Comment: Really ? It is not complete at all. You want a complete proof? I can post it as an answer
Comment: @AlonsoDelfín Yes, then maybe I will understand it
Comment: Ok, I assume you do know and understand the maximun modulus principle right? It is essential to the proof I'll be giving
Comment: @AlonsoDelfín I know it, but understanding it is different I guess...I'll try to understand it
Answer: I am giving a different proof of the one you have since I believe is not complete and that is why you don´t get it. You must already know the Maximum Principle (not modulus), in case you don´t here it is:

Maximum principle If $f: G \to \mathbb{C}$ is a non-constant holomorphic function in a region $G$, then $|f|$ has no maximum in $G$.

A proof of this can be easily obtained as a corollary of the Open mapping theorem.

Minimum Modulus principle If $f$ is a non-constant holomorphic function a bounded region $G$ and continuous on $\overline{G}$, then either $f$ has a zero in $G$ or $|f|$ assumes its minimum value on $\partial G$.

Proof:
I) Lets assume first that $f$ has no zeros in $\overline{G}$, then of course $1/f$ is holomorphic in $G$ and continuous in $\overline{G}$. Thus, by the Maximum Principle above $|1/f|$ attains its maximum in $\partial G$, that is there exist $a \in \partial G$ such that
$$
\left| \frac{1}{f(z)} \right| \leq \left| \frac{1}{f(a)} \right|  \ \forall \ z \in \overline{G}
$$
So indeed for all $z \in \overline{G}$, $|f(a)|\leq |f(z)|$, thus $|f|$ assumes its minimum value in $a \in \partial G$.
II) On the other side, if $|f|$ does not assumes its minimum value on $ \in \partial G$, then there exist $b \in G$ such that
$$
|f(b)| \leq |f(z)| \ \forall \ z \in G
$$
Lets prove that $f(b)$ must be $0$. Assume not, then
$$
\left| \frac{1}{f(z)} \right| \leq \left| \frac{1}{f(b)} \right|  \ \forall \ z \in G
$$
but since $b \not\in \partial G$, the Maximum Principle gives that $f$ must be constant (since the maximum is not attained at the boundary) a contradiction. Thus since supposing that $f(b)\neq 0$ implies that $f$ must be constant, then since $f$ is non-constant by hypothesis we can conclude that $f(b)=0$.
It follows now from I) and II) that either $f$ has a zero $b \in G$ or $|f|$ assumes its minimum value on $a \in \partial G$. $\blacksquare$
Comment: If $f$ has no zeroes, does that automatically make $f$ a constant?
Comment: Not quite. In part I) I have proved that if $f$ has no zeros then $f$ assumes its minimum value at the boundary. While in part II) I have proved that if $f(b)\neq 0$ for that specific $b$, then $f$ is constant, which is a contradiction and then $f(b)$ must be $0$. Is it clear @ᴇʏᴇs ?
Comment: I don't understand why $[1/f]$ attains a maximum
Comment: Ok, since $1/f$ is holomorphic in $G$ and continuous in $\partial G$ then by the Maximum Principle, $1/f$ can not assume a maximum in $G$ right ? Thus the since $\overline{G}$ is compact the maximum must be at $\partial G$
Comment: The relation is required in the maximum modulus principle. For $1/f$ to have a maximum on $\overline{G}$ is must be continuos in $\overline{G}$, since it is holomorphic by hypothesis on $G$ we must ask $1/f$ to be continuos only in $\partial$
Comment: The maximum principle says if $1/f$ is a non-constant holomorphic function in $G$ then $1/f$ has no maximum in $G$. So $1/f$ is continuous in $G$, but how do you know it's a non-constant or constant function? And how do you know if it's holomorphic in $G$, it's continuous in $\partial G$?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/23975/discussion-between-alonso-delfin-and-s).
Comment: We only need part II) actually, what is the point to post part I)?


Families of subsets with "small" intersections

Question: A classic problem in real analysis asserts the existence of $\mathfrak{c}$-sized $X \subset \mathcal{P} (\mathbb{N})$ with $|x \cap y|$ finite for any $x,y \in X$. The solution is fairly simple: swap $\mathbb{N}$ with $\mathbb{Q}$ without loss of generality, and for each $x \in \mathbb{R}$ let $p_x \subset \mathbb{Q}$ be some strictly increasing sequence converging to $x$. Then $X=\{p_x\}_{x \in \mathbb{R}}$ does the trick.
I'm wondering if this problem admits the following generalization.

For any infinite set $S$, there exists an $X \subset \mathcal{P}(S)$ which satisfies the following two conditions: $|X| = |\mathcal{P}(S)|$ and $|x \cap y|< |S|$ for any $x,y \in X$.

A variation of this question would be positing that the size of $|x \cap y|$ have a strict upper bound independent of $|S|$.
That is to say:

There exists a cardinal $\kappa$ such that for any infinite set $S$, there exists an $X \subset \mathcal{P}(S)$ with $|X|=|\mathcal{P}(S)|$ and $|x \cap y|<\kappa$ for any $x,y \in X$.
Comment: You already made it so small that it can't be made smaller. $\mathbb N$ is the smallest infinite set.
Comment: @IvanNeretin I've edited to clarify. Let me know if you believe there are still issues.
Comment: @MathematicsStudent1122 Your edit came just as I was finishing my answer, so I do not really address your second question..
Comment: @Vsotvep That's OK.  Your answer is great. I've upvoted it and will (probably) accept it unless a _substantially_ better one appears.
Comment: I would personally love to read any other answers, if they appear
Answer: What you describe in the first part is what is called an almost disjoint family of subsets of $\Bbb N$. We call $x,y\in\mathcal P(\Bbb N)$ almost disjoint when $x\cap y$ is finite, and thus an almost disjoint family is a family in which all members are mutually almost disjoint.
We can generalise this definition of almost disjointness to any infinite cardinality $\kappa$, by saying sets $x$ and $y$ of size $\kappa$ are $\lambda$-almost disjoint, if $|x\cap y|<\lambda$. Suppose that $|S|=\kappa$, then your generalisation is the statement that there exists a family $X\subset\mathcal P(S)$ of size $2^\kappa$, such that $X$ is $\lambda$-almost disjoint.
This turns out to be quite an interesting statement, and certainly not one that is generally provable, even if we take $\lambda$ as large as $\kappa$ itself (which I will assume in the remainder, and thus write "almost disjoint" instead of "$\kappa$-almost disjoint").
It is a consistent statement, since it is a consequence of $\mathsf{ZFC}+\mathsf{GCH}$:

For each $f:\kappa\to \{0,1\}$, define a set $x_f=\{f\restriction \alpha\mid\alpha<\kappa\}$. If $f,f':\kappa\to\{0,1\}$ are distinct functions, then it's easy to see that $|x_f\cap x_{f'}|<\kappa$. The set $X=\{x_f\mid f:\kappa\to\{0,1\}\}$ is therefore almost disjoint, and has size $2^\kappa$.
We use $\mathsf{GCH}$ to show that $X\subset\mathcal P(S)$ for some $S$ with $|S|=\kappa$. This $S$ is of course the set of functions from any $\alpha<\kappa$ to $\{0,1\}$. Therefore $|S|=2^{<\kappa}$, which is equal to $\kappa$ by $\mathsf{GCH}$.

However, it is also consistent with $\mathsf{ZFC}$ that the statement fails for certain $\kappa$. See for example the last part of this answer on MathOverflow in which a model is produced in which no almost disjoint subset of $\omega_1$ exists of size $2^{\omega_1}$.

If $\kappa$ is regular, we can however always find an almost disjoint family of size $\kappa^+$:

Let $X\subset\mathcal{P}(S)$ and $|X|=\kappa$, then we can find an $y\subset S$ such that $y$ is almost disjoint from all sets in $X$. Let $\langle x_\alpha\mid\alpha<\kappa\rangle$ enumerate $X$. Note that we can assume without loss of generality that $|x_\alpha|=\kappa$ for each $\alpha$.
As $|x_\alpha\cap x_\beta|<\kappa$ for each $\beta<\alpha$, we see that $x_\alpha\setminus \bigcup_{\beta<\alpha} x_\beta$ is nonempty, since the $\alpha$ many sets $\{x_\alpha\cap x_\beta\mid \beta<\alpha\}$ cannot cover all of $x_\alpha$ by $|x_\alpha|=\kappa$ and $\kappa$ being regular. Therefore, let $\gamma_\alpha$ be any any element in $x_\alpha\setminus\bigcup_{\beta<\alpha}x_\beta$, and let $y=\{\gamma_\alpha\mid \alpha<\kappa\}$. Then $y\cap x_\alpha\subset \{\gamma_\beta\mid \beta\leq \alpha\}$, and thus $|y\cap x_\alpha|<\kappa$.


MS DNS permissions on zones script add/remove/query

Question: Anyone know an easy way to modify security across many zones? For example I have a hundred or so reverse pointer zones and I want to make sure a group has certain permission level on all zones. Is there a way to avoid right clicking each and going into security? Also I'd like all new zones to automatically get this group.
Keeping DNS consistent across many DNS servers and managing zones is more painful then it needs to be. Wish I could right-click->security on "Reverse Lookup Zones", similar to how you can set permission at the domain level in AD.
Thanks for any help,
Fred
Comment: What permission, and are the zones AD-integrated?
Comment: Full Control on zone and all sub objects for group "DNSAdmins". Yes AD integrated.
Comment: The domain builtin group DNSAdmins by default has everything except the full control checkbox on the DomainDNSZones partition. Are these zones replicated to the domain or forest?
Comment: Yes I thought that was the case but doesn't seem to be in my environment for some reason. Zones are AD-Integrated and Replicate to "all DNS servers in this domain". DNSAdmins are not on the security tab of a new test zone I created.
Answer: You can use ADSIEdit for this.
Connect to the DomainDNSZones partition:

Right-click CN=MicrosoftDNS > Properties
Security tab
Advanced

If DNSAdmins does not exist, add it, with Applies To: This object and all descendant objects, and check the Full Control box.
Comment: This did it for me, DNSAdmins was only set to "this object" not also "descendant objects". Thanks!


Comparison of two models when the ROC curves cross each other

Question: One common measure used to compare two or more classification models is to use the area under the ROC curve (AUC) as a way to indirectly assess their performance. In this case a model with a larger AUC is usually interpreted as performing better than a model with a smaller AUC. But , according to Vihinen, 2012 (https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3303716/), when both curves cross each other such comparison is no longer valid. Why is it so?
For instance what one could ascertain about models A, B and C based on the ROC curves and AUCs bellow?

Answer: A ROC curve visualizes TPR and FPR for all possible thresholds.

If you plot two ROC curves 'A' and 'B' and they do not cross each other, then one of your classifiers is clearly performing better, because for all possible FPR values you get a higher TPR. Obviously the area under the ROC will also be greater.
Now, if they do cross each other, then there is a point where FPR and TPR are the same for both curves 'A' and 'B'. You can no longer say that one ROC curve performs better, as it now depends on what trade-off you prefer. Do you want high Precision/low Recall or low Precision/high Recall ?

Example: If one classifier performs much better on a FPR of 0.2, but it is important to reach high Recall, then it performs well on a threshold you are not interested in.
About the ROC curves in your graph: You can easily tell that 'A' performs much better, without even knowing what you want to achieve. As soon as the violet curve crosses the others it crosses them again. You are most probably not interested in that small part, where 'B' and 'C' perform slighty better.
In the following graph you see two ROC curves, that also cross each other. Here, you cannot tell which one is better as they kind of complement each other.

Notice, that at the end of the day, you are interested in picking one threshold for your classification and the AUC only gives you an estimation of how well a model performs in general.
Comment: How do you know where precision is large? This is a ROC, not a Precision-Recall curve.
For Precision you check the probability of True Positive, given your classifier said Positive.
Comment: Just for confirmation, in my example, if I choose a very high cut-off value, where precision is large, the model A would out-perform B and C by a good margin?


Code to ensure that at least one checkbox is checked : Doesn't work in Chrome or Firefox

Question: I have a checkbox list for weekdays and I want to make sure that at least one day is selected at all times. I've created the following code but it doesn't seem to work correctly. In IE 8 it works but intermittently and in chrome and firefox it doesn't work at all. Can any one explain what I'm doing wrong?
Cheers
Pete
$(function () {

    var weekdays = $("input[name='WeekDays']");

    $(weekdays).change(function (e) {

        var count = $(weekdays).filter(":checked").length;

        if (count < 1) {

            e.preventDefault();

        }

    });

});

Answer: I think the change event is called after the state has changed, so preventing the default action at this stage does not prevent unselecting it.
However, you could programatically select the checkbox again.
if (count < 1) {
    this.checked = true;
}

DEMO
Note that weekdays is already a jQuery object, so there is no sense in passing it to jQuery again.
Comment: From what I recall, IE fires the change event when the value changes, whereas Firefox and Chrome fire the change event when the checkbox loses focus and the value has changed. Working with the click event instead is generally the best solution, though there are potential downsides.
Comment: @Anthony: No, Firefox and Chrome will also fire the change event directly. Only text boxes fire the change event when they loose focus and the value changed (you can try it in the demo). The big downside of listening to the `click` event is that changes made via the keyboard or other input devices won't be recognized.
Comment: Answer goes to @felix. Interestingly, I can get the my original version to work consistently in IE8 as as I call blur() on the checkbox after calling preventDefault(). This suggests that there is a difference in the way IE and the other browsers handle state changes.


How to represent a Pivot Table as a Mathematical Formula?

Question: How do you represent a Pivot Table (as per Excel) as a mathematical mapping using set theory?
My assumption would be you're basically mapping a Cartesian Product to a count function. However, specifying the count function is where I'm unsure. This is my best attempt at doing one for a count pivot table (averages, sums etc. could be easily tweaked):
$$ C = \{a_i \in \text{Type 1}\} \times \{b_i \in \text{Type 2}\} $$
$$ Rows = \{r_i \in C\} $$
$$ C \mapsto \sum^{|Rows|}_{i=1} c()\text{, where } c() = \begin{cases} 1,& Row_i = (a_i, b_i)\\ 0,& Row_i \neq (a_i, b_i)\end{cases}$$
Is there a simpler way, or clearer more rigorous way?
How can you explicitly declareRows as a multiset?
Full disclosure, my university was pretty bad at providing a good set theoretic background. So my apologies.
Answer: For each column in a table, there is some set it takes its values from. For example, one column could consist of arbitrary real numbers - the set $\Bbb R$, another column could be a fixed list of possible values of arbitrary type: $\{$East, West, South, North$\}, \{$Doris, Kirsten, Scot, Gerry, Lori$\}$, etc. Label the set for column number $c$ as $S_c$.
A Table of size $n$ subordinate to the set sequence $(S_c)_{c=1}^m$  is then a function $$T : \{1,2, ..., n\}\times\{1,2, ..., m\} \to \bigcup_{c=1}^m S_c$$
that satisfies the condition that for all $r$ and $c, T(r,c) \in S_c$.
Let $\mathscr T((S_c)_{c=1}^m)$ be the collection of all tables (of any size) subordinate to $(S_c)_{c=1}^m$. If $(\hat S_c)_{c=1}^k$ is another collection of sets, then a Pivot Table is simply a map $$PT: \mathscr T((S_c)_{c=1}^m) \to \mathscr T((\hat S_c)_{c=1}^k)$$
that is, it is some established method of converting a table subordinate to $(S_c)_{c=1}^m$ into a table subordinate to $(\hat S_c)_{c=1}^k$


how to define an ArrayAdapter for ListView outside oncreate due to update in Kotlin?

Question: I try to get a ListView runnng with update after changing the listItems in Kotlin.
The simple examples I find here are working as long as I stay inside the activity_main. But trying to change items in a function i do not get the defined adapter.
my code:
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    // access the items of the list
    val adapter = ArrayAdapter(this,
        R.layout.mylistviewitem, array)
    //val listView: ListView = findViewById(R.id.listview_1)
    myslist.setAdapter(adapter)

works and gives me the correct list.
But when I try to change the array in a function, I do not have access to "adapter", and thus  not to the "adapter.notifyDataSetChanged()"
I try it with a simple function
fun myfkt() {
    array[1]=" changed?"
    adapter.notifyDataSetChanged()
}

So, the question is:
how do i define the adapter outside of the onCreate (main)function
Things like
var myadapter = ArrayAdapter(this, R.Layout.mylistviewitem,array)

don't work. The compile is o.k, but the app immediatly crashes
(I really spent hours, but found no solution for Kotlin. Taking code from java-examples with converting automatically to Kotlin didn't work either
Answer: Move the declaration for the adapter outside your onCreate function. You should then be able to access it from myfkt()
lateinit val adapter: ArrayAdapter

Then change your onCreate declaration to
adapter = ArrayAdapter(this, R.layout.mylistviewitem, array)

Unrelated to your question, you should considering RecyclerView. It's a much better alternative than ListView, since it formalizes good behavior through use of the ViewHolder pattern.
Comment: Thanks. it works with "lateinit var adapter: ArrayAdapter".
Comment: Due to RecyclerView: for a beginner it seemed easier for me to start with listView. May be, I switch to RecyclerView. But for a simple list of strings, it is beter to keep it simple?
Comment: Absolutely, easier to start with List View, just don't forget to come back and check out RecyclerView when you get more comfortable with Android. Goodluck!


Running azure powershell script through YAML release pipeline

Question: I have my normal and working release pipeline that, by given a certain deployment group, performs some tasks:

Copies a script
Executes that powershell script (on the target machines defined in the Deployment Group)
Deletes the script

I know that YAML doesn't support deployment groups, but (lucky me!) so far my deployment group has only one machine, let's call it MyTestVM .
So what I am trying to achieve mainly is simply executing a powershell script on that vm . Normally, what happenes with the release pipeline, is that you have a tentacle/release agent installed on the VM, your deployment target (which is inside the Deployment Group) is hooked up to that, and your release pipeline (thanks to the Deployment Group specification) is able to use that release agent on the machine and do whatever it wants on the VM itself.
I need the same... but through YAML ! I know there is PowerShellOnTargetMachines command available in YAML but I don't want to use that. It uses PSSession, it requires SSL certificates and many other things. I just want to use the already existing agent on the VM !
What I have in place so far:
pool: 'Private Pool'

steps:
- task: DownloadPipelineArtifact@2
  inputs:
    buildType: 'specific'
    project: 'blahblah'
    definition: 'blah'
    buildVersionToDownload: 'latest'
    targetPath: '$(Pipeline.Workspace)'

- task: CopyFiles@2
  displayName: 'Copy Files to: C:\TestScript'
  inputs:
    SourceFolder: '$(Pipeline.Workspace)/Scripts/'
    Contents: '**/*.ps1'
    TargetFolder: 'C:\TestScript'
    CleanTargetFolder: true
    OverWrite: true

The first part just downloads the Artifact containing my script. And then to be honest I am not even sure I need to copy the script in the second part.. first because I don't think it is copying the script to the VM target workspace, but it is copying it to the VM where the azure pipeline agent is installed. And second: I think I can just reference it from my artifact.. but this is not the important part.
How can I make my YAML pipeline make use of the release agent installed on the VM in the same way that a normal release pipeline does?
Comment: In YAML pipelines, we recommend that you put your deployment steps in a special type of job called a deployment job. A deployment job is a collection of steps that are run sequentially against the environment. Check here: https://learn.microsoft.com/en-us/azure/devops/pipelines/process/deployment-jobs?view=azure-devops.
Answer: Reached somehow a solution. First of all worth mentioning that since deployment groups don't work with YAML pipelines the way to proceed is to create an Environment and add as resource your target VM.
So I didn't need to create my own hosted agent or anything special since the problem was the target itself and not the agent running the pipeline.
By creating an Environment and adding a resource (in my case a VM) to that environment, we create also a new release agent on the  target itself. So my target VM will now have 2 release agents: the old one that can be used by normal release pipelines, and the new one, attached to the Environment resource on Azure Devops that can be used by YAML pipelines.
Now I am finally able to hit my VM:
- stage: PerformScriptInVM
  jobs:
  - deployment: VMDeploy
    pool:
      vmImage: 'windows-latest'
    # watch out: this creates an environment if it doesn't exist
    environment:
      name: My Environment Name
      resourceType: VirtualMachine
    strategy:
      runOnce:
        deploy:
        steps:
        - task: DownloadPipelineArtifact@2
          inputs:
            buildType: 'specific'
            project: 'blahblahblah'
            definition: 'blah'
            buildVersionToDownload: 'latest'
            targetPath: '$(Pipeline.Workspace)'
        - task: PowerShell@2
          displayName: 'PowerShell Script'
          inputs:
            targetType: filePath
            filePath: '$(Pipeline.Workspace)/Scripts/TestScript.ps1'
            arguments: 'whatever your script needs..'

Comment: @CeceDong-MSFT yes! I couldn't accept it as an answer right away :)
Answer: To get the job to run on the specific release agent you want, you can do two things:
Create a pool and only put your release agent into it.
pool: 'My Pool with only one release agent'

Use an existing pool, and publish/demand a capability for your agent.
On the agent machine itself, add a system environment variable (for example, MyCustomCapability. Give it a value like 1
then your pipeline becomes:
pool:
  name: 'My pool with potentially more than one agent'
  demands: 'MyCustomCapability'

If only this agent has this environment variable set, then only this agent can execute the job


If $a^n$ is a unit then $a$ is a unit

Question: Let $R$ be a ring and $\alpha \in R$. Show that if $a^n$ is a unit then $a$ is unit.
My attempt:
If $a^n$ is a unit, then $\exists u \in R$ such that $a^n \cdot u = 1$ and $ u\cdot a^n = 1$. Thus we have $a\cdot(a^{n-1}\cdot u) = 1$ and $(u  \cdot a^{n-1}) \cdot a = 1$. It remains to show that $ (u  \cdot a^{n-1}) = (a^{n-1}\cdot u)$. Any ideas on how to go about showing this?
Comment: You need that n > 0. And more generally, any divisor of a unit is again a unit.
Answer: It's a very standard fact that if an element $x$ has both a left and a right inverse, then they must be equal, and so $x$ is invertible. Indeed, assume $xy=zx=1$. Then:
$z=z(xy)=(zx)y=y$

If $a^n$ is a unit then $a$ is a unit


Why does GCP foundation setup walkthrough recommend "Non-Production" and "Development" environments?

Question: The hierarchy suggested during the "Set up your foundation" step 5. "Hierarchy & access" found within GCP as a banner is the following:

Production
Non-Production
Development

But what is the purpose of Non-Production (possibly: QA, Staging, Sandbox) - and why not include Development environment within Non-Production?
GCP Networking Diagram
Answer: Developers should not touch test or stage environments under the non-production category. Introducing new software has risks of introducing functional or security problems.
As test should be like production, so too should dev be like test. Isolating infrastructure encourages that as new services are being added, they are figured out in dev first. And it helps IT administrators when the compute and network infrastructure follows the same design in each environment. Networks are cheap to set up in the VPC cloud concept.
Bend these rules to suit your organization. A developer may put on their analyst hat to troubleshoot an issue in test. However, they should respect any change control processes, and limit significant changes to the agreed on update procedures.
For those wishing to follow along, the referenced diagram comes from the GCP console's cloud-setup wizard. As the overview mentions, "This guide is intended for large organizations."  Which makes sense for a design that sets up a handful of administrator groups, and assumes several projects.
Comment: The arguments outlined in your second paragraph regarding isolation and "be like" (not very precise engineering terms) I all agree with, perhaps even stronger as a ideally close carbon-copy through GitOps. But why not in this scenario create 4 (dev, test, staging, prod) environments instead of lumping x into the same nonprod category?
It would seem that this makes it more difficult to mimic production within staging..
Comment: I say category, but I'm unclear on how many separate environments that represents, having zero context for the applications and the organization. Duplicate VPCs and create more isolated nets if you wish, and change the design. The goal of this exercise is to diagram an infrastructure that makes sense, running necessary applications, and keeping them in a secure and mass produced box.
Comment: That makes sense. Could be as you allude to; that the diagram with "nonprod" represents any X (staging, test), such that you add additional as needed and not a category with them all lumped together. Needless to say - the diagram is unnecessarily confusing.


Pluggable database not showing the users tablespace

Question: I have oracle 19c multitenant and asm installed.
When I create a container and a pluggable database
by graphic view I can see the users tablespace from the database.
sqlplus / as sysdba
SQL> alter session set container=PDBORCL;
SQL> select tablespace_name from dba_tablespaces;
TABLESPACE_NAME
------------------------------
SYSTEM
SYSAUX
UNDOTBS1
TEMP
USERS

But if I create a container and plugable database in silent mode,
I can only see the users tablespace from the container and if I enter the pluggable database, I can't see the users tablespace.
sqlplus / as sysdba
SQL> alter session set container=TESTPDB;
SQL> select tablespace_name from dba_tablespaces;
TABLESPACE_NAME
------------------------------
SYSTEM
SYSAUX
UNDOTBS1
TEMP

I used these commands to create the container and the database
dbca -silent -createDatabase -databaseConfigType SINGLE -databaseType MULTIPURPOSE \
-templateName General_Purpose.dbc -gdbName TEST -sid TEST -createAsContainerDatabase true \
-useLocalUndoForPDBs true -storageType ASM -datafileDestination +DTA01 -recoveryAreaDestination +FRA01 \
-useOMF true -recoveryAreaSize 9000 -memoryMgmtType AUTO_SGA -totalMemory 4000 \
-characterSet AL32UTF8 -nationalCharacterSet AL16UTF16 -emConfiguration NONE -systemPassword Redhat123 \
-sysPassword Redhat123 -redoLogFileSize 200

sqlplus / as sysdba
CREATE PLUGGABLE DATABASE TESTPDB ADMIN USER usradminapp IDENTIFIED BY Redhat123 FILE_NAME_CONVERT = ('+DTA01', '+DTA01 ')

Answer: Use the query bellow to check the default tablespace in your pdb:
SELECT PROPERTY_NAME, PROPERTY_VALUE
FROM DATABASE_PROPERTIES
WHERE PROPERTY_NAME IN ('DEFAULT_PERMANENT_TABLESPACE','DEFAULT_TEMP_TABLESPACE');

You can re-create the pdb and adding the option "default tablespace" to see if it can solve your problem:
https://docs.oracle.com/en/database/oracle/oracle-database/19/multi/overview-of-pdb-creation.html#GUID-5FC7BAB3-65DE-47E2-9ED7-1093ED784A3C


tableview has nothing?

Question: my tableview has the following method.i have done everything perfectly...numberOfRowsInSection returns 10.....the following method will not be called....it shows nothing......
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

Answer: There are lots of places you could have gone wrong...and if you post some code you're much more likely to get a solution but some possibilities.
Have you also implemented
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

Have you set the tableview's datasource and delegate to your controller? (Either programatically or via interface builder outlets)
Does your controller declare the UITable view datasource and delegate protocols in it's header OR subclass UITableViewController?
Without you providing more info it's pretty hard to give a solution.
Comment: I'm very new to iPad development and missed the dataSource and Delegate connectors so your comment helped me :) Thanks.

tableview has nothing?


Prove that the integral of a nonnegative lebesgue measurable function h is the integral of measures m({h>a} over [0,\infty).

Question: The problem is to prove that a nonnegative, Lebesgue measurable function $h$ satisfies the following equality: $\int h (x)dx=\int\chi_{[0,\infty)}m(${h>b}$)$ $ db$ where {h>b} inside $m$ represents the set {$x\in R^d:h(x)>b$}. Can someone please teach me how to prove this? I was thinking of first proving this when $h$ is a simple function but I am stuck even on this simplification. Also $\chi$ represents the characteristic function.
Comment: HINT: Express $m(\{h > b\})$ as an integral and use Tonelli's theorem.
Comment: @user6247850 That theorem I believe is too strong of a result and ahead of where I am in the course. Can you help me do this more manually for the simple function case?
Comment: If you want it for just the simple function case, show it for $c1_E$ for some $c > 0$ and measurable set $E$.  This statement is almost always shown via Tonelli's theorem, though.
Answer: Let the sequence of simple functions be
$$f_n(x)=\sum_{k=1}^{N(n)}\phi_{n,k}\mathbb{I}_{A_{n,k}}(x),\,A_{n,k}\cap A_{n,j}=\emptyset,\,\forall n $$
As $f_n \uparrow f$ we have $\{f_n>t\}\subseteq \{f> t\},\,\forall n\in \mathbb{N}$ and $\{f_n> t\}\subseteq \{f_{n+1}> t\}$ and we have
$$\{f > t\}=\Big\{\sup_{n \in \mathbb{N}} f_n > t\Big\}=\bigcup_{n \in \mathbb{N}}\{f_n>t\}$$
So by measure continuity
$$\lambda(\{f > t\})=\lim_{n \to \infty}\lambda(\{f_n>t\})$$
We have
$$\lambda(\{f_n>t\})=\sum_{k:\phi_{n,k}>t}\lambda(A_{n,k})=\sum_{k=1}^{N(n)}\mathbb{I}_{\{\phi_{n,k}>t\}}(k)\lambda(A_{n,k})$$
Also
$$\mathbb{I}_{\{\phi_{n,k}>t\}}(k)=\begin{cases}1& \phi_{n,k}> t\\
0& \phi_{n,k}\leq t\end{cases}=\mathbb{I}_{[0,\phi_{n,k})}(t)$$
Therefore
$$\lambda(\{f>t\})=\lim_{n \to \infty}\sum_{k=1}^{N(n)}\mathbb{I}_{[0,\phi_{n,k})}(t)\lambda(A_{n,k})$$
As $\lambda(\{f_n>t\})\leq \lambda(\{f_{n+1}>t\})$ we use MCT
$$\int_{[0,\infty)}\lambda(\{f>t\})dt=\lim_{n \to \infty}\sum_{k=1}^{N(n)}\phi_{n,k}\lambda(A_{n,k})=\int_\mathbb{R} f\,d\lambda$$


Libgdx: Why doesn't the mouse click event Buttons.LEFT register?

Question: For some reason unknown to me, when I use Buttons.LEFT with an event handler, nothing happens. Here is my code:
if (Gdx.input.isKeyPressed(Buttons.LEFT)) {
        System.out.println("Mouse clicked!");
}

If I do, say, Keys.LEFT, or justTouched(), the message prints, but not when I do Buttons.LEFT. And yes, I'm 100% I'm pressing my mouse button, and that it works correctly. ;)
Thank you!
Answer: This is because Gdx.input.isKeyPressed() is for Keyboard input.  If you want mouse button input you should be doing
if (Gdx.input.isButtonPressed(Buttons.LEFT)){
    System.out.println("Mouse clicked!");
}

Buttons and Keys are different classes, and as such have matching methods in input.  Explore the Input API Javadocs of theirs a bit more, it's helped me quite a lot.
http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/Input.html
Comment: That would make a lot of sense! I completely overlooked that. Thanks a lot.


Decay function (e.g. weibull?) with numeric (i.e. not survival analysis) data

Question: An example data frame:
exdf <- structure(list(TENURE = c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, 99, 100, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100), GrowthRate = c(0.522068407541269,
0.285714748576455, 0.185508515947955, 0.197014234790025, 0.0955682840302288,
0.104550241818405, 0.0729165843177029, 0.052710172057008, 0.111205299930434,
0.0842167291103291, 0.0435357167369297, 0.0342561790820088, 0.0697015114811705,
0.0567551900498326, 0.0367956747574549, 0.0300708018467208, 0.0351762377682974,
0.0355785502062602, 0.0212760525934605, 0.0363614825795171, 0.0283660359906612,
0.0276822491674977, 0.0280297636181288, 0.0176973848620943, 0.0269962225046196,
0.0232995719858735, 0.0132348057981257, 0.0231117576016402, 0.0200135248674158,
0.0138992243554679, 0.0204646137008204, 0.0147834886226441, 0.0177097949074607,
0.014717031805624, 0.0132285475095113, 0.0212633514283631, 0.00842835296173483,
0.0145954105765114, 0.0101416096952409, 0.0134118780421613, 0.00938878674984167,
0.0129743252759109, 0.0109985830231452, 0.0283401588275556, 0.0204205991521889,
0.0093976137766294, 0.00910728837933128, 0.00916694752719849,
0.00741753979164272, 0.00881249103330362, 0.0111578966749217,
0.0192836374335688, 0.0120252563211682, 0.00586430387931181,
0.0143027002879901, 0.00370704967795099, 0.00682983045111385,
0.0141476105093492, 0.00482637041824496, 0.00420690319208639,
0.00376569470107668, 0.0109937747749598, 0.0140867803731126,
0.00371637851743323, 0.00717512598946612, 0.00768842197231479,
0.00251049125312619, 0.00187703000356798, 0.0048259385225542,
0.0100417595068638, 0.00374772165540982, 0.0171614859902469,
0.0149367579256126, 0.0115188216576438, 0.00490666943969309,
0.00530930735473234, 0.00723074299963677, 0.00592049387249816,
0.00484467566849744, 0.0124063039986577, 0.00573257723329412,
0.00427949785279758, 0.0030963281113916, 0.00252914919374447,
0.00635090782429515, 0.00210452127168104, 0.00804075169058649,
0.00436670408574535, 0.0035060879778257, 0.00713604840396798,
0.0023981009089411, 0.00175704532860088, 0.000779919174233257,
0.00340671636283396, 0.00460636923636137, 0.00120733393667471,
0.00933279440430645, 0.00305741675516025, 0.00304857402624847,
0.641110630691566, 0.281083708481502, 0.21664831342118, 0.142526508746734,
0.129455004633227, 0.102003156382356, 0.0774235271374781, 0.0549670789691081,
0.0809027507369802, 0.0460263351173751, 0.0653262071979981, 0.047154349769059,
0.0385947285426713, 0.0430288757773969, 0.0406360525819185, 0.0430116335897406,
0.0588492430703393, 0.0532880434533727, 0.0428311618518791, 0.0318427099482772,
0.028791324553973, 0.023804027169529, 0.0201765096165349, 0.0333877840776626,
0.02423781438746, 0.0209281238862644, 0.0152334901166924, 0.0206101546399822,
0.0192309106927642, 0.0217159111858543, 0.0204661728941318, 0.0147045919062503,
0.00963324607321603, 0.0168095825286532, 0.00772585884807775,
0.0141943686223769, 0.0105122199425551, 0.00730692991230875,
0.01505280063156, 0.00993250009012492, 0.0190685740493759, 0.0138696114197483,
0.00991543096798608, 0.0140457461257082, 0.0238644668564838,
0.014335212464454, 0.016231440976755, 0.0136006335528513, 0.010508195169141,
0.0108223681012323, 0.00724634873393271, 0.0114878660557896,
0.010768179227167, 0.0125569796266074, 0.00746257416521345, 0.00541761544241481,
0.00915133561343495, 0.0128090265857459, 0.0128834975364693,
0.00616011529066718, 0.0124072342143222, 0.00813729534453778,
0.00918992619169501, 0.00776227156683262, 0.00770248250797501,
0.00588355687767006, 0.00690140085420765, 0.00508911144051716,
0.00911620445070582, 0.00830466702459098, 0.00520036975577831,
0.00716886970824682, 0.00303064818576892, 0.0053193981576598,
0.00327658374593653, 0.00321651271471524, 0.00513516303969652,
0.00823984725674798, 0.00417642468764257, 0.014131171763804,
0.00787422067561749, 0.00692890013640657, 0.0121753072926065,
0.0070034266847312, 0.00540091988640867, 0.00689103254072876,
0.00506455733404643, 0.00598304422775975, 0.00661625550389644,
0.00732959383078224, 0.00720982160244255, 0.00564679063948148,
0.00435863414775284, 0.00556842035294203, 0.00603506069392346,
0.00548744139395829, 0.00660639356662429, 0.0045943028618467,
0.00490921014265311, 0.713632131494036, 0.316109107238324, 0.19955189191854,
0.149362726365638, 0.140527584352695, 0.122967115856381, 0.0629710542708235,
0.0794423836726601, 0.0723283480042465, 0.048411305500041, 0.0878323397155594,
0.0552740672330323, 0.0540408087274855, 0.0711265884999275, 0.0461176344041601,
0.0421688829740532, 0.0408229960327535, 0.0337191263188075, 0.0365627089380531,
0.0343486264915729, 0.0369672518324808, 0.0324027127903612, 0.0335280505737625,
0.0241231062680551, 0.0315868501489174, 0.0260876281368159, 0.0358190565406051,
0.031770274327048, 0.0307189115217597, 0.0204031908865456, 0.0304622366438121,
0.0488170927658, 0.0395661396435187, 0.0234030909209384, 0.0225458543480528,
0.0312754025113176, 0.0135110740643416, 0.0187184090181205, 0.013568316123143,
0.0170345821576348, 0.0184100113763801, 0.019219623166352, 0.0137349197436514,
0.0131633552715194, 0.0157758351970561, 0.0117732814253362, 0.0111181879788198,
0.0193989282426799, 0.0121149862839278, 0.0136437991248339, 0.0111608014682734,
0.011828405955594, 0.00944009280512503, 0.0123120446979428, 0.0175349768061963,
0.0243703580512893, 0.00775361404112473, 0.0115755699642719,
0.00869789602322868, 0.0230748185953917, 0.011388761136665, 0.0144514590777103,
0.0114791528596783, 0.0121005997846328, 0.00959154057558642,
0.0125793490404558, 0.0106768149670486, 0.00824512497201191,
0.0076573705531775, 0.0104520640098951, 0.0115961878675463, 0.0132315972263175,
0.00453620536761079, 0.00996315028677053, 0.00699906839894915,
0.0100602309904119, 0.00881275005589721, 0.00840590467502622,
0.00410243169790725, 0.00393864651260856, 0.0027632056756115,
0.00604623344076316, 0.00644190206596029, 0.0073296018951492,
0.0062144137386646, 0.00779570731803325, 0.00465780201362875,
0.0141815826452891, 0.0121929551749531, 0.00573235434597308,
0.00512844095153575, 0.0122186637666211, 0.00354975243105926,
0.0158151971904505, 0.006405119131486, 0.00504244314036839, 0.00623419419033411,
0.00664127009174464, 0.00428700468190435)), row.names = c(NA,
-297L), class = c("tbl_df", "tbl", "data.frame"))

Here's a plot of the data:
exdf |>
  ggplot(aes(x = TENURE, y = GrowthRate)) +
  geom_point()

Looks like this:

I would like to model GrowthRate as a function of Tenure.
Just eyeballing the plot, I thought that maybe a Weibull regression would be appropriate. However, all I could find there was survival analysis where one passes a Surv() object to a regression and where the surv object contains 1/0 data for whether or not the observation has survived or not. i.e. binary data.
I'm being deliberately open ended here. What is a 'good' way to model the relationship between GrowthRate and Tenure (in R)?
Comment: All decreasing curved paths are going to look qualitatively similar: that appearance is no basis for choosing a functional form.  Your questions shouldn't be about weibull regression or weibull models or particular curves: they should be about understanding your data.  You don't seem to have any good reason to insist on the use of anything weibull for that purpose, so mentioning it looks more likely to misdirect readers than to guide them towards giving you good advice.
Comment: Could you explain how this differs from your [previous question](https://stats.stackexchange.com/questions/560512/predict-based-on-time-using-a-weibull)?
Comment: At https://stats.stackexchange.com/a/35717/919 and https://stats.stackexchange.com/a/74594/919 I describe a simple, effective method.  It results quickly in `lm(GrowthRate^(1/3) ~ I(-TENURE^(-1/3)), exdf)` and you can go on from there. But parts of your post remain mysterious. I don't understand why you insist on some form of "Weibull regression," whatever that might mean.  And what does this have to do with survival analysis? There's no indication of right censoring.
Comment: In several ways. First, I've provided actual, though disguised data (E.g. your comment over there "A graph that conforms to the formula for a Weibull density is not a Weibull regression model!"). Second, I've worded this in a way to be deliberately open ended. I've hinted towards weibull because I _think_ a weibull is appropriate, but I cannot see how to make it work with this data frame. Actually, I would have liked to delete that post and started fresh with this one but since someone already answered I did not close. But...
Comment: ... , Dave's answer... I struggled to read what was happening here. Is it a weibull? nls() syntax is 'hard'.
Comment: Thanks for these links. "I don't understand why you insist on some form of "Weibull regression,". This is why I'm posting! I know "weibull regression" is a 'thing' because if I search that expression I get a lot of results. But, as far as I can tell they use 'weibull regression' in the context of survival analysis whereas I have a decay analysis...
Comment: If I image search 'weibul regression'I see some lines that look similar to the plot above, e.g. [here](https://www.google.com/url?sa=i&url=https%3A%2F%2Fhelp.xlstat.com%2Fs%2Farticle%2Fweibull-model-in-excel-tutorial%3Flanguage%3Den_US&psig=AOvVaw0u_nYU4ssAUj1Meyb6hmZo&ust=1642706868713000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCLDI_ozGvvUCFQAAAAAdAAAAABAI) or [here](https://www.google.com/url?sa=i&url=https%3A%2F%2Fes.wikipedia.org%2Fwiki%2FDistribuci%25C3%25B3n_de_Weibull&psig=AOvVaw0u_nYU4ssAUj1Meyb6hmZo&ust=1642706868713000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCLDI_ozGvvUCFQAAAAAdAAAAABAP)
Comment: That's why I'm 'clinging' to it!
Answer: Doug, I saw your comment let take this one step at a time.
The Weibull probability distributions functions is
$ \frac{k}{\lambda} * (\frac{x}{\lambda})^{(k-1)}* e^{-(\frac{x}{\lambda})^k}$ for x greater than 0.  This is a 2 parameter model ($k and \lambda$) where we need to estimate the values for both k and lambda.  We have the x (ie tenure) and the dependent variable GrowthRate.
A the nls() nonlinear least squares function is a straight forward way to perform this fit.
This Weibull equation will translate into: "GrowthRate ~ k/lam*((TENURE/lam)^(k-1))*exp(-(TENURE/lam)^k)"
i<-15 #Extra parameter to scale
#Fit k and lambda in with Weibull probability density function
#initial estiamtes is k=1 and lambda=2
model_Weibull<-nls(GrowthRate ~ i*k/lam*((TENURE/lam)^(k-1))*exp(-(TENURE/lam)^k), data=exdf,
                   start=list(k=1, lam=2))

#print summary of model
summary(model_Weibull)

#Now plot using base graphics
plot(exdf$TENURE, exdf$GrowthRate, xlim=c(1, 100))
test <- data.frame(TENURE=1:100)

#Now use the model to make the prediction
test$y<-predict(model_Weibull, test)
#Plot the prediction
lines(test$TENURE, test$y, col="green")

#Now use the model to make the prediction
test$y<-predict(model_Weibull, test)
#Plot the prediction
lines(test$TENURE, test$y, col="green")

#Repeat the fit with a different model
model<-nls(GrowthRate ~ a*exp(-b*TENURE), data=exdf,
           start=list(a=1, b=0.1))
#print summary of model
summary(model)

#Set up the prediction
test <- data.frame(TENURE=1:100)
test$y<-predict(model, test)
#Plot
lines(test$TENURE, test$y, col="blue")

From the image the Weibull model is in green and a simpler exponential model $a *e^{-b*TENURE}$ is in blue.
Hope this explains how to perform a regression with R.
Comment: Very helpful, thank you! I personally find nls() tricky to follow but have been reading some tutorials on it lately
Comment: btw, copying from a tutorial I found, this basic fit did very well on the example data `nls(GrowthRate ~ I(TENURE^power), data = exdf, start = list(power = 1), trace = T)`
Comment: But really appreciate being shown how to use a weibull fit using nls, I half just wanted to know how to do it, regardless of how well it fits
Comment: Yes, it can be tricky, especially if you have the wrong model for the data or your initial estimates are way off.  The error messages from the function can be confusing and unhelpful.  Agreed, the "power fit" is another good option to try.
Comment: It is unreasonable to use a Weibull density (or any other density, for that matter) to fit a model like this, because it presuppose the data integrate to unity.  *At a minimum,* you need to allow for a vertical scaling of the Weibull density values.  When you do this, *the Weibull is an extension of the Exponential model* (corresponding to $k=1$).  Consequently, when this exercise is done right, *it is impossible for the Weibull fit to be any worse than the Exponential fit.* For these reasons I think your results are misleading and not useful.


Formally prove the following equations using propositional logic

Question: p ∧ ¬p $\vdash$ q ∧ ¬q
p ∧ r ⇒ q ∧ r , p ∨ r ⇒ q ∨ r $\vdash$ p ⇒ q
I have literally been trying to figure these out all morning and I'm desperately stuck now. We have to prove them using propositional logic via the formal proof/natural deduction system. If anyone could help me out and explain how they reach their conclusion I'd be immeasurably grateful - thanks.
The ruleset used for this include:
and-elimination
and-introduction
or-elimination
or-introduction
<=>-introduction
<=>-elimination
=>-introduction
=>-elimination
¬-introduction
¬-elimination
Comment: What does the character "$\color{red}`$" mean?
Comment: For the first one, see this [post](http://math.stackexchange.com/questions/1663143/formal-proof-for-q-%e2%88%a7-%c2%acq-%e2%8a%a2-r-%e2%88%a7-%c2%acr).
Comment: @GitGud Oh sorry it's meant to represent the semantic turnstile |-. For some reason it didn't display correctly
Comment: @MauroALLEGRANZA Ok thank you I'll have a look at that link
Comment: @confusedbylogic123 Type `$\vdash$` to get $\vdash$.
Comment: @GitGud Edited the main post thanks
Answer: Hint
For the second one, assume $p$ and derive $p \lor r$ by $\lor$-intro.
Then derive $q \lor r$ from the second premise.
Now we have to consider $q \lor r$ for $\lor$-elim.
From the "alternative" $q$, we have immediately $p \to q$.
From the alternative $r$ we get $p \land r$ and thus $q \land r$ from the first premise.
Now apply $\land$-elim to derive $q$ and then $p \to q$ again.
Thus, we may conclude by $\lor$-elim.
Comment: Thank you for the answer! I'll run through the steps now and see if I can make sense of how I'm doing it


Are discrete random variables, with same domain and uniform probability, always independent?

Question: If $X$ and $Y$ are discrete random variables, both with domain $\{-1,0,1\}$, with uniform probability, does this imply they are independent? What would be the expected value $\mathbb{E}(XY)$ and probability like $\mathbb{P}(XY=1)$ or $\mathbb{P}(XY=-1)$ in this case?
Comment: actually if the domain of a random variable is finite then the random variable is discrete right? i remember there was some kind of rule like if $\Omega$ is finite or countable than $X: \Omega \to \mathbb R$ is discrete. but the converse isn't true like a constant random variable on any uncountable $\Omega$
Answer: It is simple to construct an example where both variables are marginally uniformly distributed, but they are not independent.  The simplest example is to take $X \sim \text{U} \{ -1,0,1 \}$ and let $Y=X$.  In this case both of the variables have a uniform distribution, but they are perfectly correlated.
Comment: You would just take an appropriate sum over the joint distribution.  For example, in the case in my answer we have $\mathbb{E}(XY) = \tfrac{1}{3} \cdot (-1)^2 + \tfrac{1}{3} \cdot 0^2 + \tfrac{1}{3} \cdot 1^2 = \tfrac{1}{3} + 0 + \tfrac{1}{3} = \tfrac{2}{3}$.
Comment: No. Counterexamples are easily constructed
Comment: For example, take mixture of (a) uniform over the four values in $\{-1,0\}^2$ and (b) an atom at $(1,1)$, with mixing weights $\frac23$ and $\frac13$ respectively. The marginals are as required but the correlation is none of the three suggested values
Comment: FWIW, it's even possible to have $X$, $Y$ and $Z$ be uniformly distributed over the same support, such that any two of them are *pairwise* independent, but all three of them are not independent. One simple construction is to let $X$ and $Y$ be independent and uniformly distributed over $\{-1, 1\}$ and let $Z = XY$. A similar trick can work over $\{-1,0,1\}$ too, but requires a slightly more complicated formula for $Z$ (such as choosing $Z$ as the unique solution of the modular congruence $Z \equiv X + Y \pmod 3$ in $\{-1,0,1\}$).
Comment: Thanks, Ben. How can we calculate P(XY=1) or E(XY) in such cases?
Comment: And if it's too much to have the random variables be equal, let $Y=-X$.
Comment: Okay, thanks again Ben! How about the correlation between any two variables that follow these properties? Is it always going to be -1, 1, or 0?
Answer: You can say $X$ and $Y$ each have mean $0$ and variance $\frac23$ and in general

Their covariance is equal to $\mathbb E[XY]$ here and can be any value between $-\frac23$ and $+\frac23$ so their correlation can be any value between $-1$ and $+1$
$\mathbb P[XY=+1]$ and $\mathbb P[XY=-1]$ can each be between $0$ and $\frac23$
$\mathbb P[XY=0]$ can be between $\frac13$ and $\frac23$

If they are independent then

Their covariance is equal to $\mathbb E[XY]$ and is $0$
$\mathbb P[XY=+1]=\mathbb P[XY=-1] =\frac29$
$\mathbb P[XY=0] =\frac59$

It is possible for them to have covariance and $\mathbb E[XY]=0$ without them being independent, for example if $(0,0)$ has probability $\frac13$ while $(+1,+1)$, $(+1,-1)$, $(-1,+1)$, $(-1,-1)$ each have probability $\frac16$, in which case $\mathbb P[XY=+1]=\mathbb P[XY=-1] =\frac13$  and also $\mathbb P[XY=0] =\frac13$
Answer: No, suppose you have $X$ as you described and for $Y$ you flip a coin and in 0.5 probability it takes the value of $X$ otherwise you uniformly sample from $\{-1,0,1\}$.
The marginal probabilities will be uniform yet they are obviously dependent. Short simulation below.
<code>x    <- sample(c(-1, 0, 1), 100000, TRUE)
coin <- rbinom(100000, 1, 0.5)
y    <- coin * sample(c(-1, 0, 1), 100000, TRUE) + (1 - coin) * x

> cor(x, y)
[1] 0.4986911
</code>

You can see that $X$ any $Y$ are dependent and have the same marginal uniform distribution.
Comment: @John: Clearly $\mathrm P(XY=1)$ can take any value from $0$ (when $Y=-X$) up to $\frac23$ (when $Y = X$); just consider mixtures of those two distributions (i.e. let $Y = -X$ with probability $0 ≤ p ≤ 1$ and $Y = X$ otherwise). It's not hard to prove that $\frac23$ is an upper limit, either; just consider the marginal probability that $X=0$. I'll leave calculating the range of $\mathbb E(XY)$ as an exercise, but similar reasoning works there too.
Comment: Thanks Kozolovska! That's a very nice example. Can we calculate P(XY=1) or E(XY) in this case (when they're not independent) ?