Using Selenium on https web application that runs over vpn

Question: First of all, I need to state that I am total beginner with Selenium.
I am trying to test an application in firefox browser using Selenium. Due to security issues the application works only over vpn.
My problem occurs with the following steps; I create the webdriver and navigate to the start (login) page of application. I get an "Authorization request" popup. If I cancel the popup, then I get to a page that states "Connection is not secure" (it's https address). After I get passed that, I lose the part where Selenium program should populate username and password and it just stays on the login page.
My question, is there a way to start Selenium testing on an application so that it is already opened and prepared (ie logged in) in browser? I am not happy that username and password are hard-coded in Selenium code.
If that is not possible, how do I skip that authorization popup and problem with non-secure connection? How do I populate username and password in safest way?
Thanks!
public static void main(String[] args) {
    System.setProperty("webdriver.gecko.driver", "C:\\Selenium-java-3.0.1\\geckodriver.exe");
    // I tried also with this code bellow in comment, but it did not work, it did not even get to login page
    //WebDriverWait wait = new WebDriverWait(driver, 10);
    //Alert alert = wait.until(ExpectedConditions.alertIsPresent());
    //alert.authenticateUsing(new UserAndPassword("cfadmin", "20lipim18"));
    driver.get("https://Application_login_page.com");
    driver.findElement(By.xpath(".//*[@id='login']")).click();
    driver.findElement(By.xpath("[@id='login']")).sendKeys("Username");

}
Comment: Can you consider to showcase your work please? Thanks
Comment: I did research. Also, I already tried suggested first solution earlier (found it here) and few other solutions but nothing works. I was hoping for some advice not criticism. I will add my code here but that will tell you nothing.
Comment: @BiljanaM. A couple of points: 1.As you mentioned `I get "Authorisation request" popup` can you share a snapshot of the "Authorisation request" popup please? 2. `"Connection is not secure"` we would be able to handle it. Thanks
Answer:
if it's possible, is there a way to start Selenium testing on application that is already opened and prepared (logged) in browser?

Try using firefox profile. Since selenium open fresh instance of browser by default. You can use your own firefox frofile.
This is a code to implement a profile, which can be embedded in the selenium code.
ProfilesIni profile = new ProfilesIni();
// this will create an object for the Firefox profile
FirefoxProfile myprofile = profile.getProfile("default");
// this will Initialize the Firefox driver
WebDriver driver = new FirefoxDriver(myprofile)

It will also maintain the session means you are already login to the application in firefox(default profile). Then if you execute the script, you will see that you are already logged in to the application.
Comment: This solution works great (or at least concept, I have done this with Chrome but not FF) -- especially if you need persistent local storage data to be present in something like IndexedDB for client usage in the selenium tests, but don't want to keep re-initializing/fetching that data for each test.
Comment: This does work. So far, no "Authentication" popup, and it looks fine. Thanks!
Answer: There is no way to open already authorised page, you have to have to pass username and password through selenium script.
You may use below code to do the authentication
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(username, password));

Comment: or can pass the username and password in url itself
Comment: I already tried this, it was an answer in similar question with similar problem, but it did not work.


Powershell If then statement not working. How to fix logic?

Question: I can't seem to get this 'if then' statement to work.  What am I doing wrong with this simple statement.
$checkUS = "false"

$usRegions =(Get-EC2Region) |Where -Property RegionName -Like -Value "us-*" |select RegionName | foreach {$_.RegionName}
$allregions=(Get-EC2Region).RegionName

If($checkUS = "true") {$Regions=$usRegions} Else {$Regions=$allregions}

thanks!
Answer: In Powershell, the = operator is used for assignment.
You need to use the -eq comparison operator when defining your IF condition.
Wrong
If($checkUS = "true") ...
Correct
If($checkUS -eq "true") ...
.

The first part (the condition) need the comparison operators
The second part of the statement is performing variable assignments and therefore the = sign is the good call here. {$Regions=$usRegions} Else {$Regions=$allregions}

Reference
About Comparison Operators
Comment: As an aside: In advanced usage, `=` can be useful in conditionals, namely _in combination_ with a logical test, to _assign the result of an expression to a variable for later use_. This is useful if the expression doesn't just yield `$true` or `$false` and therefore relies on PowerShell's [implicit to-Boolean coercion](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Booleans). E.g., `if ($files = Get-ChildItem *.txt) { … }` uses `Get-ChildItem`'s output or lack thereof as an implicit Boolean test, while capturing the output in variable `$files`.


Verifying that a random generator outputs a uniform distribution

Question: I asked a student of mine this question:

If you have a random number generator that outputs a number between
  $1$ and $k$, how would you write a test that decides whether the
  generated distribution is uniform ?

The student understood that we need to call the generator $n$ times and save a histogram $h_i$.
However I would expect the end test to be:
$$\sum{(h_i-\frac{n}{k})^2}<t$$
Where $t$ is a threshold that depends on $n$ and $k$
And what the student suggested is
$$1-t<\frac{h_i}{n/k}<1+t$$
Again, for some $t$ that is a function of $n$ and $k$
Is the student correct ?
Are those two ways equivalent ?
Comment: Both are poor tests.  Use the standard $\chi^2$ test.
Comment: By a *number between $1$ and $k$* is this intended to be a test of a generator of a discrete uniform (values on $1,2,3,...,k$) or a continuous uniform between $1$ and $k$? The phrasing in the quoted part suggests the second, but the part with the histogram suggests the first (since if you were histogramming a continuous variate you'd get $k-1$ bins ... but it wouldn't be the first time someone made a fencepost error in a question). Please make the discreteness or non-discreteness of the random variate clear.
Comment: The issues to address in a testing situation like this are not "validity" but *power* and *efficiency*.  I confess I don't fully understand the student's suggestion because it appears to be a collection of criteria applied separately to each $i$ without stating how those results are to be combined into a single test. I have therefore not been reading this question closely, because I believe it must have typographical errors in it, and have only responded to the general nature of it.
Comment: $\chi^2$ test (or any other test) answers the question "**how** do you determine the threshold ?", whats interesting here, is "**what** do you do with the threshold ?"
Comment: Could you elaborate? Your stated question asks for a decision concerning whether the distribution is uniform or not. Your subsequent remarks appear to focus on developing a test statistic. (Both suggestions are likely to be inferior to the $\chi^2$ statistic for detecting non-uniformity.)  In this context, what do you mean by "what do you do with the threshold"?
Comment: In the question, the suggested algorithm is to set a threshold $t$ such that $\sum{(h_i-\frac{n}{k})^2}<t$. Now the $\chi^2$ test is a special case, for setting $t=\chi^2*\frac{n}{k}$.
Comment: The question is, are there any cases in which the "student's solution" would not be valid ?
Comment: Discrete uniform...
Answer: Note that we cannot conclude on the basis of only a sample that data is drawn from a uniform, only that it is consistent with having come from a uniform (sufficiently small deviations will be undetectable at any given sample size), or that it is not consistent.x
Since the request is for a test rather than simply a measure, presumably it is goodness of fit of uniformity that is the principal object.
There are a host of tests of uniformity that focus on different test statistics, and offer different power against various alternatives. It often makes sense to focus on the known ones instead of causally inventing new ones, because their characteristics are understood and (in particular) the kind of situations where they have good power will often be known.
I discuss some possible choices of statistic here.
Note that if your observations are an iid sample from a uniform, then histogram counts will have a multinomial distribution.
There are effectively two suggested test statistics in your question. Setting $E_i = n/k$, and slightly rearranging the second:

$T_1=\sum_i {(h_i-E_i)^2}$

$T_2=\max_i|\frac{h_i}{E_i}-1|$

Since your $E_i$ is constant over $i$ ($=E$ say), the first statistic is a scaled chi-squared test statistic ($T_1=E\cdot X^2$). So critical values (marking the boundary of the rejection region, i.e. your "t") can be determined quite readily.
Note further that 2. is equivalent to using the largest absolute Pearson residual (for either a Poisson or multinomial model) as a test statistic, since $\sqrt{E}\cdot T_2 = \max_i|\frac{h_i-E_i}{\sqrt{E_i}}|$ - noting further that $\sqrt{\frac{E}{1-p}}\cdot T_2 = \max_i|\frac{h_i-E_i}{\sqrt{E_i(1-p_i)}}|$ - where $p_i=p=k/n$).
I have suggested$^\dagger$ using just a statistic equivalent to $T_2$ as a quick visual test when testing roleplaying dice for uniformity (which dice generate discrete uniforms). While not a "standard" test, it's not hard to find critical values here either. This is particularly suitable when the alternative is for a single discrepant bin to have a substantially higher or lower proportion than expected but where the remaining bins are uniformly sharing the rest of the probability.
$^\dagger$ - see the dashed and dotted grey lines in the last two plots there, which mark two different choices for $t$ with different type I error rates.
If you expect (or are most interested in being able to pick up) particular kinds of deviations, other statistics may be better than either of these.
Answer: It's like saying $a$ is close to be $b$ when $a-b$ is 0 or when $\frac{a}b$ is 1.  I don't see why one should be better than the other.
Comment: @whuber: I don't think they're equivalent (never said they were).  But any measure of "uniformity" seems to me to be arbitrarily defined.
Comment: @whuber I also don't agree with your interpretation of my phrasing.  I don't see why dogs should be better than cats does not mean that I think dogs and cats are equivalent.  It does sound like I'm saying that they are equally good.  And that is all I said in my answer.
Comment: This is not a veterinary site; statistical procedures are not animals. In statistics, it is standard that "equally good" tests are tests with identical risk functions.  If that's not what you meant, your answer is likely to be misunderstood, so you ought to consider clarifying your meaning. Your claims about "uniform" being "personal" fly in the face of all the literature on [testing RNGs](https://www.google.com/search?q=testing+RNGs&ie=utf-8&oe=utf-8), so there's no need to argue that one.
Comment: @whuber  Yes, I know about testing rngs.  My point is that you need to define a loss function for this to be a well-defined problem.  It's not enough to say "equiprobable" — you need to define the loss incurred by some particular variation from equiprobability.  These are two different measure of equiprobability.  It really depends on the application which one makes more sense.  This is the same thing as in a regression problem saying that the ideal loss function is least squares versus say logistic.  Each loss function depends on the application.  There is no "ideal loss function".
Comment: @whuber  Okay, I will do that, thanks for the suggestion.  Yes, I knew there was some analysis possible with this question.  For example, what is the probability a truly uniform RNG fails either test for given thresholds.  I usually leave the harder math on this site to people like you ;)
Comment: The problem is that the two test statistics are not mathematically equivalent when there is more than one bin--and that suggests this answer is misleading.
Comment: I believe most people would understand "I don't see why one should be better than the other" to mean they are equivalent in your opinion. But do you really mean "arbitrarily defined"? Even when the problem concerns a random generator for a set of integers $\{1,2,\ldots, k\}$? Besides the implicit sense of "equiprobable" expressed in the question, what alternative meanings of "uniformity" do you have in mind that would make sense and be meaningful in this context?
Comment: @whuber I mean that if I gave you to sets of numbers, it seems like a very personal question which one is more "uniform" than the other.  "Random" is also for that matter very uniform.
Comment: With those qualifications, what you have been saying makes sense!  It would be nice to see them appear in the answer itself.  (On the other hand, for testing an RNG the application is well defined.  It would be interesting to work out what loss function a standard test corresponds to and what loss functions correspond to the tests suggested here. I suspect that for many useful loss functions these two tests may be inadmissible.)
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/37636/discussion-between-neil-g-and-whuber).
Comment: You got me there ;-).  Nowadays I barely have time to act as a moderator; I have to leave the answering of tough questions to more knowledgeable or energetic people.
Answer: A test that is actually used in testing the R random number generators is based on the cumulative distribution function (rather than histogram or density), with test statistic
$$d=\max_t\left\{\left|\frac{\sum_i (X_i\leq t)}{N}-F(t)\right|\right\}$$
This test takes advantage of Massart's inequality,
$$P(\sup | F_n - F | > t) < 2 \exp(-2nt^2)$$
which gives a bound on the tail probability of $d$ that holds for all continuous and non-continuous $F$, and all $n$ and $t$.
Answer: UPDATE 2: striked wrong points, and replaced some by stuff I think are correct.
UPDATE 1: added direct analysis of both your uniformity tests, and kept my old answer as a proposed superior uniformity test that I suggest.
Summary

Both you and your student have offered uniformity tests that work.
Both of your tests don't work well with continuous numbers (i.e. if RNG spits out numbers in $[1,k]$ instead of $\{1,2,\ldots,k\}$.
Since the output of your uniformity score is not a probability, I think it has the disadvantage of being difficult to interpret.
Since your student's uniformity score is a probability, I think it has the advantage of being easy to interpret.
While not harmful to the correctness of the test, your student's uniformity test has one aspect that is useless (but also harmless; just redundant), namely: there is not point to add $t$ on right side of the inequality as the output is a probability.
One small error in your student's uniformity test is using $<$ instead of $\le$ for the upper bound. I think he/she should have used $\le$.

On the other hand, I think my proposed test is:

Unlike your tests, mine works with continuous numbers.
Similar to your student's test, mine is also easy to interpret cause it's a probability as well.

The disadvantage is that my test is possibly harder to compute. But this is not a big deal as I think the correctness of the test is worth the slight increase in difficulty.
Analysing your uniformity tests
Your notation confused me a bit. I assume that you mean that $h$ is a histogram, and $h_i$ is the frequency that is associated with input $i$ where $i$ is some number between $1$ and $k$ (which your RNG produces).
So to rewrite your test, I think you wanted to say this:
\begin{equation}
\text{teacher uniformity score} = \sum_{i \in \{1,2,\ldots,k\}} (h_i - \frac{n}{k})^2
\end{equation}
Then the uniformity test: the RNG is uniformly distributed if the uniformity score is less than some threshold $t_{teacher}$ that we agree upon. I.e. output from RNG is uniformly distributed if the following statement is true:
\begin{equation}
\text{teacher uniformity score} < t_{teacher}
\end{equation}
I see why your method makes sense. Basically, your score is essentially the sum of squared errors of observed frequencies against expected frequencies, where expected is what should happen if the RNG is perfectly uniform. So if the sum of squared errors is minimal, the more uniform it is.
So my opinion about your test is this:

Pros:

it does have merit, and it does reflect the degree of uniformity of the RNG.

Cons:

it is not easy to interpret because the output is not a probability. If you augment it such that the output is a probability, then it would be easier to interpret. At least I can't interpret it easily. This interpret-ability is a subjective thing.
it is not friendly with continuous RNGs. You can't use histograms with continuous numbers without approximating numbers into bins, which essentially deletes information and opens the vulnerability that might potentially lead to masking non-uniformity of some poor RNGs. We need to look at the probability density functions (PDFs) instead.

What you wrote about what your student claimed is also confusing, but I rewrite that to what I think is the closest thing that makes best sense in my view (kindly correct me if you think the student didn't say this):
\begin{equation}
\text{student uniformity score} = \sum_{i \in \{1,2,\ldots,k\}} \frac{h_i}{n/k}
\end{equation}
This is essentially the ratio between observed histogram and expected histogram (expected is the perfect uniform one). Clearly, if the ratio is 1 then it's perfectly uniform. But if it isn't (i.e. greater or less than 1) then it is not perfectly uniform.
So your student is suggesting that the closer the ratio is to 1, the more random it is. So $t_{student}$ is essentially some kind of error term that accounts for deviations from 1:
\begin{equation}
1-t_{student} \le \text{student uniformity score} \le 1+t_{student}
\end{equation}
My opinion about your student's uniformity test is as follows:

Pros:

It does have merit for the same reason yours does.
It is easy to interpret (thanks to it being a probability). This is subjective though. I think most humans agree with me (correct me if you disagree).

Cons:

It's not easy to interpret just like yours.
It doesn't work well with continuous RNGs for the same reason yours doesn't.

My test which I think is superior to both of your tests
Based on the question, you only seem to be interested in finding whether a sequence is uniformly distributed. I.e. it doesn't need to satisfy any other property.
If your PRNG is outputting some float, e.g. something in $[0,1]$, I would personally suggest doing this (which seems somehow similar to your student's suggest? I don't know..):

Repeat PRNG $n$ times, where $n$ is large enough.
Estimate the true probability density function $f_X$. Let $\hat f_X$ be your best estimation.

Then your sequence is perfectly uniformly distributed if $\hat f_X(x)$ forms a line with a slope of 0. This is usually unachievable in reality.
So you need to define a degree of uniformity that, if satisfied, you subjectively declare that the PRNG is uniformly distributed.
To do this, I would personally suggest to define the null hypothesis:

A sequence is uniform if the probability of each number to appear is $1/n$.

You then compute the probability based on your empirical trials.
Finally, you do some variant of Fisher's exact test to find the probability that your sequence can exist if the null hypothesis is true.
Once you get that probability, it is there where you plug your threshold. You and your student need to agree on this threshold. It's subjective.
In this specific approach, I'd expect you to agree on a very large probability that is very close to $1$. Maybe $0.999$, or whatever you and your student seem to be happy with.
Or maybe do the opposite: define the null hypothesis as:

Your sequence is not uniform, and probability of each number to appear is not $1/n$.

Then, you need to choose a a very small threshold in order to reject it.
Comment: Dude my answer is incorrect at least with respect to analyzing your student's test. It's clearly not a probability :D -- sorry. I just had a brain fart when I wrote that answer. You need to unmark this answer as an accepted answer because it's still wrong.


Can I use std::lower_bound on function calls instead iterators?

Question: Simple use case: I want to find with binary search the minimal index i for which f(i)>=t, where t is some threshold and f is a monotonically increasing function over integer values.
A simple way to go would be to just call this function on every possible input, save it to a container and then use lower_bound, this would be useful in a scenario where I want to do multiple searches on the same function with different thresholds.
However, in my scenario, function evaluations are runtime expensive and I have multiple different functions/lambdas on which I only perform a single binary search.
So I guess, what I need, is either a lower_bound function taking a function and a value range instead of start and end iterators, or I need a mechanism to hide the function calls inside an iterator structure. I know the first solution is easy to implement, but I hoped for a solution that would avoid implementing binary search from scratch.
To me, this seemed like a common use case but somehow I failed to find anything on this particular problem on the web. I'd appreciate any tips, tricks, and links.
EDIT
I found the two first provided solutions very intriguing. The given solution using the comp argument is very elegant, however I forget to mention a reason why this approach does not work for me. In addition to long runtimes for a single function evaluation I also have the problem of having a large search space (e.g. over 10**15 integers) which makes it impractical to allocate a dummy vector for this purpose. I do not know how it would work with the boost increment iterators but I need something to work with std only anyway.
The second solution using a custom iterator is quite verbose though. I tested it with the large number I mentioned (and changing the ints to long longs) but this seems to be also to slow. It seems that lower_bound actually calls the operator++ several times to go from one location to the other, so the implementation of the std::lower_bound might already be the killer for my approach here (see below modified code example and output) and there is no way around a custom implementation (which I already have, no need here).
Thanks, however, for the insights, both answers showed me something new. And maybe someone can shine some more light on the points mentioned above, as I am definitely no expert on iterators or the implementation of lower_bound, maybe I used it wrong or it is something about the code example given by @idclev that makes it iterate this inefficiently through the numbers which I did not recognize.
Modified code example
#include <iostream>
#include <unordered_map>
#include <algorithm>

long long foo(long long i){ std::cout << "function evaluation:\t" << i << std::endl; return i;}

using function_type = long long(*)(long long);

template <function_type F>
struct fun_iterator {

    using difference_type = size_t;
    using value_type = long long;
    using pointer = int*;
    using reference = int&;
    using iterator_category = std::forward_iterator_tag;

    static std::unordered_map<long long,long long> m;
    long long index;
    fun_iterator(long long index) : index(index) {}

    fun_iterator& operator++() {
        std::cout << "operator++:\t" << index << std::endl;
        ++index;
        return *this;
    }
    fun_iterator operator++(int x) {
        fun_iterator it = *this;
        ++index;
        return it;
    }
    int operator*() {
        auto it = m.find(index);
        if (it != m.end()) return it->second;
        auto res = F(index);
        m[index] = res;
        return res;
    }
    bool operator!=(const fun_iterator& other){
        return index != other.index;
    }
    bool operator==(const fun_iterator& other){
        return index == other.index;
    }
    bool operator<(const fun_iterator& other){
        return index < other.index;
    }
};

template <function_type F>
std::unordered_map<long long,long long> fun_iterator<F>::m;

template <function_type F>
std::pair<fun_iterator<F>,fun_iterator<F>> make_begin_and_end(long long begin,long long end){
    return {{begin},{end}};
}

int main() {
    auto x = make_begin_and_end<foo>(0,10L);
    auto it = std::lower_bound(x.first,x.second,4L);
    // auto x = make_begin_and_end<foo>(0,1000000000000L);
    // auto it = std::lower_bound(x.first,x.second,400000000000L);
    std::cout << it.index << std::endl;
}

and the output:
operator++: 0
operator++: 1
operator++: 2
operator++: 3
operator++: 4
operator++: 5
operator++: 6
operator++: 7
operator++: 8
operator++: 9
operator++: 0
operator++: 1
operator++: 2
operator++: 3
operator++: 4
function evaluation:    5
operator++: 0
operator++: 1
function evaluation:    2
operator++: 2
operator++: 3
function evaluation:    4
function evaluation:    3
operator++: 3
4

Answer: As @KamilCuk suggested, write your own iterator, or alternatively
You can take any container of natural numbers (if you don't have ranges at hand, simply create an std::vector<int> and populate it with monotonically growing numbers — provided you at least know the boundaries of expected interval your expected value lies within). Next, std::lower_bound accepts a comp argument:
std::vector<int> args(1000);
std::iota(args.begin(), args.end(), 0);
root = std::lower_bound(args.cbegin(), args.cend(), t,
        [](int x, int t){ return f(x) < t; });

(As a sanity check, check if root is args's begin — then 0 can be higher than your desired root — or is args's end — then the root is higher than the estimated right boundary.)
Comment: I would add that the vector can be filled with `std::iota` algorithm.
Comment: Instead of `std::vector`, you can employ [`boost::counting_iterator`](https://www.boost.org/doc/libs/1_50_0/libs/iterator/doc/counting_iterator.html): `std::lower_bound(boost::counting_iterator(0), boost::counting_iterator(1000), ...);`.
Answer: You can write your own iterator and to avoid unnessesary evaluations of the function, you can use memoization. The iterator can have a static map to cache results of function calls. To make iterators for different functions a different type, I parametrized the iterator on a function pointer:
#include <iostream>
#include <unordered_map>
#include <algorithm>

double foo(int i){ return i;}

using function_type = double(*)(int);

template <function_type F>
struct fun_iterator {

    using difference_type = size_t;
    using value_type = int;
    using pointer = int*;
    using reference = int&;
    using iterator_category = std::forward_iterator_tag;

    static std::unordered_map<int,double> m;
    int index;
    fun_iterator(int index) : index(index) {}

    fun_iterator& operator++() {
        ++index;
        return *this;
    }
    fun_iterator operator++(int x) {
        fun_iterator it = *this;
        ++index;
        return it;
    }
    int operator*() {
        auto it = m.find(index);
        if (it != m.end()) return it->second;
        auto res = F(index);
        m[index] = res;
        return res;
    }
    bool operator!=(const fun_iterator& other){
        return index != other.index;
    }
    bool operator==(const fun_iterator& other){
        return index == other.index;
    }
    bool operator<(const fun_iterator& other){
        return index < other.index;
    }
};

template <function_type F>
std::unordered_map<int,double> fun_iterator<F>::m;

template <function_type F>
std::pair<fun_iterator<F>,fun_iterator<F>> make_begin_and_end(int begin,int end){
    return {{begin},{end}};
}

int main() {
    auto x = make_begin_and_end<foo>(0,100);
    auto it = std::lower_bound(x.first,x.second,50);
    std::cout << it.index;
}

The map will be reused also for later instances of fun_iterator for the same function. And because it is parametrized on the function pointer, a fun_iterator for a different function uses a different map to store the results.


How to resize a custom UIView and maintain its custom draw in proportion?

Question: I have a custom view with some drawing on it.
I want to resize it to a new proportion and I want the pattern I drew in it's drawRect to also be resized by the same proportion.
Is there anyway I can accomplish this without refreshing and redrawing everything.
Comment: some drawing should have autoresizing masks
Answer: This should be happening for you automatically with the default contentMode, which is UIViewContentModeScaleToFill. contentMode determines how to adjust the cached bitmap without forcing a new call to drawRect:. Also see contentStretch which allows you to control which part of the view is scaled.
Answer: you will have to redraw it for the new proportion.
For that you have to store the points that made the CGPath and scale the points according to the new proportion and render it again.
Redrawing CGPath needs attention.

If you have used simple moveTopoint / AddlinePoint you can do it just by storing points in an array. You can scale and redraw it later.
If you can used functions like addcurveTopoint  etc., storing points in array won't work.A general purpose way is needed.For that you have to use the CGpathApply function. You can see an example it here. http://www.mlsite.net/blog/?p=1312
If you need to zoom and no interation neeeded you can take a scrrenshot and and zoom the image.


Is it possible to use AWS as a web host?

Question: Is it possible to load / host an entire website using AWS? Or is it only a service that can load specific pieces of a website - such as images, etc. Obviously, I'd want to use my own domain. If you can use it, are there any limitations?
Here's the AWS link, for context:
http://aws.amazon.com/s3/
Comment: I voted to close this question because it is not a programming question and it is off-topic on Stack Overflow.   In the future, non-programming questions about your website should be asked on [webmasters.se].
Answer: AWS = Amazon Web Services = a suite of different web services.
S3 (which you linked to) is an object store.  You can't host a web service on S3.
EC2, also under the AWS umbrella, is virtualized compute space.  You CAN host a web service on EC2.  It is just like having a server in a rack somewhere, except that when you shut down an instance, it is gone forever.  But using EBS, which is like a virtualized hard drive, will prevent you from losing your data when the EC2 instance shuts down.
See http://aws.amazon.com/ec2/ and http://aws.amazon.com/ebs/
Comment: So, to be totally clear... you can point a domain to EC2 and have it resolve within the cloud somehow?
Comment: @unknown (google): Yes, your EC2 instance will have a publicly available IP address.  You just need to make sure it's got port 80 open.
Comment: Oh.. as per your description, I initially thought it was something that may just suddenly happen.
Comment: When is an EC2 instance shut down?
Comment: @Oscar Reyes:  An instance is shut down when you choose to shut it down.
Comment: You can, but I think that generally, it would be cheaper to host a site on a dedicated site hosting (and a non EIG one).
Answer: EDIT: Aug 12, 2016 they have a dedicated section on how to get started hosting a website on AWS. Please note S3 only allows STATIC websites but AWS provides SDKs in case you want to run PHP, ASP.NET, etc on your instance. See the links for more details.
http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html
https://aws.amazon.com/websites/

So guess what I just found while doing some Google searches for hosting on AWS?! A blog post by the AWS stating that you can (now) host a website on S3. (Funny enough, the StackOverflow and the AWS post were right next to each other in the SERPs!)
http://aws.typepad.com/aws/2011/02/host-your-static-website-on-amazon-s3.html
Answer: Yes it is completely possible to host websites on AWS in 2 ways:
1.) Easy - S3 (Simple Storage Solution) is a bucket storage solution that lets you serve static content e.g. images but has recently been upgraded so you can use it to host flat .html files and your site will get served by a default Apache installation with very little configuration on your part (but also little control).
2.) Trickier - You can use EC2 (Elastic Compute Cloud) and create a virtual Linux instance then install Apache/NGinx (or whatever) on that to give you complete control over serving whatever/however you want. You use SecurityGroups to enable/disable ports for individual machines or groups of them.
@danben your EC2 instance does not have a constant public IP by default. Amazon makes you use a CNAME - not an A record as your IP may change under load. You have to pay for an ElasticIP to get a consistent public IP for your setup (or use some sort of DynDNS)
Answer: As @danben mentioned, there is a difference between S3 and EC2.
One thing that may be interesting for people looking to host a website on Amazon, specially if they want to start small is that Amazon started offering a free tier some months ago. Together with services like BitNami Cloud Hosting (disclaimer, I helped design it, so it is a bit like my baby :)  means you can get your site on the Amazon cloud in just minutes, for basically 0 dollars. You still need to give credit card info to Amazon, but it will not be charged if you stay within the limits of their free tier.
One thing to consider too is that at the time of writing this (Jul 2011), Amazon restricts you to one IP address per server. If you need to host multiple domains, you may need to use name-based virtual hosts or some tricks using their Elastic Load Balancer (which will cost you more). But all in all, it is worth a try if you are a bit technical and want more control than what shared hosting provides you
Answer: At reinvent 2018, AWS launched the Amplify Console, a continuous deployment and hosting service for single page and static apps with serverless backends. Check it out: http://console.amplify.aws
Answer: Yes! You can easily host your website on AWS.
There are two ways;

One with Native AWS - This is a tricky method that requires expertise and a series of commands to run. You need to manage security, DNS, SSL, server protocols, and more by yourself.
Managed Cloud Platforms like Cloudways - You can easily launch an AWS server and host your website with a few clicks. Moreover, you can quickly manage your server protocols, packages, security firewalls, DNS, and more from its intuitive platform.


How to write a regex that matches a string containing at least 4 letters?

Question: Ex:  I want to ensure that a string must contain A, B, C, D
  test strings:
  "ABCDF" will be true
  "AACDF" will be false (it not contains 'B')
  "AABCDFG" will be true (it allows duplicated words)

Thanks to everyone!
Comment: Have you tried anything?  Do some research, try it out, we will help if you demonstrate some effort.
Comment: Possible duplicate of [Regex to match only letters](https://stackoverflow.com/questions/3617797/regex-to-match-only-letters)
Comment: yes, Nic3500, I read and try some such as (*.[abcd]{1,}.*){4,} , it can not exclude the string like 'aabbff'
Comment: @antonio-steve to combat that look into how anchoring works...
Answer: If you want a regex matching a single word containing 4 particular
letters (in some bigger text), you can use:
(?=\w*A)(?=\w*B)(?=\w*C)(?=\w*D)\w+

It contains 4 positive lookups.
Each of them looks for A, B, C  and D, respectively,
after a number of word chars (possibly 0).
Then there is the actual matching part - a sequence of word chars.
You should use also g (global) option, to match all such words.
Another possibility is that you want to verify the whole string (something
like password criteria verification).
Then the regex can be:
(?=.*A)(?=.*B)(?=.*C)(?=.*D).+

The differences are that:

Each lookahead looks for the particular char after any number
of any chars (instead of word chars).
The matching part contains also any chars (matches the whole string).
g option is not needed.


Should I remember the diatonic chord names of each scale?

Question: I've mainly been playing chords/scales based on patterns that I remember. But do you think it's worthwhile to actually remember/take time to commit to memory the names of each chord in each key?
So if one would ask, what's the diatonic chords of Ab? should I know "Eb major, Ab major, Db major, fminor, etc" right away?
I play both piano and guitar and I'm looking to be able to better move between them, so I'm thinking this might be an important thing to do. (?)
Answer: If I understand your question, my answer is "No". As in, "don't go through the trouble to memorize chord names". That seems like a waste of time.
I do recommend practicing in various keys and working through the process of finding and playing all the diatonic chords in different keys. If you can find and play the chords when you need to, it doesn't matter if you can name them off the top of your head. If you really need the name, find it and play it, then look at your fingers and figure out the name.
Being able to play the chords of a key when you want helps you write and improvise, and it will also help your sight reading. Mainly you want to imprint the patterns of the chords in your brain. For example, you want to know intuitively that the third of the V chord is the seventh degree of the major scale. If you're writing or improvising and you want to use the seventh degree as a leading tone back to the tonic, you want to know pretty quickly what your options are: the iii, the V, and the vii (dim) (for diatonic triads). Then you can determine what makes sense based on the chord you want before the leading tone (e.g., do you want to go stepwise up from ii or something).
Also, it helps if you play around with the diatonic chords enogh that you get "bored" with them and start exploring other options.
I guess I'm recommending you learn by doing, not by arbitrary memorization of names. The names won't help you, the finger positions on the keyboard will.
Note: I play and write for both piano and guitar and I learn shapes and finger positions and patterns for both instruments. I don't worry at all about names. Once you have the shapes and finger positions down, the names are dead easy. It doesn't work in the other direction, though. Also I have a relationship in my head between shapes on the guitar and shapes on the piano. So I know what frets are which piano keys. That's much faster and more intuitive than knowing that a fret is a C and then remembering which key is the same C. Again, the names will come easily once you have the direct shape and position relationships down.
Comment: I think I pretty much agree with everything here, but I do think that it is important to know the names of the chords you are playing, for the most part. In particular I am thinking of chords, like **m6** and **m7♭5** chords that have the same shapes, but different root notes in those same shapes, and different functions. You ought to know which you are playing when you play one of these shapes, I think.
Comment: @DavidBowling I'm not sure how strong it is to say one "ought to know" something. It certainly agree it is *helpful* to know these things, but when playing and when composing, I find that I have to forget about music theory and that working with shapes and sounds produces pleasing results, and I've written several chord progressions that I love (and others seem to at least like) where I would have to spend a long time to fully analyze them. It's knowledge that is helpful to have, I just don't think anyone should go through too much trouble to have it.
Comment: Absolutely. 'Tis thus when people try to learn music theory (or most theory for that matter) without playing practically as well. Bones need flesh! +1.
Comment: Whilst agreeing with most of your answer, having worked with players who couldn't communicate what chord was in question, (even though they could play it), or had to be shown, one note at a time what a particular chord was, it's a great time (and sanity) saver. A hammer is a hammer, a chisel is a chisel. Isn't it easier to ask for the one you want by name? If you know it...
Comment: @Tim I think my interpretation of the question and my intention in my answer might be different from how some people are reading them. I agree it's very helpful to know the names of the chords. What I was trying to capture in my answer is that it doesn't make sense to me to make a special effort to learn the chord names in isolation, but rather to learn to play chords and also know the notes of the chords and know how to construct and deconstruct names from the notes. I'm recommending against specifically memorizing chord names and instead suggesting learning the names more organically.
Comment: @Tim I think the last paragraph in my answer explains better. Learn to play and understand the chords before/as part of learning the names. Once you understand the chords and shapes, learning the names is easy. Whereas memorizing the names in isolation (which is my interpretation of the question) does not help with understanding or playing the chords and will be harder than learning to play and understand them first and then connect them with the names.
Answer: I think Todd's answer is right on: that memorizing these chords away from the music is only helpful to a point, and the real skill is your active creation of these chords on a musical instrument (in your case, piano and guitar).
But I want to add one thing: I do think it's helpful to mix the two. In other words, I've found it tremendously helpful for myself (and for my students) to be able, at any time, to tell me—without hesitation—what chord they're playing. Too many musicians can play music without really knowing what they're playing, to which I say they can hardly be called musicians at all.
So you may want to spend some time, as you practice, simply saying the names of the chords out loud. As you progress, you can say the inversions to yourself. If you're interested, maybe the Roman numeral in whatever key you're in, or the scale-degree name (this is "supertonic," this is "dominant"). And so on. In short, you can never know too much about what you're playing.
The added bonus is, over time, a connection between pitch names, the tactile feel of the chords, and the sounds themselves. This is one of the many ways that relative pitch is built over time. (This is what builds absolute pitch, too, but really that's for the malleable brains of youngsters.)
Doing this also makes it more clear what chords you think work well together, what chords progress into what others, what chords cannot move to what, etc.
Comment: You expect students to be aware of each name of each chord they're playing. Whilst it's laudable, I wonder if that's what actually happens in a real live playing situation.Many's the time I've busked songs I've heard, in keys that I've not played them in, and would have been hard pushed to call out chord names.I think auto-pilot takes over, and there's other things that are more important to consider.But, for students, at a different level, maybe it's different.Same with note names.I'm sure if I stopped a great player and asked what note he'd just played, the answer would be 'the right one...'
Comment: @Tim it's true. Although I think it's safe to say my approach to music is in general quite theoretical, I sometimes find myself playing stuff I have trouble naming, in particular when playing with keyboarders who like ridiculous keys. "What do you mean, I should play a B♭ here? No way! Hang on, what notes do I do before that... C♯, B, next I could perhaps play A♯ – oh \*groan\* I see..."
Comment: I also think "you can never know too much about what you're playing". also knowing the chord names is useful when going between instruments.
Answer: I have found it extremely helpful to know the function of chords in the keys they belong to. For example, a C Major chord is I in C major, V in F major, IV in G Major, III in A minor, and so forth. This comes in very handy when I am playing around, either figuring out a song I am learning by ear or trying out a new harmonization to something or writing a new piece. Knowing the functions of the chords is kind of like having a thesaurus handy. It allows you to have an idea of what chords can be tried out where without having to resort to the same exact vocabulary every time. Instead of thinking always about what chords belong to the key, I think more about all that I can do with an individual chord.
Answer:
Should I remember the diatonic chord names of each scale?

Why not? It's a fairly straightforward exercise, not difficult - and will help you in situations like recognising the key of a song from a chord sheet and quickly transcribing songs yourself. It will be even more useful if you remember where (different voicings of) each chord are on the guitar neck - that should make it easy to relate the piano, the guitar, and the sheet music/chords/tabs that you are playing.
In fact, if I had to choose, I would say that learning where the chords/scales are on the guitar neck would be a more useful exercise than memorising the chords in each key. Partly, this is because many songs these days don't actually stick to the chords diatonic to the key the song is in - though it might help you in analysing harmonies if you can easily spot the difference between diatonic chords and chords from outside the key.
Answer: Why not? it's easy when you think in terms of the cycle of fifths. See the zigzag diagram below. Each diagonal step advances one fifth. It shows how the diatonic scale is built up from seven notes separated by consecutive intervals of a fifth. All the notes for a particular key signature are found together, three on one line (starting with the root note of the major key) and four on the other line.
Thus C major is CDE FGAB and Eb major is Eb F G Ab Bb C D.

Gb  Ab  Bb   C   D   E   F#  G#  A#
  Db  Eb   F   G   A   B   C#  D#

Taking the key of C major as an example, the major chords are C major, one fifth forward = G major and one fifth back = F major.
This is followed by the three chords of the relative minor: A minor, one fifth forward = E minor and one fifth back = D minor.
Following the three minor chords we have B diminished.
Once I understood the cycle of fifths, I never had any trouble remembering which chord names went with which scale. As others have said, it is more important to be able to play them than name them, but I found it helped with that too.
Answer: For yourself, playing by yourself, it's not much of an issue. However, when you play with others, using a common language - music - is quite useful. So, communicating with others, naming particular chords - which are family related, as we know - makes life so much easier.
And here, we're only talking about the 3 majors, 3 minors and 1 diminished for each of the keys. Not a big deal, when we should know the circle of fifths - which is actually being half way there anyhow.
Yes, there are many guitarists who don't even know the names of notes played, and a lot of the time it doesn't matter a jot. One can use fret/string numbers and another will understand. It won't mean much to a sax or piano player, though.
Being conversant with chord families and their names isn't trivial. It's part of being a musician rather than a layman. Knowing that C>Em is the same as Ab>Cm is the same as G>Bm is important, especially when transposing. Maybe just knowing where to go is good, but what's wrong with having that extra bit of info?
Answer: IT's not worth learning them by rote.  It's not worth learning much at all from a 'theory-out' viewpoint.  Better to let your experience of playing and studying lots of music reveal patterns.  A song in Ab will doubtless include lots of Ab, Db and Eb7 chords.  And Fm, Bbm7, Gb (yes, that one keeps cropping up, despite being a bit 'off the grid'), Dbm...    Don't use theory to suggest what chords MAY be played.  Let it describe the ones you (and other, more experienced players and composers) HAVE played.
Answer: One way to remember the chords that correspond to a given key is that certain scale degrees always correspond to a major or minor chord in a diatonic scale.
For example:
In the key of C Major the diatonic scale is: C - D - E - F - G - A - B.
We can assign roman numerals to the scale degrees as follows: I - ii - iii - IV - V - vi - vii
Here's the formula:

The chords that correspond to the first, fourth, and fifth chords are always major.
The chords that correspond to the second, third and sixth scale degrees are always minor.
The chord that corresponds to the seventh scale degree is always diminished.

Following this formula with the C scale, we get: C - Dm - Em - F -G - Am - Bdim
Hope this is helpful!


query on oracle database using kafka messaging system

Question: I have an oracle database which is a data warehouse and I'm using a kafka messaging system to exchange messages in my system. In my disaster recovery solution I'm going to query on an oracle database using kafka connect and then copy the queried messages to a H2 database. Do you guys have a solution to query on an oracle database using kafka connect? I'm not going to use any third party software solution like "confluent" and I prefer not to use kafka APIs!
Please HELPPP!!
Comment: apache-flume? https://www.toadworld.com/platforms/oracle/w/wiki/11524.streaming-oracle-database-table-data-to-apache-kafka
Comment: Can I perform a simple select query using flume??
Comment: Apache Flume was Ideal for me and I used it in order to bulk insert from a database to another. Thanks golezTrol
Answer: If you are already using Kafka then Kafka connect would be ideal for your situation. You can read from an Oracle DB and make it available on the Kafka topic using  Kafka connect source and then configure a Kafka Connect Sink  to source it to your H2 database.
Comment: Thanks dude but I need to tell you that I did the job using flume without any need to kafka-connect. Because I just wanted to use something endorsed by apache and as you know kafka-connect is  licensed by confluent which I assume is a third party. It was amazing. I will give you accurate details to you in an answer in the near future!


How to evaluate the integral: $\int\ln x\;\sin^{-1} x\, \operatorname d\!x$?

Question: Can the following integral integrated by parts?
$$\int\ln x\;\sin^{-1} x\, \operatorname d\!x$$
Comment: @swapnanilsaha There should be an empty check mark next to answers to your questions. Clicking that will accept someones answer. Note that you can only accept one answer.
Comment: @Holdsworth88 : Thankyou very much.
Comment: "Can the following integral integrated by parts?" - repeated use of it, yes. To start you out: $u=\arcsin\,x$, $\mathrm dv=\log\,x\mathrm dx$.
Comment: Can you please explain how to do that?
Answer: Integration by parts formula
$$\int u(x)\underset{dv}{\underbrace{v^{\prime }(x)dx}}=u(x)v(x)-\int v(x)
\underset{du}{\underbrace{u^{\prime }(x)dx}}.$$
If we apply the LIATE rule to
$$\int \ln x\arcsin x\,dx,$$
we should choose
$$u =\ln x,\quad dv=\arcsin x\,dx.$$
Normally there is a choice of the terms $u,v'$ of the integrand $uv'$ that makes integration much easier. However in the present case the other possible choice $u=\arcsin x,v'=\ln x$ leads to integrals of  similar difficulties.
$$\begin{eqnarray*}
I &=&\int \ln x\arcsin x\,dx, \qquad \text{(}v =\int \arcsin x\,dx\quad \text{see evaluation below)} \\
 &=&\left( \ln x\right) \left( x\arcsin x+\sqrt{1-x^{2}}\right) -\int \frac{
1}{x}\left( x\arcsin x+\sqrt{1-x^{2}}\right) \,dx \\
&=&\left( \ln x\right) \left( x\arcsin x+\sqrt{1-x^{2}}\right) -\int \arcsin
x\,dx-\int \frac{1}{x}\sqrt{1-x^{2}}\,dx \\
&&\text{(see evaluation of the last integral below)} \\
 &=&\left( \ln x\right) \left( x\arcsin x+\sqrt{1-x^{2}}\right)  -\left( \sqrt{1-x^{2}}+x\arcsin x\right)  \\
&&-\sqrt{1-x^{2}}-\frac{1}{2}\ln \frac{\sqrt{1-x^{2}}-1}{\sqrt{1-x^{2}}+1}+C.
\\
&=&\left( -1+\ln x\right) \left( x\arcsin x+\sqrt{1-x^{2}}\right)
-\sqrt{
1-x^{2}} -\frac{1}{2}\ln \frac{\sqrt{1-x^{2}}-1}{\sqrt{1-x^{2}}+1}+C.
\end{eqnarray*}$$

Evaluation of $\int \arcsin x\,dx$ by substitution $$\begin{eqnarray*}
\int \arcsin x\,dx &=&\int u\cos u\,du,\quad u=\arcsin x \\
&=&\cos u+u\sin u \\
&=&\sqrt{1-x^{2}}+x\arcsin x+C.
\end{eqnarray*}$$
Evaluation of $\int \frac{1}{x}\sqrt{1-x^{2}}\,dx$ by substitution and
partial fractions
$$\begin{eqnarray*}
\int \frac{1}{x}\sqrt{1-x^{2}}\,dx &=&-\int \frac{u^{2}}{1-u^{2}}\,du,\qquad
u=\sqrt{1-x^{2}} \\
&=&u+\frac{1}{2}\ln \left( u-1\right) -\frac{1}{2}\ln \left( u+1\right)  \\
&=&u+\frac{1}{2}\ln \frac{u-1}{u+1} \\
&=&\sqrt{1-x^{2}}+\frac{1}{2}\ln \frac{\sqrt{1-x^{2}}-1}{\sqrt{1-x^{2}}+1}+C.
\end{eqnarray*}$$
Comment: Alternatively, $$\frac{\sqrt{1-x^2}}{x}=\frac{1}{x\sqrt{1-x^2}}-\frac{x}{\sqrt{1-x^2}}$$
Comment: @J.M. Thanks, with this split the integral becomes $$\int \frac{1}{x}\sqrt{1-x^{2}}\,dx=\sqrt{1-x^{2}}-\text{arctanh}\frac{1}{
\sqrt{1-x^{2}}}+C.$$
Answer: Following J.M.'s hint, you may want to prove, again integrating by parts, that
$$\int\log x\,dx=x\log x-x+C\,\,,\,\,C=\,\,\text{a constant}$$and perhaps also to note that
$$\int \frac{x}{\sqrt{1-x^2}}dx=-\frac{1}{2}\int\frac{-2x}{\sqrt{1-x^2}}dx$$
Answer: Let  I =  ∫ ln x * sin−1 x dx,
= x(ln x - 1) * arcsin x - ∫ x(ln x - 1) * 1/√(1 – x^2) dx
= x(ln x - 1) * arcsin x - ∫(ln x - 1) * x / √(1 – x^2) dx
= x(ln x - 1) * arcsin x + (ln x - 1) * √(1 – x^2) – ∫ (1/x) * √(1 – x^2) dx
Call this last integral  I1.
Put u = x^2;  then du/dx = 2x
∴ I1 = ∫ (1/(2u)) * √(1 – u) * du/dx dx
Put  u = 1 – v^2, v ≥ 0;  so du/dv = -2v
∴ I1 = ½ ∫ 1/(1 – v^2) * (-2v^2) dv
v^2 / (v^2 – 1) = (v^2 – 1 + 1) / (v^2 – 1) = 1 + 1 / (v^2 – 1)
= 1 + ½ (1/(v – 1)  - 1/(v + 1))
So  I1  = v + ½ ln (A * (v – 1) / (v + 1)),  where  A is the arbitrary constant
<code>= √(1 – u) + ½ ln (A * (√(1 – u) – 1) / (√(1 – u) + 1)),

= √(1 – x^2) + ½ ln (A * (√(1 – x^2) – 1) / (√(1 – x^2) + 1)),
</code>
Add this to the other parts, and you are done.
I at first thought it could not be done in elementary functions; but there we are!)


Calculate the dimensions of a rotated rectangle inside a bounding box

Question:
I'm trying to figure out if it's possible to calculate the width & height of the gray rectangle if I only know the width & height of the dotted red rectangle and the angle of the rotation.
I've tried substituting values for the width and height and using $x \cos(\alpha) + y \sin(\alpha)$ and attempting to figure out a scaling factor, but I'm not really getting anywhere.
Comment: Could you draw a figure where you indicate the name of the variables (say $h, w,x,y,\alpha$)? That way I can write the appropriate formula. Or at least indicate which one is which.
Comment: Thanks @Andrei, updated as requested.
Answer: $$x\cos\alpha+y\sin\alpha=w\\x\sin\alpha+y\cos\alpha=h$$
Multiply first equation by $\cos\alpha$, the second by $\sin\alpha$ and subtract:
$$x(\cos^2\alpha-\sin^2\alpha)=w\cos\alpha-h\sin\alpha$$or $$x=\frac{w\cos\alpha-h\sin\alpha}{\cos^2\alpha-\sin^2\alpha}$$
Similarly, multiply the first equation by $\sin\alpha$, the second by $\cos\alpha$ and subtract:
$$y(\sin^2\alpha-\cos^2\alpha)=w\sin\alpha-h\cos\alpha\\y=\frac{w\sin\alpha-h\cos\alpha}{\sin^2\alpha-\cos^2\alpha}$$
Notice that the denominator might be $0$ for $\alpha=45^\circ$. Then you must have the numerator equal to $0$ as well, or $w=h$, so you have a square inside a square $x=y$ and $$2x\frac{\sqrt 2}2=w$$ or $$x=w\frac{\sqrt 2}2$$
Comment: Thank you so much @Andrei, appreciate your fast response.
Comment: When rotated 45 degrees there are no unique result and it also not necessarily a square.


Simson's Rule but Intervals Aren't the Same

Question: I'm currently working on some homework, and ran into a question that has stumped me. We're working on Simpson's rule, which is easy enough, but then I got to a problem where the intervals aren't the same.
\begin{array}{|c|c|c|c|}
\hline
 Time(seconds)& 1.2& 1.7& 2.3& 3.0& 3.9& 4.8& 5.9& 7.1& 8.5\\ \hline
 Velocity(mph)& 30& 40& 50& 60& 70& 80& 90& 100& 110\\ \hline
\end{array}
It also gives me the information $60mph = 88 ft/sec$
I'm supposed to be using Simpson's rule to estimate the distance traveled by the car from time $t = 1.2 seconds$ and $t = 8.5 seconds$, but the time intervals aren't the same. What do I need to do to solve this?
Answer: Use integration by parts
$$s=\int_{t_1}^{t_2}vdt=\!\!\!\!\!\left.\phantom{\frac{1}{2}}vt\,\right|_{t_1}^{t_2}-\int_{v_1}^{v_2}tdv.$$
Since your $v$ is equally spaced, you can do Simpson's integral. Simpson's rule is more accurate for equally spaced intervals because the third-order Taylor term is canceled as "free lunch".
Or one can use the formula
$$\int_a^bf(t)dg(t)\approx\begin{bmatrix}f(a),\;f(\frac{a+b}{2}),\;f(b)\end{bmatrix}\left(\begin{array}{rrr}
\displaystyle-\frac{1}{2} & \displaystyle\frac{2}{3} & \displaystyle-\frac{1}{6}\\\displaystyle-\frac{2}{3} & 0\, & \displaystyle\frac{2}{3}\\
\displaystyle\frac{1}{6} & \displaystyle-\frac{2}{3} & \displaystyle\frac{1}{2}
\end{array}\right)\begin{bmatrix}g(a)\\g(\frac{a+b}{2})\\g(b)\end{bmatrix}.$$
This formula is invariant under integration by parts, i.e., the right-hand side exactly reproduces
$$\int_a^b f(t)dg(t)+\int_a^b g(t)df(t)=f(b)g(b)-f(a)g(a),$$
and reduces to Simpson's rule if $\,g(t)=t\,$ is a linear function. I derived this myself but would appreciate anyone who can find me a reference.
Comment: Huh, so formatting DOES work. Anyway, using your method i get
$$\frac{73.33-44}{6}\left(1.2+4(1.7)+2.3\right)=50.3498$$
$$\frac{102.66-73.33}{6}\left(2.3+4(3)+3.9\right)=88.9677$$
$$\frac{132-102.66}{6}\left(3.9+4(4.8)+5.9\right)=141.81$$
$$\frac{161.33-132}{6}\left(5.9+4(7.1)+8.5\right)=209.221$$
and the answer is 490.348 (after doing conversions, that's what my numbers are a bit off)

The only problem I have is that your midpoint comment isn't completelyright, 1.7 is not between 1.2 and 2.3, same with 7.1 being between 5.9 and 8.5. I don't know if this will effect the problem tho.
Comment: Both methods should get you $564.67\,\mbox{mph}\cdot\mbox{sec}=828.18\,\mbox{ft}$. You have done the $\int tdv$ integral and the integration by parts would get you $\int vdt$.


regex, problem with backreference in pattern with preg_match_all

Question: i wonder what is the problem with the backreference here:
preg_match_all('/__\((\'|")([^\1]+)\1/', "__('match this') . 'not this'", $matches);

it is expected to match the string between __('') but actually it returns:
match this') . 'not this

any ideas?
Comment: Do back refs really work in char classes?
Comment: sorry, there is a missing \
i have corrected the battern
Comment: On to the next solution.
Answer: You can't use a backreference inside a character class because a character class matches exactly one character, and a backreference can potentially match any number of characters, or none.
What you're trying to do requires a negative lookahead, not a negated character class:
preg_match_all('/__\(([\'"])(?:(?!\1).)+\1\)/',
    "__('match this') . 'not this'", $matches);

I also changed your alternation - \'|" - to a character class - [\'"] - because it's much more efficient, and I escaped the outer parentheses to make them match literal parentheses.

EDIT: I guess I need to expand that "more efficient" remark.  I took the example Friedl used to demonstrate this point and tested it in RegexBuddy.
Applied to target text abababdedfg,
^[a-g]+$ reports success after three steps, while
^(?:a|b|c|d|e|f|g)+$ takes 55 steps.
And that's for a successful match. When I try it on abababdedfz,
^[a-g]+$ reports failure after 21 steps;
^(?:a|b|c|d|e|f|g)+$ takes 99 steps.
In this particular case the impact on performance is so trivial it's not even worth mentioning.  I'm just saying whenever you find yourself choosing between a character class and an alternation that both match the same things, you should almost always go with the character class.  Just a rule of thumb.
Comment: "Much more", really? How much more?
Comment: Yes, alternations are very slow, a plague that should be avoided. However, assertions are even slower.
Comment: @sln: That depends on how well the assertion is written and how it's used (just like regexes themselves).  Anyway, the flexibility they provide is well worth the performance hit in most cases.  But there's no excuse for using something like `(a|b|c)` when you can use `[abc]` instead.
Answer: I'm suprised it didn't give you an unbalance parenthesis error message.
 /
   __
   (
       (\'|")
       ([^\1]+)
       \1
 /

This [^\1] will not take the contents of capture buffer 1 and put it into a character
class. It is the same as all characters that are NOT '1'.
Try this:
/__\(('|").*?\1\).*/
You can add an inner capturing parenthesis to just capture whats between quotes:
/__\(('|")(.*?)\1\).*/
Edit: If no inner delimeter is allowed, use Qtax regex.
Since, ('|").*?\1 even though non-greedy, will still match all up to the trailing anchor.  In this case __('all'this'will"match'), and its better to use ('[^']*'|"[^"]*)
as
Comment: Technically I think `\1` will be interpreted in a character class as the character with an octal value of 1, but the point is essentially the same nonetheless (i.e. `[^\1]` is not doing what the OP thinks it is). [Example](http://ideone.com/0vQHN).
Answer: You can use something like:
/__\(("[^"]+"|'[^']+')\)/
Comment: This would be the preferred method if no inner delimeter is allowed.
Comment: Just to note that the drawback with this method is that its impossible to capture the inner data without the delimeter included.
Comment: @sln: Sure you can capture it; just use a different group for each subpattern: `~__\(("(?[^"']+)"|'(?[^"']+)')\)~`
Comment: @sln @Alan, or you can use `(?|...)` if your flavor supports it. Eg: `/__\((?|"([^"]+)"|'([^']+)')\)/`. Alan, I wouldn't use `[^"']`, the whole point of different quoting chars is that you can use one inside the other. ;)
Comment: @Alan - I should have said, theres no clean way for an inner capture without post processing logic of the independent capture buffers to determine which one captured.
Comment: @Qtax - Branch reset (if available) is an alternative, however, there are idiosyncracy's across engine's which lead me to be wary of them. Originally saying its impossible, to me though means requiring some platform dependent post processing. Ie: possible caveats.
Answer: Make your regex ungreedy:
preg_match_all('/__((\'|")([^\1]+)\1/U', "__('match this') . 'not this'", $matches)

Comment: Don't use back refs in char classes.
Comment: And what would you do if a string to match contains escaped quote? Like this: __('match that\'s') . 'not this' :|
Comment: `[^\1]` matches any char but a char with octal value `1`


What goes the Pappus' theorem says

Question: I found the following statement:
Let $A, C$ and $E$ be three distinct points on the line $l_1$ and $B,D,F$ three distinct points on the line $l_2$. Let us assume that $AB\cap DE=L$, $CD\cap FA=M$, and $EF\cap BC=N$. Then $L,M,N$ are collinear.
In the picture of the paper I'm reading, it looks like $C$ lies between $A$ and $E$ and $D$ lies between $B$ and $F$. Do we need this assumption or does the theorem work no matter in what order the points are on the line? And how do I prove the case that some of the lines $AB$, $CD$ and $EF$ are parallel?
Answer: The order matters, because the lines (e.g. $AB$, $DE$, $EF$, $BC$, etc.) with one point on $l_1$ and one on $l_2$ could be parallel, and so $L$, $M$, or $N$ might not exist.
For example, if the points appeared in the order $A$, $E$, $C$ on $l_1$ and $B$, $D$, $F$ on $l_2$, then we could easily have $$AB \cap DE = \varnothing$$

What goes the Pappus' theorem says


PostgreSQL Table Comparison

Question: I have a table:
CREATE TABLE my_schema.my_data
(
    id character varying COLLATE pg_catalog."default" NOT NULL,
    name character varying COLLATE pg_catalog."default" NOT NULL,
    length numeric(6,4),
    width numeric(6,4),
    rp numeric(4,2),
    CONSTRAINT id_pkey PRIMARY KEY (id)
);

and a temp table:
CREATE TEMPORARY TABLE new_data (LIKE my_schema.my_data);

The temporary table is then being filled with a more recent version of the data set that exists in the my_data table.
I am attempting to identify the records in the temporary table that have the same primary key as an existing record in the my_data table but have at least one other value that is different.
My current method is to run a query similar to this example:
SELECT temp.id
FROM (SELECT * FROM my_schema.my_data WHERE my_data.id IN ('X2025','X8716','X4091','X2443','X8922','X5929','X3016','X3036','X4829','X9578')) AS orig
RIGHT JOIN (SELECT * FROM pg_temp.new_data WHERE new_data.id IN ('X2025','X8716','X4091','X2443','X8922','X5929','X3016','X3036','X4829','X9578')) AS temp
ON (orig.id = temp.id OR (orig.id IS NULL AND temp.id IS NULL))
AND (orig.name = temp.name OR (orig.name IS NULL AND temp.name IS NULL))
AND (orig.length = temp.length OR (orig.length IS NULL and temp.length IS NULL))
AND (orig.width = temp.width OR (orig.width IS NULL and temp.width IS NULL))
AND (orig.rp = temp.rp OR (orig.rp IS NULL and temp.rp IS NULL))
WHERE orig.id IS NULL;

This seems pretty inefficient and I am not seeing very good response times on larger tables were there are more columns and I am iterating through batches of about 10,000 records.
Any suggestions for identifying the records that are different in a more efficient manner?
UPDATE:
I have a dataset that is pulled fresh on a regular basis.  Unfortunately, I get the full data set each time instead of only new or updated records.  (I am working on fixing this process in the future.)  For the time being I just want to update my table to match the latest data pull each day.  I worked through a process to handle these comparisons and updates but it was super slow.  My data base table contains import_date and modified_date columns that are currently being filled using triggers.  Via the triggers every INSERT statement uses the current_date as both the import_date and modified_date for those records.  Additionally, the modified_date is set to current_date via a trigger BEFORE UPDATE.  As such, I only want to update records that actually experienced a data change in with the most recent data pull.  Otherwise, the modified_date column becomes pretty useless, as I won't be able to determine when the values for that record most recently changed.
Current Table: ORIG
(actual table contains about 1 million records)
| import_date | modified_date | id | name | length | width |  rp  |
|  2018-08-17 |  2018-08-17   | 87 | Blue | 12.0200| 8.0503| 1.82 |
|  2018-08-17 |  2018-08-17   | 88 | Red  | 11.0870| 2.0923| 1.72 |
|  2018-08-17 |  2018-08-17   | 89 | Pink | 15.0870| 7.9963| 0.95 |
Temporary Table: TEMP
(Also contains about 1 million records.  Will contain all of the primary keys (id column) that exist in the current table but may also contain new primary keys.)
| import_date | modified_date | id | name | length | width |  rp  |
|     NULL    |     NULL      | 87 | Teal | 12.0200| 8.0503| 1.82 |
|     NULL    |     NULL      | 88 | Red  | 11.0870| 2.0923| 1.72 |
|     NULL    |     NULL      | 89 | Pink | 15.0870| 7.9963| 0.95 |
Using the example data above, I would expect only the first record, id 87, to be updated.  After which my table would look like:
| import_date | modified_date | id | name | length | width |  rp  |
|  2018-08-17 |  2018-09-12   | 87 | Teal | 12.0200| 8.0503| 1.82 |
|  2018-08-17 |  2018-08-17   | 88 | Red  | 11.0870| 2.0923| 1.72 |
|  2018-08-17 |  2018-08-17   | 89 | Pink | 15.0870| 7.9963| 0.95 |
WHAT WORKED FOR ME:
I updated my modified_date trigger function to identify when a new modified date is needed:
CREATE FUNCTION my_schema.update_mod_date()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
DECLARE
BEGIN
    IF tg_op = 'INSERT' THEN
        NEW.modified_date := current_date;
    ELSIF tg_op = 'UPDATE' THEN
        IF NEW.name IS DISTINCT FROM OLD.name
        OR NEW.length IS DISTINCT FROM OLD.length
        OR NEW.width IS DISTINCT FROM OLD.width
        OR NEW.rp IS DISTINCT FROM OLD.rp THEN
            NEW.modified_date := current_date;
        ELSE
            NEW.modified_date := OLD.modified_date;
        END IF;
    END IF;
    RETURN NEW;
END;
$BODY$;

Then I was able to use the original solution proposed by @EvanCarroll:
BEGIN;
INSERT INTO my_schema.my_data (SELECT * FROM pg_temp.new_data)
ON CONFLICT (id) DO UPDATE SET modified_date=NULL, id=EXCLUDED.id,
name=EXCLUDED.name, length=EXCLUDED.length, width=EXCLUDED.width,
rp=EXCLUDED.rp;
COMMIT;

This ensured that the modified_date only gets changed if one of the other values in the row changed.
Comment: Is the goal to update the original table?
Comment: @EvanCarroll Yes, the end goal is to update the original table using the new dataset.
Answer: How about joining on the PK, but then only selecting records where the rest of the record is somehow difference, like so:
SELECT
    new_data.*
FROM
    my_data
INNER JOIN
    new_data
    ON  (my_data.id = new_data.id) -- Same PK
    AND (ROW(my_data.*) IS DISTINCT FROM ROW(new_data.*)) -- Any difference in other fields

This will return records from the new_data table with id that matches records in my_data, but where any other field(s) do not match.
Documentation: https://www.postgresql.org/docs/current/static/functions-comparisons.html#ROW-WISE-COMPARISON
Comment: I tested this with a dataset of 10,000 records and saw a speed up of about 10% over my previous method.  While this is progress, I am hoping for a more significant improvement in performance.
Comment: `(ROW(my_data.*) IS DISTINCT FROM ROW(new_data.*))` can be simplified to `my_data IS DISTINCT FROM new_data`
Comment: @a_horse_with_no_name That worked but performed a little slower.  When I tested it came out about 6% faster than my method compared to the 10% speedup of the method proposed by Nicarus
Comment: @NathanScheiderer: interesting. I wouldn't have expected that it makes a performance difference
Comment: @a_horse_with_no_name - They are executed a little differently - the explain plan can visualize it for you. But basically, ROW(tbl.*) unpacks and compares each field in the respective tables versus comparing the tuples.
Answer:
@EvanCarroll Yes, the end goal is to update the original table using the new dataset. – Nathan Scheiderer 41 mins ago

Then you don't want to do this. You want to instead use INSERT ... ON CONFLICT DO UPDATE. That's how you upsert in PostgreSQL.
Update
If you have a row like a modified_time that you only want updated when the row is updated, have it handled with a trigger. Like this. Then you would just write the below like this,
INSERT INTO foo
SELECT *
FROM bar
WHERE NOT EXISTS (
  SELECT 1
  FROM foo
  WHERE foo.x = bar.x
    AND NOT foo.whatever = bar.whatever
);

Now it won't accept updates on the row unless whatever is different for each x. Ideally though you wouldn't do that. If the rows must be unique by whatever I would add that to the index.
Comment: Awesome! This addresses a wider scope in my process than my initial question, potentially saving me a few steps, but also introducing some more complexity.  My original table includes import_date and modified_date columns that are 'auto-filled' using triggers functions before insert or update.  So I would want to exclude those columns in any comparisons that are done between the two tables.  Would this be feasible with the 'ON CONFLICT DO UPDATE' approach?
Comment: I worded that incorrectly.  I am not wanting to exclude import_date and modified_date from the comparison.  Rather I don't won't those columns to be updated by my trigger functions unnecessarily.  If I understand how this solution works it will run an update on each record where the primary key from the new data set already exists in the original table.  This means some of my records would have a new modified date even though the data didn't actually change.
Comment: I was able to use INSERT...ON CONFLICT DO UPDATE with a modified version of my trigger functions and drastically improved the performance.  I will post a more detailed explanation above.
Comment: There is an election on the SF and you could be a well-known candidate.

PostgreSQL Table Comparison


Expectation of the area of the triangle

Question: A point X is randomly chosen from the interval (0, a) of the x-axis and Y respectively from the
interval (0, b) of the y-axis. Suppose that X and Y are independent. Determine the expectation
of the area of the triangle OXY (O = origin).
My probability density function is ab/2? I have previously used Lebesgue integration to determine the expected value. However I do not understand how to use it when I have two unknown variables.
Answer: The area of a triangle with the coordinates $(x_1,y_1), (x_2,y_2), (x_3,y_3)$ is
$$
S = \frac{1}{2} \left | x_1y_2 + x_2y_3 + x_3y_1 - y_1 x_2 - y_2x_3 - y_3x_1 \right |
$$
When you sample $X$ and $Y$, you will have a triangle with points $(0,0), (X,0), (0,Y)$, so you are interested in the random variable
$$
S = \frac{1}{2} |XY| = \frac{1}{2}XY
$$
since we are guaranteed that $X,Y$ are positive. Then by the independence, we simply have
$$
\mathbb{E}[S] = \frac{1}{2} \mathbb{E}[XY]=\frac{1}{2} \mathbb{E}[X] \mathbb{E}[Y] = \frac{1}{2} \frac{a}{2} \frac{b}{2} = \frac{ab}{8}.
$$
Comment: I don't see the point to refer to this complicated first formula for $S$ : it is plainly the half area of a rectangle with sides $X$ and $Y$...
Comment: Yes, you're right.. on the bright side they have an approach to solving the problem for more general triangles
Answer: Define a random variable $A:(0,a)\times (0,b)\to \Bbb R$ by $$A(x,y)=\frac{xy}{2}.$$By definition, the expected value of $A$ is $$\Bbb E[A]=\int_0^a\int_0^b A(x,y)\,{\rm d}\Bbb P(x,y),$$where $\Bbb P$ is the Lebesgue probability measure on $(0,a)\times (0,b)$. But ${\rm d}\Bbb P = (ab)^{-1} {\rm d}x\,{\rm d}y$. Hence $$\Bbb E[A] = \frac{1}{ab}\int_0^a\int_0^b\frac{xy}{2}{\rm d}x\,{\rm d}y =\frac{1}{2ab}\frac{a^2}{2}\frac{b^2}{2} = \frac{ab}{8}.$$

Expectation of the area of the triangle


Error with cursor and SQLite in android

Question: I have an error with a cursor when I'm reading a database :
04-07 18:11:25.672: ERROR/AndroidRuntime(5801): android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed. # Open Cursors=666 (# cursors opened by this proc=666)

It happens on the line
cursor.getCount()

The entire file is 8kb, it has 32 lines, but IDs go from 737 to 768, is the problem from there?
(I have noticed that if ID is below 600, there are no problems)
Comment: More code would be helpful... the error message seems to indicate you are opening a lot of cursors at once.
Answer: (Question answered by the OP in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:

I solved the problem. My code was :

public News getNewsWithID(int id){
        Cursor c = bdd.query(TABLE_NEWS, new String[] {COL_ID, COL_ASSO, COL_DATE, COL_HEURE, COL_TYPE, COL_TITRE, COL_CONTENU, COL_SERVEURID}, COL_ID +"='"+ id +"'" , null, null, null, null);
        return cursorToNews(c);
    }

I changed to :

public News getNewsWithID(int id){
        Cursor c = bdd.query(TABLE_NEWS, new String[] {COL_ID, COL_ASSO, COL_DATE, COL_HEURE, COL_TYPE, COL_TITRE, COL_CONTENU, COL_SERVEURID}, COL_ID +"='"+ id +"'" , null, null, null, null);
        News temp = cursorToNews(c);
        c.close();
        return temp;
    }

I thought that the cursor was closed on onDestroy().
Answer: You should really be closing the cursor in a finally block, to ensure that it's closed even if an exception happens.
public News getNewsWithID(int id){
    Cursor c = bdd.query(TABLE_NEWS, new String[] {COL_ID, COL_ASSO, COL_DATE, COL_HEURE, COL_TYPE, COL_TITRE, COL_CONTENU, COL_SERVEURID}, COL_ID +"='"+ id +"'" , null, null, null, null);
    try {
        return cursorToNews(c);
    } finally {
        c.close();
    }
}

Error with cursor and SQLite in android


Combine views sort criteria in exposed form

Question: Drupal 7, views 3.6.
I have a view with 2 sort criteria: date and category. The sort is exposed in a form block.
Currently the user only has the choice to select 1 sort criteria, ie: sort by date or sort by category.
Is there a way to have the combination of these 2 criteria exposed, ie: sort by date asc, and by category desc ?
Thanks for your input,
Jerome
Answer: Use Better Exposed Filters module:

The Better Exposed Filters module replaces the Views' default single-
  or multi-select boxes with radio buttons or checkboxes, respectively.
  Description fields and Select All/None links can be added to exposed
  filters to make for a better user experience.
Answer: Use Grouped filters for combining 2 exposed criteria.
In views exposed form :
Select Filter Type to Grouped filters and then it will display Grouped filter form then u can select which filter u required between 2 exposed filters.


Compute $\mathbb{P}(1<X^2+Y^2<2)$ when $(X,Y)$ is i.i.d. standard normal

Question:
Assume that  $(X,Y)$ is i.i.d. standard normal. Compute $\mathbb{P}(1<X^2+Y^2<2)$.

So I've decided to use polar coordinates to solve and I've gotten to this point:
$$\iint_{1\lt X^2+Y^2\lt2} e^{\frac{-(x^2+y^2)}{2}}dxdy=\iint_{1\lt r^2\lt2}e^{\frac{-r^2}{2}}drd\theta$$
Where  $1\lt r\lt\sqrt2$ and $0\lt \theta \lt 2\pi$.
How do I go about integrating dr? I know I need to use the $\Phi$ function but I'm not so sure how to go about doing that. Any help would be muchappreciated.
Comment: Alternative: $X^2\overset d= Y^2\sim\text{Gamma}(1/2,1/2)$. The sum of two independent gammas is again gamma. It's cdf is well known.
Comment: You cannot integrate it in closed form, you can express it using the erf function. But in this case you forgot the jacobian of the integral, if you include it you find a closed form pretty easily
Comment: You can derive that using the your usual techniques. However, at some point it's just a "common fact", I guess.
Comment: @probablyme is there a name of this technique/law?
Answer: Your forgot the Jacobian factor $r$. If you include it, the integral becomes a lot easier to evaluate.
Comment: He also forgot the normalization constants for the densities:$$\int_{-\infty}^{+\infty}e^{-x^2/2}\,dx \neq 1.$$
Comment: @JackD'Aurizio This is unclear, maybe the OP just focussed on the problematic part.
Comment: Oh right how could I forget!!! It seems my calculus knowledge disappears when approaching probability questions. Thanks again for your help!
Answer: To elaborate on @probablyme 's comment, you can use the characteristic function to derive the "common fact".
We have that if $X \sim N(0,1)$, then the characteristic function (CF) of $X^2$ (for any $t \in \mathbb{R}$) is
$$
\begin{align}
\varphi_{X^2}(t)&=E \left(e^{itX^2} \right) \\ \\
&= \int_{-\infty}^{\infty} e^{itx^2} \frac{1}{\sqrt{2 \pi}} e^{\frac{-x^2}{2}} dx \\ \\
&= \frac{1}{\sqrt{2 \pi}} \int_{-\infty}^{\infty} e^{-x^2 \left(1-2it\right)2^{-1}} dx \\ \\
&=\frac{1}{\sqrt{2 \pi}} \frac{\sqrt{\pi}}{\sqrt{\left(1-2it\right)2^{-1}}} \, , \quad \mbox{see Gaussian integral on Wikipedia for this result} \\ \\
&= (1-2it)^{-1/2} \quad \mbox{which is the CF of a } \chi^2_{(1)}
\end{align}
$$
Let $Z$ be a r.v. distributed as $\chi^2_{(1)}$. By the Uniqueness Theorem, if $\varphi_{X^2}(t) = \varphi_{Z}(t)$, then $X^2 \sim Z$. So, $X^2 \sim \chi^2_{(1)}$. The same is valid for $Y^2$.
Now, since $X^2, Y^2 \stackrel{iid}{\sim} \chi^2_{(1)}$, we can calculate the CF of $X^2+Y^2$ for any $t \in \mathbb{R}$:
$$
\begin{align}
\varphi_{X^2+Y^2}(t) &= E \left(e^{it(X^2+Y^2)}\right) \\
&= E \left(e^{itX^2}e^{itY^2}\right) \\
&= E \left(e^{itX^2} \right) E\left(e^{itY^2}\right) \, , \quad \mbox{by independence} \\
&= \varphi_{X^2}(t) \varphi_{Y^2}(t) \\
&= (1-2it)^{-1/2} (1-2it)^{-1/2} \\
&= (1-2it)^{-2/2} \, , \quad \mbox{which is the CF of a } \chi^2_{(2)}
\end{align}
$$
Therefore, $X^2+Y^2 \sim \chi^2_{(2)}$, and you can use its PDF to get your answer.
Also, we have that $\chi^2_{(1)}$ is a special case of Gamma ($Gamma(1/2,1/2)$, as stated by @probablyme). The same way,  $\chi^2_{(2)}$ can be seen as $Gamma(2/2,1/2) = Gamma(1,1/2)$ or $Exponential(1/2)$ (another special case of Gamma).
Answer: Since $X,Y\sim N(0,1)$ then $X^2,Y^2\sim \chi^2(1)\implies X^2+Y^2\sim \chi^2(2)$ Now use the$\chi^2$ distribution's CDF or PDF as required..
Comment: How did you get that $X^2 \sim Cauchy(1)$?
Comment: This is odd, Cauchy(1) and Cauchy(2) random variables are positive or negative with equal probability while X^2 and X^2+Y^2 are always positive... (Add some suitable expression of bewilderment at the upvote.)
Comment: @Did  : It was a serious typo on my part. I am extremely sorry. I dont know what made me type that.. Please forgive me.
Comment: @Gus_est : It was a serious typo on my part. I am extremely sorry. I dont know what made me type that.. Please forgive me.
Comment: No worries. It happens to us all


Facebook signed request problem

Question: I want to write a fangate for my facebook page, but it didnt work and i doesnt find any help on the inter net
require 'facebook.php';

$app_id = '16850872653xxxx';
$app_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));

$signed_request = $_REQUEST['signed_request'];

//echo $signed_request;

list($encoded_sig, $payload) = explode('.', $signed_request, 2);

// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);

// check sig
$expected_sig = hash_hmac('sha256', $payload, $app_secret, $raw = true);

function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}

if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}

I am using this code... but it just jumps to github where i have downloaded the facebook.php....
does anybody see a problem with this code?
the require just jumps to github and the json_decode doesnt work...
Comment: FYI, even though you have edited this post, your app id and app secret are still visible (in the revision history); you may want to regenerate your app secret (in the FB developers area) to keep your app secure.
Answer: There are a few errors with the code you sent. This is what I use, and it works:
if (isset($_REQUEST['signed_request'])) {
      $encoded_sig = null;
      $payload = null;
      list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
      $sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
      $data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
      if($data->page->liked) {
          echo "This content is for Fans only!";
        } else {
          echo "Please click on the Like button to view this tab!";
        }
    }

And don't post your application secret key on the forum, please edit your post as soon as possible.
Comment: thanks... do I have to use a server that supports https? sorry I cant change my post... or I even dont know how to... but i have deleted the app...
Comment: Well, you don't have to use a SSL certificate, but facebook will show a warning to everyone using the new secure page every time they visit your app. Such users are rare now, just a few percent, but they are very loud and soon you will start getting mails like "Why isn't your app secure". I recommend you get SSL soon.
Comment: Great block of code that, just what I was after - Thanks @DannyKK
Comment: Excellent code. May I just add that as of today all canvas apps must have an SSL certificate (HTTPS)

Facebook signed request problem


Form API AJAX refreshes page

Question: I need to add some AJAX functionality to a node form. Using hook_form_alter I'm overriding form elements. In this particular case I need to add a callback on the 'language' element provided by the translation module (Core, Content Translation).
However, when selecting a different option in the 'language' listbox, the page refreshes. What could trigger this behaviour?
This is the code I'm using:
function foo_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'bar_node_form') {
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $form['language']['#ajax'] = array(
      'callback' => 'bar_form_callback',
      'wrapper' => 'bar-form-wrapper',
    );

    if (isset($form_state['values'])) {
      drupal_set_message('ajax callback');
    }
  }
}

function bar_form_callback($form, $form_state) {
  return $form;
}

Comment: Did you find a solution for this??, I'm facing the same problem...
Answer: What exactly are you trying to do? Is the page refreshing or the entire $form? What you're asking it to do is by attaching #ajax to the select is that when it changes a value resubmit the entire $form, which would probably include any submit handlers. Typically #ajax would be directed at a form element rather than the entire form.
Comment: The complete page is refreshing.
Comment: So what are you trying to do actually? The callback function should just return the part(s) of the form that you want to update. Why are you returning the entire form?
Comment: I need to change properties of a few form elements.
Comment: Even if I replace/return one element in the callback the page reloads.
Comment: I'm out of ideas. If you get me your whole module I'm happy to try and give it a quick debug.
Answer: since the callback is acting as a form submit, your callback (_submit) should have the same naming convention as your form id.
"bar_node_form" is your form id so:
'callback' => 'bar_node_form_submit',

Answer: When you specify 'callback' => 'bar_form_callback', it's not referring to a PHP callback per se. Callback in this case refers to a hook_menu() callback, in other words, the URL that JavaScript will call when the AJAX trigger is fired.
You need to define a bar_form_callback path in your custom_module_menu() function. That menu callback then call function bar_form_callback().
D.O. FAPI reference.
Comment: As explained in my question, adding AJAX to the form is what I intend to do. "What could trigger this behaviour?" is a question on what causes the page to reload (yes, a hard reload). The page reloads when I select a language in the select box.
Comment: Hopefully it's just that you're missing the hook_menu() callback.
Comment: I don't think you need a hook_menu() defined for the #ajax callbacks.
Comment: I think you do. Else, how is Drupal going to find your function? I doubt there's some automagical behavior for that. Also check your Firebug. When you click on the languages button, what is the XHR (AJAX) callback path? Probably is thenameofyoursite.com/bar_form_callback.
Comment: Also, check your PHP error log and the Drupal watchdog. It might have been throwing an error. "Hard" reload is not supposed to be the normal behavior, so one can only assume there's an error involved. I think again your error is that you're missing the AJAX callback (the hook_menu implementation).
Comment: Malks is right, you don't need hook_menu defined for an #ajax callback.
Comment: What path in the Drupal site is JavaScript calling? What PHP function is handling that message. There's a PHP callback somewhere getting the message from JavaScript's XHR, and something tells me it's not your PHP function. If you do a `error_log('foo bar baz');` on your PHP callback, what happens? Does "foo bar baz" appear on your error log?
Comment: #ajax is handled by a drupal defined callback. Part of its reason for existing is to save the coder the effort of having to define a callback manually.
Comment: Good. I'm curious though, is your PHP function getting called?
Comment: ['#ajax']['callback'] refers to a callback in your module, not to a hook_menu implementation

Form API AJAX refreshes page


Transformar linhas em colunas no SELECT Oracle

Question: Segue abaixo um select para consulta de dados em uma tabela:
SELECT
'OS:'||AT.CD_NUMERO_OS ||' ITEM:'|| AT.ITEM ||' ETAPA DA ATVD:'||AT.CD_ETAPA_ATIVID||' ATVD:'|| AT.CD_ATIVIDADE AS "DADOS DA OS",
AT.DT_INICIO AS "DATA DE INICIO",
AT.DT_TERMINO AS "DATA DE FIM"

FROM GMATIVID AT

INNER JOIN GMOSERVI OS ON OS.CD_NUMERO_OS = AT.CD_NUMERO_OS

WHERE OS.DT_OS BETWEEN TO_DATE(:data_abertura_os_inicial, 'DD/MM/YYYY') AND TO_DATE(:data_abertura_os_final, 'DD/MM/YYYY')
AND OS.SITUACAO LIKE 'E'

ORDER BY AT.CD_NUMERO_OS ASC, AT.ITEM ASC, AT.CD_ATIVIDADE ASC

Abaixo segue o resultado dessa consulta:

Preciso transformar as linhas em colunas para encaixar no relatório report que estamos desenvolvendo, segue abaixo como preciso da informação:

É possível realizar essa "transposição" de linhas em colunas diretamente na consulta SQL?
Comment: Pesquise pir PIVOT ou CASE PIVOT https://www.oracle.com/technical-resources/articles/database/sql-11g-pivot.html   https://blogs.oracle.com/sql/how-to-convert-rows-to-columns-and-back-again-with-sql-aka-pivot-and-unpivot
Answer: Com PIVOT você resolve isso.
Exemplo :
SELECT d.department_name, e.job_id, count(e.employee_id)
FROM hr.employees e
INNER JOIN hr.departments d
  ON d.department_id = e.department_id
GROUP BY d.department_name, e.job_id
ORDER BY d.department_name, e.job_id
;

WITH values_join
AS
(
  SELECT d.department_name department_name, e.job_id job_id, e.employee_id qty_empl
  FROM hr.employees e
  INNER JOIN hr.departments d
  ON d.department_id = e.department_id
)
SELECT * FROM values_join
  PIVOT
  (
  COUNT(qty_empl)
  FOR job_id IN ('AC_ACCOUNT','AC_MGR','AD_ASST','AD_VP','FI_ACCOUNT','FI_MGR','HR_REP',
                 'IT_PROG','MK_MAN','MK_REP','PR_REP','PU_MAN','SA_MAN','SA_REP',
                 'SH_CLERK','ST_CLERK','ST_MAN')
  )
ORDER BY department_name
;


What's the difference between using Drupal's jQuery library and adding it in html.tpl.php?

Question: I'm recoding one site (D7) where I stumbled upon statically added jquery (using a script tag inside html.tpl.php that pulls jquery library from google CDN). I installed "jQuery CDN" module that does the same and expected that when I loose statically added script tag everything would stay the same, but the menu and slider don't work (menu is implemented using some internal jsddmenu.js file, also slider using slides.jquery.js). What's the difference between those two implementations, when both of them add:

to the html code?
Answer: Its better to add javascript using your:
a) theme's .info file using scripts[] = "some/filename.js"
b) in the theme dynamically ... such as mytheme_node_view() { drupal_add_js('file', 'some/filename.js'); }
c) or in a custom module ... (similar to above)
depending entirely on your site's needs.
the reason its better to approach this this way is:
1) the theme's scripts[] array is cacheable and will attach the javascript to every page.
2) dynamically attaching it allows the script to be used only when needed.
3) you don't force the client to load anything they don't need.
4) if its attached in one of the above ways, it can be minified if needed --- allowing the client to download one big javascript file instead of a dozen separate ones.
Comment: thanks for that clarification, but I was more interested in: why using Drupal's jquery library isn't working the same as adding the same script tag myself in html template file.
Comment: You cannot add remote scripts in .info files. I'm not sure if you can do it in drupal_add_js either. But definitely using http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_html_head/7
Caching is the main reason, and theme updates is another reason.
Comment: If it's working when added in the html template and not when added correctly, I would double-check that the caches have been cleared after adding it.
Answer: Why you should not add script in your tpl because Drupal has theme layer access and module layer access. It's for Drupal caching performance reason.
Have you read about how to work with Javascript & jQuery ?
http://drupal.org/node/171213
You can check this option to use Google CDN
http://yourdrupal.site/admin/config/development/performance
If you need uptodate version you can install
http://drupal.org/project/jquery_update
Answer: Its may related to lead and Lag of files, when you add script in tpl it will load after all scripts specified in head. jQuery in dependency for slider ...


Como incluir uma linha no início de um arquivo de texto?

Question: Meu sistema gera um arquivo de texto, e com base na soma de uma informação que consta em cada linha, ele faz o cálculo de um dígito verificador.
Porém, esse resultado deve estar na primeira linha do arquivo, como posso fazer para incluir essa linha no início?
Answer: Simples. Você só precisa

Ler todo o arquivo e salvar numa lista de string, onde cada linha represente uma string na lista
Inserir a nova linha na posição 0 da lista
Escrever todas as strings da lista no arquivo

const string nomeArquivo = "arquivo.txt";

List<string> linhas = File.ReadAllLines(nomeArquivo).ToList(); // Passo 1
linhas.Insert(0, "Primeira linha"); // Passo 2
File.WriteAllLines(nomeArquivo, linhas); // Passo 3


DoCmd.OutputTo only works on break

Question: I've come across a challenging problem with the DoCmd.OutputTo command in VBA Access 2013.
I've got below code which is basically to print a specific report from what is essentially a collection of records of reimbursements. The idea is that one would be able to [export] the active record (from the active form) to a PDF file and then add the scanned invoices to the PDF.
Thereto I would need to build the base file (i.e. the PDF where the invocies are added to) and then run the routine for adding the individual files.
Below code should create the initial PDF file:
<code>    Dim rpt as Report

    filePath = "<some filepath>"
    fName = Me!idDecl & " - (script).pdf"
    filePath = filePath & fName

    Set rpt = Report_qryDeclInvoice
    With rpt
        .Filter = "[fltID]= " & Me!id
        .FilterOn = True
    End With

    DoCmd.OpenReport rpt.Name, acViewPreview, , "[fltID]= " & Me!id
    DoCmd.OutputTo acOutputReport, rpt.Name, acFormatPDF, filePath, False
    DoCmd.Close acReport, "qryDeclInvoice"
</code>
If I run the code -without breaks- the report opens as per the filtered argument, however, the subsequent command to output the record to PDF doesn't ?
That is, there appears a dialog box very briefly (can't read what it says) and then execution simply stops, no errors, no faultcodes just a clean break ?
Now for the interesting bit..
If I set a breakpoint on the DoCmd.OutputTo line, and execute the line with F8 the code works more or less flawlessly (see below)?? It appears that the break allows the preview routine to complete first and then run the OutputTo routine.
In addition to above challenge, on some of the reports (i.e. on some reimbursements) it works fine and the file is created yet on others it does not create the initial PDF at all and the code breaks without error codes or fault reporting. Without there being a distinguishable difference between the reports ?
I've tried delaying the OutputTo from the OpenReport function by sleeping it for 1000ms but that doesn't work (even upto 5000ms doesn't yield results)
Also if I remove the open preview line and just execute the OutputTo line, without opening the preview first, it works only when breaking and executing with F8 and again, only on some of the reports not all ?
It seems that the OutputTo command is -at least in my case- somewhat unreliable :-)
Any suggestions ??
Comment: GD All,

OK, found out what was going on;

The faulty reports created multiple pages, based on grouping.

VBA code in/on the report, re-created page numbers based on grouping (i.e. restarted page numbering for start of every group.)

The execution of VBA within the report (i.e. on open, or on page) interferes with the execution of OutputTo routine

Both the above interfered with the OutputTo routine, though not sure why -yet-

Removal of all VBA code within the report solved the issue !!
Comment: Excellent - why not add that as an answer, Q&A style?
Answer: OK, found out what was going on;
The faulty reports, that I mentioned, created multiple pages, based on grouping.
A section of VBA code in/on the report, re-created page numbers based on grouping (i.e. restarted page numbering for start of every group.) The execution of this VBA within the report (i.e. on open, or on page) interferes with the execution of the "OutputTo" routine. The above interfered with the OutputTo routine, causing it to break, though not sure why -yet-
Removal of all VBA code within the report solved the issue !!
Some added details:

No need for the preview anymore
set the filter of the report from VBA and open the report through the report object.name

Find below the working code:
<code>Dim rpt as Report

filePath = "<somepath>"
fName = Me!idDecl & "-(script).pdf"
filePath = filePath & fName
'Debug.Print filePath

Set rpt = Report_qryInvoice
With rpt
    .Filter = "[fltID]= " & Me!id
    .FilterOn = True
End With

'Sleep (5000)
DoCmd.OutputTo acOutputReport, rpt.Name, acFormatPDF, filePath, False, , , acExportQualityScreen
</code>

DoCmd.OutputTo only works on break