Proof of $\ln{ab} = \ln{a} + \ln{b}$ using the limit definition of $\ln{x}$

Question: I have seen proofs for $\ln{ab} = \ln{a} + \ln{b}$ that use the integral definition of $\ln{x}$ but is there a proof that uses the limit definition $$\ln{x} = \lim_{h\to 0} \frac{x^h-1}{h}$$
I tried using squeeze theorem with AM-GM inequality on $a^h$ and $b^h$ $$a^h + b^h \ge 2\left( ab\right)^{h/2}$$ Which I could reduce to a lower bound
$$\lim_{h\to 0} \frac{a^h-1}{h} + \frac{b^h-1}{h} \ge \lim_{h\to 0} \frac{2\left( \left( ab\right) ^{h/2}-1\right)}{\frac{h}{2}2}$$
$$\ln{a} + \ln{b} \ge \ln{ab}$$ But I couldn't complete the proof with an upper bound. I tried using the HM inequality $$\frac{4a^hb^h}{a^h + b^h} \ge a^h + b^h$$ $$\lim_{h\to 0} \frac{\frac{4a^hb^h}{a^h + b^h} - 2}{h} \ge \ln{a} + \ln{b}$$ But the left hand side just ended up giving me a useless upper bound $$\lim_{h\to 0} \left( \frac{2}{a^h+b^h}\right)\left( \frac{2\left( ab\right)^h-a^h-b^h}{h}\right)$$ $$\lim_{h\to 0}a^h\frac{b^h-1}{h} + b^h\frac{a^h-1}{h}$$ $$\ln{b} + \ln{a}$$
Is there a way to complete the squeeze theorem or even a different approach entirely to prove it
Comment: What is $x^h$ for real $h$?
Answer: $$\begin{align}\ln(ab)&=\lim_{h\to0}\frac{(ab)^h-1}h\\&=\lim_{h\to0}\frac{(a^h-1)b^h+(b^h-1)}h\\&=(\ln a)b^0+\ln b.\end{align}$$
Answer: Let $f(x) := a^x$ and $g(x) := b^x$.  Then by definition, we have $f'(0) = \ln a$ and $g'(0) = \ln b$.  On the other hand, since $f(x) g(x) = (ab)^x$, we also have $(fg)'(0) = \ln(ab)$.  Therefore, the product formula for derivatives gives
$$\ln(ab) = (fg)'(0) = f(0) g'(0) + g(0) f'(0) = 1 \cdot \ln b + 1 \cdot \ln a.$$
(If you unfold the usual proof of the product formula for derivatives, what you end up with is essentially the answer by Anne Bauval.)
Answer: We need to show that
$$
\lim_{h \to 0}\left(\frac{a^h-1}{h}+\frac{b^h-1}{h}-\frac{(ab)^h-1}{h}\right)=\lim_{h \to 0}\left(\frac{a^h+b^h-(ab)^h-1}{h}\right)=0
$$
We see $a^h+b^h-(ab)^h = b^h-a^h(b^h-1)$. As a result,
$$
\lim_{h \to 0}\left(\frac{a^h+b^h-(ab)^h-1}{h}\right)=\lim_{h\to 0}  \left(\frac{b^h-1}{h} -\frac{a^h(b^h-1)}{h} \right)=\ln{b}-\ln{b}=0.
$$
Comment: Essentially the same as my answer, except for two mistakes of sign: $a^h+b^h-(ab)^h =- a^h(b^h-1)+b^h,$ and $\frac{a^h+b^h-(ab)^h-1}{h}=-\frac{a^h(b^h-1)}{h} +\frac{b^h-1}{h}.$
Comment: @AnneBauval Thank you for pointing out the mistake. Indeed they are essentially the same. One uses the trick of creating terms and another one uses the trick of combining terms. Both are useful in the study of calculus. But the more important point is commuting product sign and limit sign.


Adding an additional GET variable on form submit

Question: I have two "forms" that consist of a single dropdown list each. I'm submitting both forms with javascript onchange="this.form.submit()" I need to reserve a variable, if it is set, on the second form submit. I have the form submitting to the same page and currently, it isn't passing the first variable.
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="GET">
    <select name="show" style="width:100%;" onchange="this.form.submit()">
        <option value="cond" <?php if(isset($_GET['show'])&&$_GET['show']=='cond'||!isset($_GET['show'])) { echo 'selected'; } ?>>Condensed</option>
        <option value="full" <?php if(isset($_GET['show'])&&$_GET['show']=='full') { echo 'selected'; } ?>>Show All</option>
    </select>
</form>

<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="GET">
    <select name="sort_slsp" style="width:100%;" onchange="this.form.submit()">
    <option value="">--Choose Salesperson--</option>
            <?php
                $get_all_slsp = mysqli_query($lmcon, "SELECT * FROM slsps ORDER BY slsp_name");
                while($row = mysqli_fetch_array($get_all_slsp)) {
                    echo '<option value="' . $row['slsp_id'] . '">' . $row['slsp_name'] . '</option>';
                }
            ?>
    </select>
</form>

Comment: @fusion3k: I think the value is contained in `$_SERVER["PHP_SELF"]`, from the first form submit, and since OP uses it as value of the `action` attribute, they expect it to be send with the rest of the form. (Why that doesn't happen – see my answer.) A hidden field is the (easiest) way to go here, that's right.
Comment: please show some of your code...
Comment: I added the two forms above.
Comment: I don't understand. Where is the variable on second form? If you want submit an additional value with the form, you can add (after `` declaration, before `` tag) something like ``. But
I do not know if I understand the question.
Answer: When the form method is GET, browsers overwrite any possibly existing query string part of the URL specified via the action attribute with the new query string they construct from the form fields.
The easiest solution here is to add that additional value you want to submit as a hidden input field into the form:
<input type="hidden" name="foo" value="bar">

Seing as your first select field has the name show, and that is likely the value you want to pass on here(?), you'd fill that value attribute as such,
value="<?php echo htmlspecialchars($_GET['show']); ?>"

(Adding a check for whether that parameter exists in the first place, and maybe output a default value if not, I'll leave up to you.)
Comment: I was gonna suggest him to make the form's action URL contain already present URL query, but your solution is more interesting for sure.
Comment: @Nino: _"to make the form's action URL contain already present URL query"_ – that's what they already had (if I understood OP correctly), but it doesn't work (see first paragraph of my answer.)
Comment: No, I meant have a form action like this `?foo=bar&` instead of current URL.
Comment: @Nino Yes, I know. That does not work – again, first paragraph of my answer …
Comment: Really? Okay, weird.
Comment: YES! :) I'm now checking if the variable is set (on each form) and if so, adding the hidden input. Super simple! Thanks a ton man!
Comment: Is it appropriate protocol around here to edit my question with the solution, above?
Comment: @jds: No, you can leave the question as it is. Upvoting and/or marking an answer as accepted is the mechanism here to tell people that an answer helped you solve your problem. (If you're new here, I suggest a quick look at the tour, to understand how SO works a little better: http://stackoverflow.com/tour)
Comment: Thanks brother. I appreciate it. You've been a big help! Before I look, is it against the rules to hire a person for consultation through here?
Comment: Offering a job inside a question here would get it closed quite quickly, and http://stackoverflow.com/jobs is for "bigger" jobs. For smaller consultancy work (business or private), I suggest you look/search locally if possible.


Improper Integral Question

Question: Express $$\int_0^1x^m(1-x^n)^pdx$$ in terms of gama function and hence evaluate the integral.
I used the substitution $x^n=y$ and solving got this integral as equal to the beta-function
$${1\over n}\beta({{{m+1}\over n},{p+1}})$$ solving futher by converting to gamma function ($\gamma)$ i get
$${1 \over n}[{{\Gamma({m+1 \over n})\Gamma(p+1)}} \over \Gamma({{m+1} \over n}+p+1)$$
and the answer i finally get is
$$p\over (m+p-1)!(m+np+1)$$
Is it correct ? One doubt i had in the solution is can we write
$$\Gamma(a+p)={{(a+p-1)!} \over (a-1)!} \Gamma(a)$$  ??
Comment: At first I thought it was a question about an improper integral. But you integral does not seem improper, so perhaps it is an improper question about an integral? (English is such a weird language sometimes.)
Comment: Lets say yes, coz nothing is mentioned in the question.
Comment: I think i figured it out. Should it not be $$\Gamma(a+p)={{(a+p-1)!} \over (a-1)!} \Gamma(a)$$
Comment: For your last question, no you can't do that. $\Gamma(a+p)=(a+p-1)(a+p-2)\cdots a\cdot\Gamma(a)$, and you can't simplify that the way you suggested.
Comment: LOL!!! No its not an imroper question about integration. I mean a Euler Integral. Here you will see that for m<0 the integral will become improper
Comment: how did you write that gamma  ?
Comment: @AmanMittal to make a capital greek letter, use a capital to start the LaTeX command: `\gamma` $\to \gamma$, and `\Gamma` $\to \Gamma$
Comment: Like so: `\Gamma`
Comment: @anorton I mean the gamma function that you have mentioned. i was not able to find out how to write that here.
Comment: i guess there is a problem in the step where i write $\Gamma(a+p)=(a+p-1)!\Gamma(a)$ Any clue about that ?

Is there any rule that can reduce $\Gamma(a+p)$ to something * $\Gamma(a)$
Comment: @Is $a$ guaranteed to be integer-valued?  (Or at least, is $a+p$ guaranteed to be integer-valued?
Comment: Your answer looks suspicious, because unless you write it in terms of gamma functions, it can't possibly be true for the case when m and/or n and/or p aren't positive whole numbers.
Answer: $$
\begin{align}
\int_0^1x^m(1-x^n)^p\,\mathrm{d}x
&=\int_0^1u^{m/n}(1-u)^p\,\mathrm{d}u^{1/n}\\
&=\frac1n\int_0^1u^{(m+1)/n-1}(1-u)^p\,\mathrm{d}u\\
&=\frac1n\frac{\Gamma\left(\frac{m+1}{n}\right)\Gamma(p+1)}{\Gamma\left(\frac{m+1}{n}+p+1\right)}\\
&=\frac{p}{m+1+pn}\frac{\Gamma\left(\frac{m+1}{n}\right)\Gamma(p)}{\Gamma\left(\frac{m+1}{n}+p\right)}
\end{align}
$$
So your initial answer looks good. However, I don't see how you get from there to
$$
\frac{p}{(m+p-1)!(m+np+1)}
$$
In the last question, for integer $n$, $\Gamma(n)=(n-1)!$. The rest is simply cancellation.

Improper Integral Question


In wrestling, how is scoring measured?

Question: In wrestling, whether it be at the collegiate (collegiate wrestling) or high school (scholastic wrestling) level, how is wrestling scored on a per match in addition to a team basis?
Comment: I now just noticed you were asking for scoring in collegiate/high school wrestling...which is widely used in the US. These differ from international styles as presented in my answer.
Answer: Pages 34-40 of the International Wrestling Rules published by the International Federation of Associated Wrestling Styles (FILA), the governing body of international amateur wrestling, contains more details on scoring as it relates to greco-roman, freestyle, and women's wrestling.

Takedown: awarded when the wrestler gains control of his opponent from a neutral position in which three points (eg. two arms and head, two knees one arm (or head), or two arms one knee) are controlled

5 points: awarded when a wrestler throws his
opponent off the mat from either the standing or par terre (starting)
position, and the opponent's feet go
above his head into the "danger position"  (see definition below)
3 points: awarded when a wrestler throws his opponent off the mat but does not bring him into a danger position, or takes his opponent from his feet or
stomach to his back or side into the danger position
1 point: awarded when a wrestler takes his opponent from his feet to his stomach
or side in which his back or shoulders are not exposed to the
mat but are controlled

Reversal (1 point): awarded when a wrestler gains control over his opponent when the opponent has initial control
Exposure (2-3 points): awarded when a wrestler exposes or places (but not pins) his opponent's back to the mat for several seconds  (also see "danger position" below | more details on exposure on p. 35-37)
Out-of-Bounds (1 point): awarded to a wrestler when his opponent places his foot into the protection area
Stalling (1 point): awarded to a wrestler when his opponent flees a hold or refuses to start
Penalties

1-2 points:  awarded to a wrestler when his opponent commits an infraction (eg. fleeing, intending to injure, striking, holding illegally, etc.)...the wrestler also is awarded choice of position to the opponent while the opponent is awarded a caution
1 point: awarded to a wrestler when his opponent takes an injury timeout (except when the opponent is bleeding) or regularly refuses to take an ordered hold

Definition of "danger position":  (p. 35)

A wrestler shall be considered in the 'danger position' when the line
  of his back (or the  line of his shoulders) vertically or in parallel
  with the mat, forms an angle of less than 90  degrees to the said mat
  and when he resists with the upper part of his body to avoid a
  'fall'.

In wrestling, how is scoring measured?


C++ How do I print a .txt file verbatim?

Question: I have a file that I am trying to print to the screen, but all it returns is "0x28fe88", when the file itself is 13 columns by a couple hundred rows.
#include <iostream>
#include <fstream>
#include <istream>
#include <ostream>
#include <cstdlib>
using namespace std;

int main()
{
    //Opens .txt file
    ifstream infile1;
    infile1.open("Taylor.txt");

    //Fail check
    if(infile1.fail())
    {
        cout << "File failed to open.\n";
        exit(1);
    }

    //Prints file to screen (not correctly)
    cout << infile1;

    //Closes file
    infile1.close();
    return 0;
}

I would otherwise not post the full code, but I hope it is short enough to not warrant catching flak.
Comment: `cout << infile1;` *does not* print the file contents to stdout. It's printing the object address out.
Comment: You're not printing the contents of the file you're printing the ifstream object.
Comment: The original code inserts a stream object into a stream. That works because, prior to C++11, stream classes (technically, the base class `basic_ios`), has a conversion to `void*` that indicates whether the stream is in a good state (returns a null pointer if it's not, and a non-null pointer otherwise); what the original code display is the result of this conversion operator. In C++11 that conversion is no longer present; it's been replaced with `explicit operator bool()`, which serves the same purpose without introducing mysterious conversions in non-boolean contexts.
Answer: To just print out text file use this cout << infile1.rdbuf();, because now you're printing a pointer to a file.
EDIT:
If this didn't work for you, the closest thing to it would be to read file character by character. There are other ways around it using strings, but this code will do just fine:
while(infile1.good())
    cout << (char)infile1.get();

It reads character code while the file is good to read and instantly converts it to char (might need some modifications for UNICODE) and prints it out.
Comment: This should also print a pointer, this time the pointer to infile1's buffer object. Try this code: cout.rdbuf(infile1.rdbuf());
Comment: `cout << infile1.rdbuf()` works just fine, because who knows :)
Comment: I supplemented this for what I had, but it is still printing the previously stated output. To reiterate, I just want to print the file as is.


Solve $\sin A +\sin 2A +\sin 3A + \sin 4A = 0$, for $0 \leq A \leq 180$

Question: I've tried using factor formula but still did not manage to get the answer, not sure if factor formula is the right method.
I rearrange to $\sin 4A + \sin 2A + \sin 3A + \sin A = 0$,
and after applying factor formula,
$2 \sin 3A \cos A + 2 \sin 2A \cos A = 0$
$2 \cos A ( \sin 3A + \sin 2A) = 0$
$2 \cos A ( \sin \frac{5}{2} A \cos \frac{1}{2} A) = 0$
Then I'm stuck..
Comment: One of the factors is zero.
Comment: Related : http://math.stackexchange.com/questions/1341096/cos-2-leftx-right-cos-2-left2x-right-cos-2-left3x-right-frac32
Answer: From the point that you stopped

$$2 \cos A ( \sin \frac{5}{2} A \cos \frac{1}{2} A) = 0$$

$$2\cos(A/2)\cos(A)\sin(\frac{5A}{2})=0 \bigg/:2$$
$$\cos(A/2)\cos(A)\sin(\frac{5A}{2})=0$$
$\cos(A/2)=0\;$ or $\cos(A)=0\;$ or $\sin(\frac{5A}{2})=0$
Comment: I solve and got 0, 90, 144, 180 but im still missing 72(answer sheet shows that 72 is one of the answer).

Can you see if you have 72 as one of your answer?
Comment: The general solution should be: $a_1=n\pi,\;a_2=n\pi-\frac{\pi}{2},\;a_3=2n\pi-\frac{4\pi}{5},\;a_ 4=2n\pi-\frac{2 \pi}{5} ,a_5=2n\pi+\frac{2\pi}{5} ,\; n \in \mathbb{Z}$
Comment: @ming $72^\circ$ satisfies $\sin\frac{5A}2 = 0$. In fact, the general solution from $\sin\frac{5A}2 = 0$ is
$$\begin{align*}
\frac{5A}2 &= 180^\circ n&n\in\mathbb Z\\
A &= 72^\circ n
\end{align*}$$
Comment: to be honest I actually dont understand what are y'all doing, maybe a little but mostly no.

here's how I approach,

Let basic angle = a

cos A = 0        sin 5/2 A = 0        cos 1/2 A = 0
  a = 90              a = 0                     a = 90
Comment: @ming Then the problem is you have missed $\frac{5A}2 = 180^\circ$ and $\frac{5A}2 = 360^\circ$.
Answer: You've done the hard work
Now the product of three multiplicands is zero
so at least one of them must be equal to zero
If $\sin B=0,B=n180^\circ$
If $\cos C=0, C=(2m+1)90^\circ$ where $m,n$ are integers
Answer: Had the number of summands been larger, we could employ the method dsecribed in How can we sum up $\sin$ and $\cos$ series when the angles are in arithmetic progression?
If $\sin\dfrac A2=0,$ given expression holds true
and $\dfrac A2=n180^\circ\iff A=n360^\circ$ where $n$ is any integer
Else $A\ne n360^\circ$ and $\sin A+\sin2A+\sin3A+\sin4A=\cdots=\dfrac{\cos\dfrac A2-\cos\dfrac{9A}2}{\sin\dfrac A2}$
So we need $\cos\dfrac A2-\cos\dfrac{9A}2=0\iff\cos\dfrac{9A}2=\cos\dfrac A2$
$\implies\dfrac{9A}2=360^\circ m\pm\dfrac A2$ where $m$ is any integer, but $A\ne n360^\circ$
Consider the +, - separately
Answer: we have, $$\sin A+\sin 2A+\sin 3A+\sin 4A=0$$ $$(\sin A+\sin 3A)+(\sin 2A+\sin 4A)=0$$ $$2\sin\left(\frac{A+3A}{2}\right)\cos\left(\frac{A-3A}{2}\right)+2\sin\left(\frac{2A+4A}{2}\right)\cos \left(\frac{A-3A}{2}\right)=0$$ $$2\sin 2A\cos A+2\sin 3A\cos A=0$$ $$2\cos A(\sin 2A+\sin 3A)=0$$ $$\implies \cos A=0\implies \color{blue}{A=2n\pi+\frac{\pi}{2}}$$ $$\implies \sin 2A+\sin 3A=0\implies \sin 3A=-\sin 2A$$ $$\implies 3A=2n\pi-2A\implies \color{blue}{A=\frac{2n\pi}{5}}$$ Or $$3A=(2n+1)\pi-(-2A)$$ $$\implies \color{blue}{A=(2n+1)\pi}$$ Where, $n$ is any integer.
Edit: For $0\leq A\leq 180^\circ$ put $n=0$, $n=1$ & $n=2$ in the solutions, we get the following $$\color{blue}{A\in \left\{0, \frac{2\pi}{5}, \frac{\pi}{2},  \frac{4\pi}{5}, \pi\right\}}$$ or $$\color{blue}{A\in \left\{0^\circ, 72^\circ, 90^\circ, 144^\circ, 180^\circ\right\}}$$
Comment: $$\begin{align*}\sin A + \sin 3A &= 2\sin 2A \color{red}\cos A\\
\sin 2A + \sin 4A &= 2 \sin 3A \color{red}\cos A\end{align*}$$ which is what OP has written.
Comment: @peterwhy: So, could you please explain if there is something wrong in the solution, if you don't mind?
Comment: Then the $5$th line should be
$$\implies \cos A = 0 \implies \color{blue}{A= n\pi + \frac\pi2} $$
Comment: Oh, sorry I couldn't spot the error. you are right. thanks!
Answer: To be honest I actually don't understand what are y'all doing, maybe a little but mostly no.
here's how I approach,
Let basic angle = a
cos A = 0
  a = 90
A = 90
sin 5/2 A = 0
a = 0
5/2 A = 0, 360
A = 0, 144
cos 1/2 A = 0
a = 90
1/2 A = 90
A = 180
Therefore, A = 0, 90, 144, 180
But where's the 72 T.T
Comment: Then the problem is you have missed $\frac{5A}2 = 180^\circ$.
Comment: oh my gawd.. thanks so much!


duvida sobre ação css em div

Question: Bom galera eu gostaria de saber como posso fazer uma div acionar o display none
quando eu estiver com focus na input ex de codigo
//CSS
.email:focus > div.oculta{
     display:none;
}
//HTML

  <input type="text" class="email" name="email" placeholder="email" />

teste

como posso fazer isso funcionar?
Answer: O seu seletor CSS está aplicando display: none para um div.oculta filho de um .email:focus. No seu HTML, o div.oculta não será afetado, pois não é filho de .email:focus.
Dessa forma, você poderia fazer funcionar: utilizando o seletor ~ ou +, que selecionam elementos seguidos:
.email:focus + div.oculta{
     display:none;
}

  <input type="text" class="email" name="asdasd" placeholder="email" />

    teste

Caso você queira ocultar o div.oculta com o HTML dessa forma, não será possível usar seletores CSS para atingí-la a partir de .email:focus. Portanto, vai precisar de um evento JavaScript onFocus ligado ao elemento. Por exemplo:
document.querySelector('.email').onfocus = function() {
    document.querySelector('.oculta').style.display = "none";
}

document.querySelector('.email').onfocusout = function() {
    document.querySelector('.oculta').style.display = "block";
}

Comment: Poxa amigo, muitíssimo obrigado. agora compreendo. Sim realmente funciona com o js. agradeço

duvida sobre ação css em div


Tests to Compare Sales Mix Percent between Periods

Question: Background
I wish to compare menu sales mix ratios for two periods.
A menu is defined as a collection of products. (i.e., a hamburger, a club sandwich, etc.)
A sales mix ratio is defined as a product's sales volume in units (i.e., 20 hamburgers) relative to the total number of menu units sold (i.e., 100 menu items were sold).  In the hamburger example, the sales mix ratio for hamburgers is 20% (20 burgers / 100 menu items). This represents the share of total menu unit sales.
A period is defined as a time range used for comparative purposes (i.e., lunch versus dinner, Mondays versus Fridays, etc.).
I am not interested in overall changes in the volume (I don't care whether I sold 20 hamburgers in one period and 25 in another).  I am only interested in changes in the distribution of the ratios (20% of my units sold were hamburgers in one period and 25% were hamburgers in another period).
Because the sales mix represents a share of the whole, the mean average for each period will be the same; the mean difference between the periods will always be 0%; and, the sum total for each set of data will always be 100%.
Objective:
Test whether the sales distribution (sales mix percentage of each menu item relative to other menu items) changed significantly from one period to another.
Null Hypothesis: the purchase patterns and preferences of customers in period A are the same as those for customers in period B.
Example of potential data input:
<code>[Menu Item]  [Period A]  [Period B]
Hamburger      25%          28%
Cheeseburger   25%          20%
Salad          20%          25%
Club Sandwich  30%          27%
</code>
Question:
Do common methods exist to test whether the distribution of share-of-total is significantly different between two sets of data?
A paired T-Test would have worked if I was measuring a change in the number of actual units sold, but not (I believe) for a change in share of total units.
I've been searching online and a few text books for a while with no luck.  I may be looking for the wrong terminology.
Any direction, be it search terms or (preferably) the actual names appropriate tests, are appreciated.
Thanks,
Andrew
EDIT: I am considering a Pearson Correlation test as a possible solution - forgetting that each row of data are independent menu items, the math shouldn't care.  A perfect match (identical sales mix) would receive a coefficient of 1 and the greater the change the lower the coefficient would be. One potential issue is that unlike a regular correlation test, the changes may be amplified because any change to one number automatically impacts the others. Is this a viable solution? If so, is there a way to temper the amplification issue?
Answer: Consider using a Chi Squared Goodness-of-Fit test as a simple solution to this problem:

H0: the proportion of menu items for month B is the same as month A
Ha: at least one of the proportions of menu items for month B is
  different to month A

There is a nice tutorial here.


Slow down player gradually using rigidbody?

Question: I'm making a 2D platformer and want the player to slowly  slow down after releasing the left/right buttons.
I haven't found any good solutions on the internet. Here is my code:
bool isSprinting =  Input.GetButton("Sprint");
float playerInput = Input.GetAxis("Horizontal");

        if(!isSprinting)
        {
            rb.velocity = new Vector2(playerInput * moveSpeed, rb.velocity.y);
        }
        else
        {
            rb.velocity = new Vector2(playerInput * runSpeed, rb.velocity.y);
        }

        if(rb.velocity.x > 0)
        {
            transform.localScale = Vector3.one;
        }
        else if(rb.velocity.x < 0)
        {
            transform.localScale = new Vector3(-1f, 1f, 1f);
        }

Answer: You can manually reduce the velocity, use Rigidbody2D.Drag, or use Input smoothening.
To manually slow down the Rigidbody2D, you could do something like the following. This should only be done in a FixedUpdate to keep consistent behavior even with varying frame rates.
const float SMALL_INPUT_CONSTANT = 0.01f;//increase to slow down even if a controller's joystick is slightly pressed
const float LERP_CONST_BETWEEN_0_AND_1 = 0.05f;//increase to slow down faster
if(Mathf.Abs(playerInput) < SMALL_INPUT_CONSTANT){
    rb.velocity = new Vector2(Mathf.Lerp(rb.velocity.x, 0, LERP_CONST_BETWEEN_0_AND_1), rb.velocity.y);
}
else
{
//insert other movement code here (the if(!isSprinting)...else... code you posted), because you shouldn't set the velocity if the user isn't giving `Horizontal` input
}

You can increase Rigidbody2D.Drag in the Editor, it's labeled as Linear Drag. This will make the Rigidbody2D fall like a feather, so only use it if that's what you want.

I haven't used Input smoothening, but I think it would be the Gravity variable in the Input Manager.


Understating the proof of the existence theorem of Poisson integral from Rudin

Question: I have some problem with the understanding of the following theorem from rudin:
Theorem $11.7$: If $f \in C(T)$ and if $Hf$ is defined on the closed unit disc $\bar U$ by
$$(Hf)(re^{i\theta})=\begin{cases}f(e^{i\theta})& r=1\\ P[f](re^{i\theta})& 0\le r<1 \end{cases} ,$$
then $Hf \in C(\bar U)$.
Now recall that $T=$Unit circle and $U=$ unit disc and $f\in L^1(T)$ then
$$P[f](re^{i\theta})=\frac{1}{2\pi} \int_{-\pi}^{\pi}P_r(\theta -t)f(t)dt$$
where $\displaystyle P_r(t)=\sum_{-\infty}^{\infty}r^{|n|}e^{int},~$ for $0\le r<1,~t \in \mathbb R$. Now proof of the above theorem given as:

Now I am not able to figure out one thing:
$(a)$ How did they get equation in $(5)$ by using $(4)$ for $r \neq 1?$ That is,  how to derive $(Hg)(re^{i\theta})=\displaystyle \sum_{n=-N}^{N} c_nr^{|n|}e^{in\theta}~$ from $~g(e^{i\theta}) = \displaystyle \sum_{n=-N}^{N} c_n e^{in\theta}~$ and using $(1)?$
Can you please help me to understand this? Thank you.
Answer: The proof of $Hg \in C(\overline U)$, from (4) onwards, is only for a trigonometric polynomial (i.e. a finite linear combination of the functions $e^{in\theta}$). At the end of the proof Rudin shows that this is true for every $f \in C(\overline U)$
Comment: Sir I got why $Hg \in C(\bar U)$, but I am not able to find the trigonometric sum equation in $(5)$ from $(4)$ and $(1)$. That is, how to derive $(Hg)(re^{i\theta})=\displaystyle \sum_{n=-N}^{N} c_nr^{|n|}e^{in\theta}$ from $g(e^{i\theta}) = \displaystyle \sum_{n=-N}^{N} c_n e^{in\theta}$
Comment: Compute $P[f](r e^{i\theta})$ when $f$ has the form $e^{in\theta}$ for some integer $n$. This is easy from the definition of $P_r(t)$.  Now take a finite linear combination of such $f$'s to write down  $Hg(re^{i\theta})$. That gives you (5). @abcdmath
Answer: Sorry, I had made wrong answer previously(, which is deleted now).
I was also just reading this part of the book today, and got confused.
Here is the correct answer.
The equation in the section 11.6 of the book, which is also referenced in 11.8, has an error.
$P[f](re^{i\theta})=\frac{1}{2\pi} \int_{-\pi}^{\pi}P_r(\theta -t)f(t)dt$
The $..\int_{-\pi}^{\pi}...f(t)dt$  part of the equation is wrong. The domain of $f$ is not $[{-\pi}, {\pi}]$.
$f\in L^1(T)$. Hence,  $f:T \to \mathbb{C}$,
The domain of $f$ is T = {$e^{it}$ | $t\in \mathbb{R}$ }, which is the unit circle on the complex plane.
Hence, the correct equation is this.
$P[f](re^{i\theta})=\frac{1}{2\pi} \int_{-\pi}^{\pi}P_r(\theta -t)f(e^{it})dt$
Now let, $g(e^{it}) =\displaystyle \sum_{m=-N}^{N} c_me^{imt}$
for $0 \le r \lt 1$,
$(Hg)(re^{i\theta})=P[g](re^{i\theta})=\frac{1}{2\pi} \int_{-\pi}^{\pi}P_r(\theta -t)g(e^{it})dt$
$=\frac{1}{2\pi} \int_{-\pi}^{\pi}P_r(\theta -t)\displaystyle \sum_{m=-N}^{N} c_me^{imt}dt$
$=\frac{1}{2\pi} \int_{-\pi}^{\pi}\displaystyle \sum_{m=-N}^{N} c_me^{imt}P_r(\theta -t)dt$
$=\frac{1}{2\pi} \int_{-\pi}^{\pi}\displaystyle \sum_{m=-N}^{N} c_me^{imt}\displaystyle \sum_{n=-\infty}^{\infty} r^{|n|}e^{in(\theta - t)}dt$
$=\frac{1}{2\pi} \int_{-\pi}^{\pi}\displaystyle \sum_{m=-N}^{N} c_m  \displaystyle \sum_{n=-\infty}^{\infty}r^{|n|}e^{in\theta + i(m-n)t) }dt$
$=\frac{1}{2\pi} \displaystyle \sum_{m=-N}^{N} c_m \displaystyle \sum_{n=-\infty}^{\infty} r^{|n|}e^{in\theta} \int_{-\pi}^{\pi} e^{i(m-n)t }dt$
$=\frac{1}{2\pi} \displaystyle \sum_{m=-N}^{N} c_m r^{|m|}e^{im\theta} \bullet {2\pi}$
$=\displaystyle \sum_{m=-N}^{N} c_m r^{|m|}e^{im\theta}$


iPhone - how do I add a navigation controller to a view?

Question: I currently have an application that does the the following:
S: Loads a view as a login screen to start with.
a: If login is successful I add a terms and conditions screen as a subview
b: If not successful I add a sign up form as a subview
F: Then I load the main part of my app on success of either of the a or b which is the part of the app where there is a navigation controller and a tab bar controller. This is set up in MainWindow.xib
S, a and b also have Nav bars but no navigation controllers as I didn't think I would need navigation control on the login screens.
However it turns out I do, I want to be able to have back navigation from both a and b to the initial login screen.
I have tried several ways of doing this including trying the following answers:
How to add navigation controller in View Based Application in iPhone?
How do you properly set up a secondary view to support a navigation Controller on the iPhone?
how to add navigation controller programatically?
But none of them work for me, they display the new Navigation controller over the login screen and dont load the a or b screens.
I'm guessing this is because I am adding them as subviews to my loginView and this is not the correct way to do this? My code is as follows:
<code> if(self.tcSubViewController == nil){

        TCSubViewController *_tcSubViewController = [[TCSubViewController alloc] initWithNibName:@"T&CView" bundle:[NSBundle mainBundle]];

        self.tcSubViewController = _tcSubViewController;

        [_tcSubViewController release];

    }
 [self.view addSubview:[tcSubViewController view]];
</code>
I'm guessing there's a fundamental flaw in the way my Login flows? I should be able to completely remove the LoginView and then display the Terms and conditions view without having to add it as  subview, shouldn't I?
Answer: Navigation controller philosophy is that you add only navigationController.view as UIWindow subview and it wil manage the rest by itself. You only need to push/pop viewControllers and their corresponding views will be added/removed from screen automatically.
sample code from my current application:
<code>HomeController *homeController = [[[HomeController alloc] init] autorelease];
self.controller = [[[UINavigationController alloc] initWithRootViewController:homeController] autorelease];
self.controller.navigationBarHidden = YES;
[self.window addSubview:self.controller.view];
[self.window makeKeyAndVisible];
</code>
and then to push next view you just add next controller:
<code>[self.navigationController pushViewController:newController animated:YES];
</code>
Comment: giving error:property controller not found in appdel...what is that controller?
Comment: It is UINavigationController. If you don't want to extend AppDelegate you can do it like:
HomeController *viewController = [[HomeController alloc] init];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
self.window.rootViewController = navigationController;
Answer: You need to dismiss the navigation controller to go back to.
To dismiss modal view:
1.Easy way: In your modal view in some method that you call to dismiss just add:
[self.navigationController dismissModalViewControllerAnimated:YES];
2.More complex way: Implement and delegate protocol on your modal view and make the view controller that presents the modal view the delegate of it. And in the delegate method dismiss the modal view. I do this way when I need to send data from modal view to the controller that present it.
Reference to this post
Comment: Sorry I meant to specify that a modal view is not the way I want to do it as I require a back button with the arrow shape to the left.


Convert a hex string to base64 in Julia

Question: I am trying to convert a hex string to base64 in Julia. I looked at Codecs.jl but I am not sure if that will help me.
The hex string I want to convert is 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d.
Not really sure where to start here so any suggestions are welcomed.
Answer: For this you want to use Base64 from the standard library. First use hex2bytes to convert your string to a byte array, then base64encode to convert it back to a  string:
using Base64
function base16to64(st::AbstractString)
    bytes = hex2bytes(st)
    return base64encode(bytes)
end

Comment: to go from a Base64 string to a hex string, `bytes2hex(base64decode(base64string))`

Convert a hex string to base64 in Julia


Prove that there exists number $k\in \mathbb{N}$ such that $ V = \operatorname{Ker}A^{k} \dot{+} \operatorname{Im}A^{k}$

Question: Problem:
Let A be linear operator A $\in L(V)$. Prove that there exists number $k\in \mathbb{N}$ such that $ V = \operatorname{Ker}A^{k} \dot{+} \operatorname{Im}A^{k}$. Then prove that operator $\left.A\right|_{\operatorname{Ker}A^{k}}$ is nilpotent and operator $\left.A\right|_{\operatorname{Im}A^{k}}$ is regular.
My attempt:
We know that $A$ can be written as sum of two operators: $A = N + S $ where $N$ is nilpotent and $S$ diagonalizable operator. Then I construct $A^k = \sum_{j=0}^{k} {k\choose j}S^{k-j}N^{j}$ where $k = \operatorname{ind}(N)$ but this does not give anything good.
I know that I need to show somehow that for every $v\in V$: $v=a+b, a\in \operatorname{Ker}A^k, b\in \operatorname{Im}A^k$ but I do not know how. I have no idea how to proceed.
Thanks for any help.
Comment: To prove the $\oplus$, try show that $\mathrm {Ker}(\mathcal A^k) \cap \mathrm {Im}(\mathcal A^k) = 0$.
Answer: Maybe an alternative.
$$
\DeclareMathOperator\Ker{Ker}
\DeclareMathOperator\im{Im}
$$
Assume $\dim V =n <\infty$. Then if $v \in V$ that $\mathcal A^k v = 0$ for some $k \in \mathbb N$, then $0= \mathcal A(\mathcal A^k v)=\mathcal A^{k+1}v$, thus $\Ker (\mathcal A^k) \subseteq \Ker (\mathcal A^{k+1})$. Also if $u  = \mathcal A^{k+1}v$, then $u = \mathcal A^k (\mathcal A v)$, hence $\im(\mathcal A^{k+1}) \subseteq \im (\mathcal A^k)$. Thus we have two chains
$$
0\subseteq \Ker \mathcal A \subseteq \Ker(\mathcal A^2) \subseteq \dots \subseteq \Ker(\mathcal A^m) \subseteq \cdots \subseteq V
$$
and
$$
V \supseteq \im\mathcal A \supseteq \im(\mathcal A^2) \supseteq \dots \supseteq \im(\mathcal A^m) \supseteq \cdots \supseteq 0.
$$
Hence we have the dimension of $\Ker (\mathcal A^j)$ increases, the dimension of $\im(\mathcal A^j)$ decreases. If either sequence of them is strictly monotonic, then they would be unbounded, contradicting the fact $\dim V <\infty$. So there exists some $k\in \mathbb N$ s.t. $\dim(\Ker(\mathcal A^k)) = \dim(\Ker(\mathcal A^{k+1}))$. Then for each $p\in \mathbb N^*$, if $\mathcal A^{k+p+1} v =0$, then $\mathcal A^{k+1} (\mathcal A^p v)$, i.e. $\mathcal A^p v \in \Ker(\mathcal A^{k+1}) = \Ker(\mathcal A^k)$, thus $\mathcal A^{p+k} v =0$. Thus $\Ker(\mathcal A^{p+k+1}) =  \Ker(\mathcal A^{p+k})$. Therefore $\Ker(\mathcal A^k) = \Ker(\mathcal A^{k+p})$ for all $p \in \mathbb N^*$. Now use the rank-nullity theorem, we have $\dim(\Ker(\mathcal A^j)) + \dim(\im(\mathcal A^j)) = \dim V$ for each $j \in \mathbb N$. Thus for the same $k$, $\im(\mathcal A^k) = \im (\mathcal A^{k+p})$ for each $p \in \mathbb N^*$.
Now we easy to see that $\mathcal A\vert_{\Ker(\mathcal A^k)}$ is nilpotent with index $k$: for each $u \in \Ker(\mathcal A^k)$, $\mathcal A^k u =0$. For $v \in \im(\mathcal A^k)$, there is some $w\in V$ that $v = \mathcal A^k w$. Suppose $\mathcal Av = 0$, then $\mathcal A^{k+1}w =0$, so $w \in \Ker (\mathcal A^{k+1}) = \Ker(\mathcal A^k)$, thus $v =\mathcal A^k w = 0$. Therefore $\mathcal A\vert_{\im(\mathcal A^k)}$ is invertible.
For the $\oplus$, we only need to show that $\Ker(\mathcal A^k) \cap \im(\mathcal A^k) =0$. Suppose $x$ is in this intersection, then $x = \mathcal A^k y$ for some $y\in V$. Also $\mathcal A^k x =0$, so $y \in \Ker(\mathcal A^{2k}) = \Ker(\mathcal A^k)$, i.e. $\mathcal A^k y = 0$, hence $x = 0$. Now the proof is completed.
Comment: This proof is remarkably beautiful, thank you very much.
Comment: @Thom You are welcome. Glad to help.
Answer: Hint: Note that $A = N \dot+ P$, where $N$ is nilpotent and $P$ is invertible.  With that, we have $A^k = 0 \dot + P^k$.
Answer: The problem asks you to decompose $V$ as $V=A^k(V) + A^{-k}(0)$. If you are familiar with the primary decomposition theorem and its proof, we can prove this statement using the very similar argument. Here's some details.
Let $m(t)=t^kp(t)$ be the minimal polynomial of $A$ where $\gcd(t^k, p(t)) = 1$. In case that $k=0$, $A$ is bijective and the statement holds trivially for $k=1$. So assume $k\geq 1$. Then, by Euclidean algorithm, we have for some $f,g \in \mathbb{F}[t]$,
$$
t^kf(t)+p(t)g(t)=1.
$$That is, we have
$$
A^kf(A)+p(A)g(A)=I,
$$and
$$
A^kf(A)v+p(A)g(A)v=v
$$for all $v\in V$. The first term $A^kf(A)v$ belongs to $A^k(V)$, and the latter term satisfies
$$A^k[p(A)g(A)v]=[A^kp(A)]g(A)v = 0,$$
hence belongs to $A^{-k}(0)$. This shows $V = A^k(V) + A^{-k}(0)$. Furthermore, dimension theorem says that $\dim V = \dim A^k(V) + \dim  A^{-k}(0)$, so the sum is direct.Now notice the fact that $V = A^k(V) \oplus A^{-k}(0)$ implies $$A^{2k}x =0 \Rightarrow A^k x=0.$$
We see that $A^k(V)$ and $A^{-k}(0)$ are both $A$-invariant. So $A$'s restrictions on both spaces are well-defined. If we write $T=A|_{A^{-k}(0)}$, it is straightforward that $T^k=0$, that is, $T$ is nilpotent. Finally, $S= A|_{A^k(V)}$ is regular if and only if
$$
Sv=0, v=A^kw\in A^k(V) \Rightarrow v=0.
$$This is also straightforward since
$$
Sv = Av = A^{k+1}w = 0 \Rightarrow A^{2k}w=0 \Rightarrow A^kw = 0\Leftrightarrow v=0.
$$


D7: How do export content types, module settings, taxonomy terms, webforms and other nodes?

Question: It seems D7 lacks an important feature for migrating data content types, module settings, taxonomy terms, webforms and other nodes.
I tried with Features modules but it seems it creates modules out of features and this is bad.
Where is Drupal CCK Content Copy Module  for Drupal 7?
Comment: Features create an exportable in a module because it is much easier than anything in the db. Not sure why you think it is bad?
Comment: It might be bad when you export from a multiple language website default english with content types interconnected with node references to a website that has default other language like in my case...
Answer: It is not bad.  It is preferable to store as much configuration as possible in code, so that it can be version-controlled and deployed easily elsewhere with Git etc..  Features makes this possible somewhat, but it is not yet feature-complete.  Some work that is still on-going:

Taxonomy terms: This will be implemented with a combination of Features and Deploy, but it is not quite ready.  See http://drupal.org/node/1245582#comment-5146834 for details.
Content type settings: A fair amount of this is now working, but Strongarm needs to be set up first for these to be exported with Features.  See Features does not capture important settings while exporting a content type for details.

As there is no more CCK in Drupal 7, that content-copy feature is no longer available.  We've moved onto Fields.  If you want a quick way to get bundles exported without getting into Features, check out the Bundle copy module.


Two data sets with different time instances on the same ChartJs chart

Question: My scenario:
A machine creates events ON, RELOAD, OFF on certain time instances.
It also sends sensor Heat data every hour, that may or may not be at time instances of events.
See sample data below.
events [10.30AM, 4.45PM, 6.15PM, 8PM]

Heat Data [11Am, 12PM,........., 7PM]

As you can see data points falls in different time ranges. Therefore, If I use example below, heat data will be totally miss aligned.
https://www.chartjs.org/samples/latest/scales/time/line-point-data.html
Is there a way to plot these two datasets accurately?
Answer: Simply define your data as points through an array of objects that have an x and an y property each.
data: [{
    x: new Date(),
    y: 1
}, {
    t: new Date(),
    y: 10
}]

Make sure to not define data.labels in this case.


Can I search for black pixels in a photo and find out where they are in the photo using python?

Question: I want to search for black pixels in a screenshot I took using pyautogui and I want to find the x and y location of those pixels using python so that I can move the mouse to the black pixels locations using pynput. I tried using imageio but I could not find a command that would do what I want. I asked this a few hours Ago but it was closed so I made the necessary edits to it.
Answer: Here is one way in Python/OpenCV/Numpy using np.argwhere on a thresholded image that isolates the black spots.

Read the input
Threshold using inRange on black and invert
Use np.argwhere to located the coordinates of the black pixels in the mask
Print the results

Input (4 black clusters near the 4 corners):

<code>import cv2
import numpy as np

# read input
img = cv2.imread("lena_black_spots.png")

low = (0,0,0)
high = (0,0,0)

mask = cv2.inRange(img, low, high)
mask = 255 - mask

# find black coordinates
coords = np.argwhere(mask==0)
for p in coords:
    pt = (p[0],p[1])
    print (pt)

# save output
cv2.imwrite('lena_black_spots_mask.png', mask)

cv2.imshow('img', img)
cv2.imshow('mask', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>

Mask:

Coordinates:
<code>(18, 218)
(18, 219)
(19, 218)
(19, 219)
(20, 218)
(20, 219)
(38, 21)
(38, 22)
(39, 21)
(39, 22)
(173, 244)
(173, 245)
(174, 244)
(174, 245)
(194, 23)
(194, 24)
(195, 23)
(195, 24)
</code>
Answer: I'd recommend looking into the ImageMagick library. That's the go-to library for working with images in Python.


Acessar método usando Traço (-) na URL CakePHP 3

Question: Tenho um método de assinatura: public function mostPopular() estou tentando acessa-lo via URL da seguinte forma: products/most-popular porém estou sendo direcionado para uma página de Erro:

The action most-popular is not defined in ProductsController

porém seguindo as convenções de nomes do CakePHP 3.0 não deveria acontecer este erro.
Arquivo de rotas (routes.php)
<?php

use Cake\Core\Plugin;
use Cake\Routing\Router;

/**
 * The default class to use for all routes
 *
 * The following route classes are supplied with CakePHP and are appropriate
 * to set as the default:
 *
 * - Route
 * - InflectedRoute
 * - DashedRoute
 *
 * If no call is made to `Router::defaultRouteClass`, the class used is
 * `Route` (`Cake\Routing\Route\Route`)
 *
 * Note that `Route` does not do any inflections on URLs which will result in
 * inconsistently cased URLs when used with `:plugin`, `:controller` and
 * `:action` markers.
 *
 */
Router::defaultRouteClass('Route');

Router::scope('/', function ($routes) {
    /**
     * Here, we are connecting '/' (base path) to a controller called 'Pages',
     * its action called 'display', and we pass a param to select the view file
     * to use (in this case, src/Template/Pages/home.ctp)...
     */
    $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);

    // tendo pages após o dominio (sequido de qualquer coisa) será redirecionado para o controller pages,
    // método display, qualquer coisa após o * será passado como parametro
    /**
     * ...and connect the rest of 'Pages' controller's URLs.
     */
    $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);

    /**
     * Connect catchall routes for all controllers.
     *
     * Using the argument `InflectedRoute`, the `fallbacks` method is a shortcut for
     *    `$routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'InflectedRoute']);`
     *    `$routes->connect('/:controller/:action/*', [], ['routeClass' => 'InflectedRoute']);`
     *
     * Any route class can be used with this method, such as:
     * - DashedRoute
     * - InflectedRoute
     * - Route
     * - Or your own route class
     *
     * You can remove these routes once you've connected the
     * routes you want in your application.
     */
    $routes->fallbacks('InflectedRoute');
});

/**
 * Load all plugin routes.  See the Plugin documentation on
 * how to customize the loading of plugin routes.
 */
Plugin::routes();

Código do método mostPopular():
public function mostPopular()
{
    $this->layout = false;
    if($this->request->is('post'))
    {
        $productsQuantity = 4;
        $order = 'DESC';
        $column = 'visited';
        $subCategoryId = $this->request->data['subCategory'];
        $productsMostPopular = $this->Search->listProductsByTrend($subCategoryId, $productsQuantity, $column, $order);
        //$this->set('productsMostPopular', $productsMostPopular);
        //$this->set('_serialize',array('productsMostPopular'));
        echo json_encode($subCategoryId);
    }
}

OBS: Estou usando o CakePHP 3.0
Comment: Acho que no cakephp 2 não era assim :)
Comment: Se não me engano você  não vai conseguir acessar o método dessa forma, somente conseguirá acessar se for nomeDoMetodo
Comment: @AndréBaill o problema é que segundo a documentação da forma que fiz está suportado pelo CakePHP
Comment: Puts, o Laravel por padrão vem com essa conversão :)
Comment: @WallaceMaxters por padrão o Cake também tem
Comment: @WallaceMaxters o CakePHP 3 mudou muita coisa
Comment: @Ricardo pode partilhar o link da doc onde viu?
Answer: Consegui fazer com que o CakePHP 3 usa-se o comportamento Default de rotas tracejadas mudando o paramentro do método fallbacks para 'DashedRoute' por padrão as rotas vem com $routes->fallbacks('InflectedRoute');
$routes->fallbacks('DashedRoute');


How to display comment status with radio buttons?

Question: How can I display the comment status (open and close) with radio buttons in the comment submit page? I want it be selectable during comment submission by the user.

Actually, I have a content type which has an comment field with two radio buttons:

Satisfied
Unsatisfied

My goal is that, when users select the "Satisfied" button, the comment will be closed automatically; when the "Unsatisfied" button is selected, the users are able to send the next comment.
Comment: welcome to Drupal Answers, your question appears to lack clarity on what you are trying to achieve here, please elaborate on the workflow that you wish to accomplish and where you are stuck in trying to do so.
Comment: It looks to me like you want some sort of [voting](https://www.drupal.org/search/site/vote?f[0]=ss_meta_type%3Amodule) process, with a way to explain the choice made. Is that correct?
Answer: I think you have to use rate module for your comment, then use Rules module to close the comment on specific node.


which one has better performance to load views

Question: When I want to print my views block result(or views) in my tpl files,I have several ways,
views_embed_view
views_get_view
module_invoke for block ( I means something like $block = module_invoke('views', 'block', 'view', 'map-block_1'); )
which one is better and has better performance?
Answer: views_embed_view is just a wrapper for views_get_view:
function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);
}

So how would you set dynamic arguments on views_embed_view? With views_get_view you can at least do this:
  $view = views_get_view($view_name);
  if (!$view || !$view->access($display_id)) {
    return;
  }
  $view->set_display($display_id);
  $view->set_arguments($variables);
  $view->pre_execute();
  $view->execute();
  return $view->render();

module_invoke for block is too roundabout and limited for my liking. Why limit yourself to a block when you can choose from any display available?
views_block_view contains this snippet:
if ($view = views_get_view($name)) {

So it also uses Views_get_view.
Performance-wise I reckon the differences are negligible.
So, IMO, views_get_view wins.


Multiple conditions not working in PHP

Question: I'm making a test for my minecraft whitelist, I have 15 questions and every value of question must be = yes, when I have 6 conditions of questions (question1 - question6) , everything is ok and working! But when I add more than 6 conditions (I need 15 conditions for value "yes"), the script not working
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Whitelist</title>

<title>Chunk.cz - Whitelist</title>

<?php

$ip = 'xx.xx.xx.xx';

$question1 = $_POST['question1'];
$question2 = $_POST['question2'];
$question3 = $_POST['question3'];
$question4 = $_POST['question4'];
$question5 = $_POST['question5'];
$question6 = $_POST['question6'];
$question7 = $_POST['question7'];

$player = $_POST['player'];

if (!empty($_POST['player'])) {

   if ($question1 == "yes" && $question2 == "yes" && $question3 == "yes" && $question4 == "yes" && $question5 == "yes" && $question6 == "yes" && $question7 == "yes") {

  if(!in_array($param,$bad)) {

      echo '
';
      echo '

';
      echo '
Byl si přidán na whitelist pod nickem: ', $hrac;
      echo '
IP serveru: ';
      echo '', $ip;
      echo '

';

                            $connect = mysql_connect("xx.xx.xx.xx","xxxxxx","xxxxxx");
                            if (!$connect)
                            {
                            die("NELZE SE PRIPOJIT DO DATABAZE! PROSIM OPAKUJTE POKUS POZDEJI. DEKUJI ZA POCHOPENI.");
                            }

                            $DB = mysql_select_db('chunk');

                            if(!$DB)
                            {
                            die("MySQL nemuze vybrat databazi!");
                            }

                            if(!mysql_query("INSERT INTO whitelist (name)
                            VALUES ('$player')"))
                            {
                            die("Zadost nebyla podana, nemuzeme se spojit s databazi. Omlouvame se, zkuste to pozdeji.)");
                            }

    }
    else { // Špatná odpovìï
      echo '
';
      echo '

';
      echo '
Máš něco špatně, zkus to znova

';
      echo '<input type=button onclick="history.back()" value="Zkusit znova">';
      echo '

';
    }
}
else {
  echo '

  <form method="POST">

          Napiš svůj nick z minecraft.net:

<input type="text" name="hrac">

    ', /* Zaèátek otázek */'

      1. Co je to griefing?

<input type="radio" name="question1" value="no"> To je příkaz pouze pro administrátory, množí si tak materiál.

<input type="radio" name="question1" value="no"> Group briefing - plugin na "schůze" v chatu - vytváří soukromé chatové kanály.

<input type="radio" name="question1" value="yes"> Úmyslné způsobování škody jiným hráčům jakýmkoliv způsobem. Obvykle jde o ničení staveb.

      2. Když se chci k někomu podívat do domu:

<input type="radio" name="question2" value="no"> Pomocí bugu obejdu zamčené dveře, stejně nikdo nic nopozná.

<input type="radio" name="question2" value="yes"> Požádám majitele domu, jestli by mě dál nopozval.

<input type="radio" name="question2" value="no"> Nakouknu dovnitř tak, abych nomusel nic ničit, a pokud se mu to nolíbí, okamžitě odejdu.

<input type="radio" name="question2" value="ne"> Prokopu se dovnitř a díru zase zacpu.

      3. Jaké mody (modifikace hry) nejsou na serveru zakázané?

<input type="radio" name="question3" value="ne"> Na serveru nejsou zakázané žádné mody.

<input type="radio" name="question3" value="ne"> X-ray.

<input type="radio" name="question3" value="yes"> Optifine, Minimapy.

<input type="radio" name="question3" value="ne"> Smart moving.

      4. Jakým příkazem zjistím, kolik mám zrovna peněz?

<input type="radio" name="question4" value="ne"> Napíšu moderátorovi, on mi to řekne.

<input type="radio" name="question4" value="ne"> Na serveru nejsou žádné peníze, jen výměnný obchod.

<input type="radio" name="question4" value="ne"> /penize

<input type="radio" name="question4" value="yes"> /money

      5. K čemu především slouží redstone?

<input type="radio" name="question5" value="yes"> K vytváření "elektrických drátů" v logických obvodech (například na připojení dveří na páku, která je otevře).

<input type="radio" name="question5" value="ne"> K ničemu, má jen zpomalovat kopání.

<input type="radio" name="question5" value="ne"> K výrobě nástrojů.

      6. Co je hlavním úkolem moderátorů?

<input type="radio" name="question6" value="ne"> Stavět obří projekty.

<input type="radio" name="question6" value="ne"> Teleportovat hráče na požádání.

<input type="radio" name="question6" value="yes"> Dohlížet na dodržování pravidel ve hře.

<input type="radio" name="question6" value="ne"> Rozdávat bany lidem, kteří jim odporují nebo se jim nelíbí.

      7. Jak správně natěžím dřevo?

<input type="radio" name="question7" value"ne"> Stačí dřevo na které dosáhnu, zbytek shnije.

<input type="radio" name="question7" value"ne"> Pokácím celý strom tak, aby nezůstalo vůbec žádné dřevo ani listí.

<input type="radio" name="question7" value"yes"> Vykácím všechno dřevo, listí nechám a namísto kmenu dám sazeničku.

<input type="radio" name="question7" value"ne"> Alespoň jeden kousek dřeva se musí nechat, aby strom dorostl.

', /*
Pokud budete chtít pøidat další otázku, tak pøipište:

      #. Nadpis Otázky:

<input type="radio" name="question#" value"ne"> Špatná odpovìï

<input type="radio" name="question#" value"yes"> Správná odpovìï

<input type="radio" name="question#" value"ne"> Špatná odpovìï

(všechny znaky "#" nahraïte poøadím otázky (napø pro 7. otázku èíslem 7))
(hodnota value mùže být yes/ne , u správné odpovìdi dejte yes (správná odpoveï mùže být pouze 1!))
*/'
    ', /* Konec otázek */'

Stisknutím tlačítka potvrzujete, že souhlasíte s pravidly serveru
<input type="submit" value="Odeslat požadavek">

</form>
';
}

?>

here is the line of conditions
if ($question1 == "yes" && $question2 == "yes" && $question3 == "yes" && $question4 == "yes" && $question5 == "yes" && $question6 == "yes" && $question7 == "yes") {

when it is like this, it works:
if ($question1 == "yes" && $question2 == "yes" && $question3 == "yes" && $question4 == "yes" && $question5 == "yes" && $question6 == "yes") {

but when I add more conditions, its not working
if ($question1 == "yes" && $question2 == "yes" && $question3 == "yes" && $question4 == "yes" && $question5 == "yes" && $question6 == "yes" && $question7 == "yes" && $question8 == "yes" && $question9 == "yes" && $question10 == "yes" ..........) {

thank you very much for help! this is for minecraft whitelist, sorry for my bad english
Comment: that is your karma for bad code design, i think you have a typo somewhere
Comment: Do you know how many questions here?
Comment: oh... `else {
  echo '` use `else { ?>` because you will prbably get problems friom it, now my bet is that if you print_r($_POST); you will see only 6 q-ns :)
Answer: I'm not sure why adding more conditions makes your code not work, but you could do something like this:

$answers=array('question1'=>yes,'question2'=>yes,'question3'=>no); //array of the answers received
$count=0;
$requiredCount=3;
foreach ($answers as $key=>$value){
   if ($value=='yes'){
    $count++;
   }
}
if ($count==$requiredCount)
{
//process as valid
}else{
//process as not valid
}

Of course you'd want tabs in the appropriate places to make your code more readable, alas, they get stripped out here.

Multiple conditions not working in PHP


How to make shiny 'showNotification' scrollable?

Question: I have a shiny showNotification which prints warnings and errors. Mostly it works well but sometimes there are a lot of warnings or really long warnings and the user can't see them all. How can I get showNotification to scroll vertically?
Here is a reprex of my problem.
library(shiny)

shinyApp(
  ui = fluidPage(
    actionButton("show", "Show")
  ),
  server = function(input, output) {
    observeEvent(input$show, {
      showNotification(
        "R version 4.3.0 (2023-04-21 ucrt) -- Already Tomorrow
        Copyright (C) 2023 The R Foundation for Statistical Computing
        Platform: x86_64-w64-mingw32/x64 (64-bit)

        R is free software and comes with ABSOLUTELY NO WARRANTY.
        You are welcome to redistribute it under certain conditions.
        Type 'license()' or 'licence()' for distribution details.

        R is a collaborative project with many contributors.
        Type 'contributors()' for more information and
        'citation()' on how to cite R or R packages in publications.

        Type 'demo()' for some demos, 'help()' for on-line help, or
        'help.start()' for an HTML browser interface to help.
        Type 'q()' to quit R.

        R version 4.3.0 (2023-04-21 ucrt) -- Already Tomorrow
        Copyright (C) 2023 The R Foundation for Statistical Computing
        Platform: x86_64-w64-mingw32/x64 (64-bit)

        R is free software and comes with ABSOLUTELY NO WARRANTY.
        You are welcome to redistribute it under certain conditions.
        Type 'license()' or 'licence()' for distribution details.

        R is a collaborative project with many contributors.
        Type 'contributors()' for more information and
        'citation()' on how to cite R or R packages in publications.

        Type 'demo()' for some demos, 'help()' for on-line help, or
        'help.start()' for an HTML browser interface to help.
        Type 'q()' to quit R.

        R version 4.3.0 (2023-04-21 ucrt) -- Already Tomorrow
        Copyright (C) 2023 The R Foundation for Statistical Computing
        Platform: x86_64-w64-mingw32/x64 (64-bit)

        R is free software and comes with ABSOLUTELY NO WARRANTY.
        You are welcome to redistribute it under certain conditions.
        Type 'license()' or 'licence()' for distribution details.

        R is a collaborative project with many contributors.
        Type 'contributors()' for more information and
        'citation()' on how to cite R or R packages in publications.

        Type 'demo()' for some demos, 'help()' for on-line help, or
        'help.start()' for an HTML browser interface to help.
        Type 'q()' to quit R.

        R version 4.3.0 (2023-04-21 ucrt) -- Already Tomorrow
        Copyright (C) 2023 The R Foundation for Statistical Computing
        Platform: x86_64-w64-mingw32/x64 (64-bit)

        R is free software and comes with ABSOLUTELY NO WARRANTY.
        You are welcome to redistribute it under certain conditions.
        Type 'license()' or 'licence()' for distribution details.

        R is a collaborative project with many contributors.
        Type 'contributors()' for more information and
        'citation()' on how to cite R or R packages in publications.

        Type 'demo()' for some demos, 'help()' for on-line help, or
        'help.start()' for an HTML browser interface to help.
        Type 'q()' to quit R.

        R version 4.3.0 (2023-04-21 ucrt) -- Already Tomorrow
        Copyright (C) 2023 The R Foundation for Statistical Computing
        Platform: x86_64-w64-mingw32/x64 (64-bit)

        R is free software and comes with ABSOLUTELY NO WARRANTY.
        You are welcome to redistribute it under certain conditions.
        Type 'license()' or 'licence()' for distribution details.

        R is a collaborative project with many contributors.
        Type 'contributors()' for more information and
        'citation()' on how to cite R or R packages in publications.

        Type 'demo()' for some demos, 'help()' for on-line help, or
        'help.start()' for an HTML browser interface to help.
        Type 'q()' to quit R."
      )
    })
  }
)

Answer: You can add some CSS to your ui in order to style the selector .shiny-notification. The key here is to define overflow: auto; for making it scrollable.
    ui = fluidPage(actionButton("show", "Show"),
                   tags$head(tags$style(
                       HTML(
                           ".shiny-notification {
                                position:fixed;
                                top: 10px;
                                bottom: 0px;
                                left: 300px;
                                right: 300px;
                                overflow: auto;
                            }
                           "
                       )
                   ))),


What's the best way to mix remote expect scripts and local bash commands?

Question: I'm automating tasks on a local and remote machine (behind a firewall). Once I'm done with tasks on the remote machine, I'd like the script to return to executing commands on the local machine.
#!/usr/bin/expect -f
set timeout -1
spawn ssh username@host
expect "Password: "
send "mypassword\r"
expect "username@host:~$"
...do some stuff...
send "exit\r"
expect eof

[then, once on the local machine, change directories and do other things]

What's the best way to append bash commands? I suppose I could start with bash, call expect within it, then simply return to bash once expect is done.
Comment: That's what I would suggest. Run the expect script from a bash scdript.
Answer: Expect is based on Tcl, so it can run the same commands. But if your goal is to run bash commands, the best bet is to run them from bash as a separate script, exactly as you propose in your last sentence.
Answer: It really depends on what your idea of ...do some stuff... is. Here's an example of something I recently did from my OSX w/s to an AWS instance
 export all_status
 init_scripts=($(ssh -q me@somehost 'ls /etc/init.d'))
 for this_init in ${init_scripts[@]};do
    all_status="${all_status}"$'\n\n'"${this_init}"$'\n'"$(ssh -q somehost \'sudo /etc/init.d/${this_init} status\')"
 done
 echo "$all_status" > ~/somehost_StatusReport.txt
 unset all_status

Passing a command at the end of the ssh command will cause the command to be run on the remote host. Or you can scp a script to the remote host and run it with
 ssh somehost '/home/me/myscript'

Answer: I met this situation recently too. I make a shell supexpect.sh which could login and execute command automatically. It will return to your local shell at the end.
#!/usr/bin/expect
#Usage:supexpect <host ip> <ssh username> <ssh password> <commands>
set timeout 60
spawn ssh [lindex $argv 1]@[lindex $argv 0] [lindex $argv 3]
expect "yes/no" {
    send "yes\r"
    expect "*?assword" { send "[lindex $argv 2]\r" }
    } "*?assword" { send "[lindex $argv 2]\r" }
send "exit\r"
expect eof

To execute:
./supexpect.sh 10.89.114.132 username password "ls -a;pwd;your_stuff_on_remote_host"

Note:
The prompt might need to adapt to your own system, and of course you need to pass execute permission to it.


Find a recurrence relation for a(n) for the number of bees

Question: Find a recurrence relation for a(n) for the number of bees in the nth previous generation of a male bee, if a male bee is born asexually from a single female and a female bee has the normal male and female parents. Given a(1) = 1, a(2) = 2, a(3) = 3.
Can someone show me how to solve this?
Answer: I will assume that each parent is unique, that they sire exactly one offspring each (together in the case of male and female), all mating for a generation coincides and occurs simultaneously according to a set schedule, and they die immediately after.
$a(n)$ is the total number of bees in a generation.
Notice that the number of female bees in a generation is precisely the number of bees in the younger generation since every bee has a mother (possibly a father too but irrelevant for now).
We get then the nice fact that among the $a(n)$ bees, precisely $a(n-1)$ of them are female and the remaining $a(n)-a(n-1)$ are male.
Now, for the next generation, each female bee from the current generation contributes two bees to the total for the next generation while each male from the current generation contributes one bee to the total for the next generation.

 We get then $a(n+1) = 2\cdot \underbrace{a(n-1)}_{\#female} + 1\cdot \underbrace{(a(n)-a(n-1))}_{\#male} = a(n)+a(n-1)$, and we recognize now that our sequence is simply the Fibonacci sequence with possible shifting.
Comment: @amd the first is male.  Let's call him Buzz and he is generation zero.  Buzz has one mother so $a(1)=1$.  Then Buzz's mother has two parents since she is female, $a(2)=2$.  Finally, Buzz's mother's mother has both a mother and a father while Buzz's mother's father has only a mother, giving $a(3)=3$ total ancestors in the third generation.
Comment: Ah. I missed that we're looking at ancestors.
Comment: thank you for explaining it so clearly @JMoravitz


Is there a quick way to add translation key to all locales

Question: There are translations in 5 languages in my app. Each language has one corresponding file. Adding new translation key in every one of them by hand is very inefficient. How do you solve this problem? Maybe someone has written script for or know Rails command for this purpose?
Answer: You can manage this translations and keep all keys in sync between with this gem i18n-tasks. This gem also support auto fill missing keys.
i18n-tasks health

So all you had to do is add one key to one file, and auto fill missing keys in other files.
 i18n-tasks add-missing


why &p+1 give the same result as p

Question:     #include <stdio.h>
    int main(void)
    {
        int a[]= {15, 14, 34, 46, 69, 86, 10, 0, 4};
        int *p = a; // p point to the first element of array a[0]
        printf("%x\n%x\n",&p+1, &a[0]);
        return 0;
    }

that code will print as example
bff0e554
bff0e554

so &p+1 return the address of the first element of array.
As i understand, &p return the address of that pointer and &p+1 should print the address of pointer + 1 please tell me what i missed !!
Comment: Coincidence.  You're confusing `p+1` and `&p+1`.  It just so happens that `p` is stored such that one after `p` is the start of the array.  Reverse the order of the declarations, or introduce another array in between, or some other pointers, or almost anything that changes the layout of the variables on the stack and your printed values will no longer match – it's coincidence that they do.
Comment: An array is not a pointer is not an array. `&p` is the **address** of `p`.
Comment: @JonathanLeffler; It may be a coincidence, but you shouldn't ignore UB at this place.
Answer: &p takes the address of p, not the value of p. That for you &p + 1 == a is pure coincidence and depends on your stack alignment. Your compiler could have sorted the both variables in another order or put a gap in between.
Comment: Actually there is not even a requirement to have a stack.
Answer: That's a funny one. Write down precisely what &p+1 means. It has nothing to do with any addresses in the array a. What it prints is pure coincidence.
Add another array b. Then set p = b and print &p + 1 and &b [0]. Maybe you figure out what happens.
Comment: as you and Kay says it's pure coincidence, i have declared the pointer first then the result has changed. btw (this was an exercice proposed by a teacher, he says that &p+1 == &a[0] in the solution -_-)
Comment: Tell your teacher to make `p` a global (while still letting `a` be a local) and have him explain why `&p+1` is nowhere in the vicinity of `a`. (Though first check what the teacher said, you may just find that you didn't interpret it correctly.)
Answer: An array is not a pointer is not an array.
&p is the address of p, not the address it contains (i.e. its value), which would be p (FYI: the value of the object it points to is *p). Similarly, &a[0] is the address of the first element in the array. It is pure coincidence the array is at the next address location (&p +1).
Additionally, the correct printf conversion-specifier for pointers is %p and it expects a void * (you are required to cast here, because that is a variadic function). Using a different specifier invokes undefined behaviour.
You should enable compiler warnings. Modern compilers will warn about such fundamental mismatches of types between the printf (and scanf) format strings and the arguments.
Comment: @CharlieMartin: I did not write anything else. For the question and my answer it does not even matter they are the same. However, e.g. `&a` and `&a[0]` are still different types, so it very well matters - just not here (and I do not even refer to this). I'm very confident I do know C very well and certainly did not have a "fancier memory model" in mind. How would you read this from the answer?
Comment: @CharlieMartin: I'd really be interested to understand what you consider "*Nonsense*" with this answer?
Comment: Nonsense. You're thinking of languages with a fancier memory model. In C, an array is simply a block of allocated memory. The address of the first element, and the address of the array are identical, and (modulo an edge condition with externs) `*(p+i) == a[i]`.
Comment: @CharlieMartin: But I appreciate unqualified downvotes. I'm not on your lawn!
Answer: Check that you're running what you think you are. I just tried it, and it worked.
bash $ cc -o foo foo.c
foo.c:6:23: warning: format specifies type 'unsigned int' but the argument has type
      'int **' [-Wformat]
    printf("%x\n%x\n",&p+1, &a[0]);
            ~~        ^~~~
foo.c:6:29: warning: format specifies type 'unsigned int' but the argument has type
      'int *' [-Wformat]
    printf("%x\n%x\n",&p+1, &a[0]);
                ~~          ^~~~~
2 warnings generated.
bash $ ./foo
58af0888
58af0890
bash $

Observe the warnings, btw.
Comment: Quite rectified. You did not address the UB, nor did you explain why **OP** sees the same value or why you don't.
Comment: And yes, we just had a couple of downvotes for showing the results of compiling the code given.
Comment: @CharlieMartin the OP expects the first value to reveal the address of `a[1]` and the second to reveal the address of `a[0]`. The second value is explicit ground truth, but the first value should be the second value plus the size of an int... that's not the values you're getting.
Comment: I executed the program as he gave it, by copy and paste. I don't know what he's doing, but the program as written gives the results shown.
Comment: @CharlieMartin exactly. The results shown are clearly inappropriate for what he's posted he's trying to accomplish (which is not necessarily clear based on his choice of wording, but becomes more clear when analyzing why he might have accepted the answer he did). The OP was under the mistaken impression that `&p+1 == &a[1]`, which is not a reasonable position for him to have taken.

why &p+1 give the same result as p


JDBC: Query results and add batch into another table

Question: I have some mySQL tables: "books", "task" and "task_items". I'm building an REST API (Java) that allow users to create tasks (basically edit fields) with some books. When user creates a new task, I'm creating a new row in task table, getting the last ID, selecting some books and add all of it into task_items table. Something like this:
Table books:
ID   TITLE   AUTHOR
1    Book A  John
2    Book B  Doe

Table task
ID   NAME   DATE
Empty at begining

Table task_items
ID   TASK_ID   BOOK_ID   TITLE   AUTHOR
Empty at begining

When user access api/task/newtask, I'm doing something like this:
// Creating task and return it's ID, everything works well
conn.setAutoCommit(false);
query = conn.pareStatement(INSERT INTO task VALUES ("New task", NOW()), Statement.RETURN_GENERATED_KEYS);
query.execute();
ResultSet rs = query.getGeneratedKeys();
if (rs.next()) {
    taskId = rs.getInt(1);
}
else {
    conn.rollback();
    return false; // can't create task
}

// Selecting some (or all) books
query = conn.prepareStatement("SELECT * FROM books");
ResultSet rs = query.executeQuery();

if (!rs.isBeforeFirst()) {
    conn.rollback();
    return false; // no books
}

// There's some books, insert them into task_items with taskId
// TODO

return true;

So, I have to insert batch the resultSet from the SELECT query into task_items, including taskID (with is commom to all rows). I dont't know how to do that (the TODO part). I would be grateful for any help.
Comment: Where is `conn.pareStatement()` coming from?  Are you using java.sql.Connection here?
Comment: I just simplified my code. In fact, api/task/newtask is a method called createTask that's call int getNewTask(conn) and int cretateTaskItems(conn).
Answer: I got it. The "TODO" part should b like that:
// There's some books, insert them into task_items with taskId
rs = query.executeQuery();
query = conn
            .prepareStatement("INSERT INTO task_items"
                    + "(TASK_ID, BOOK_ID, TITLE, AUTHOR)"
                    + "VALUES"
                    + "(?, ?, ?, ?)");

    while (rs.next()) {
        query.setInt(1, taskId);
        query.setInt(2, rs.getInt("ID"));
        query.setString(3, rs.getString("TITLE"));
        query.setString(4, rs.getString("AUTHOR"));

        query.addBatch();
    }

    System.out.println("executing batch...");

    query.executeBatch();

    System.out.println("batch executed");
    query.close();

    ...


Proving the probability integral transform without assuming that the CDF is strictly increasing

Question: I know that the proof of the probability integral transform has been given multiple times on this site. However, the proofs I found use the hypothesis that the CDF $F_X(x)$ is strictly increasing (together, of course, with the hypothesis that $X$ is a continuous random variable). I know that actually the only required hypothesis is that $X$ is a continuous random variable, and strict monotonicity is not required. Can you show me how?
Since I'm already here, I also take the occasion to ask for a simple application of the probability integral transform :) can you show me that, if $X$ has CDF $F_X(x)$ and $Y$ is the truncation of $X$ to $[a,b]$, then $Y$ is distributed as  $F_X^{-1}(U)$ where $U\sim[F_X(a),F_X(b)]$?
Comment: if you would be so kind, in the proof of your link, could you point to where the requirement that $F_X(x)$ has to be strictly increasing. Thanks!
Comment: Of course there is. The random variable whose pdf is equal to 1/2 in [0,0.5], 0 in [0.5,1] and 1/2 in [1,1.5], has a CDF which is continuous, but is not strictly increasing.
Comment: @Erosennin, the proof assumes the existence of the inverse of $F_X(x)$.
Comment: The hard part is dealing with the non-absolutely continuous part of $F$. The idea is made clear by considering the extreme case of discrete $F$.  At http://stats.stackexchange.com/a/36246/919 I give an algorithm that implements the probability integral transform in that case (as well as supplying working code). Emulating that algorithm for arbitrary $F$ will answer your question.
Comment: Thanks! But is there ever a CDF that is not strictly increasing? You have probably already thought of this, though...
Comment: @Erosennin consider any discrete random variable for example - F is a step function, which is not strictly increasing.
Comment: thanks guys , @Glen_b bit emberrased I didnt think of discrete distributions
Answer: In the wikipedia link provided by the OP, the probability integral transform in the univariate case is given as follows

Suppose that a random variable $X$ has a continuous distribution for which the cumulative distribution function(CDF) is $F_X$. Then the random variable $Y=F_X(X)$ has a uniform distribution.
PROOF
  Given any random variable $X$, define $Y = F_X (X)$. Then:
$$ \begin{align} F_Y (y) &= \operatorname{Prob}(Y\leq y) \\
         &= \operatorname{Prob}(F_X (X)\leq y) \\
         &= \operatorname{Prob}(X\leq F^{-1}_X (y)) \\
         &= F_X (F^{-1}_X (y)) \\
         &= y \end{align} $$
$F_Y$ is just the CDF of a $\mathrm{Uniform}(0,1)$ random variable.
  Thus, $Y$ has a uniform distribution on the interval $[0, 1]$.

The problem with the above is that it is not made clear what the symbol $F_X^{-1}$ represents. If it represented the "usual" inverse (that exists only for bijections), then the above proof would hold only for continuous and strictly increasing CDFs. But this is not the case, since for any CDF we work with the quantile function (which is essentially a generalized inverse),
$$F_Z^{-1}(t) \equiv \inf  \{z : F_Z(z) \geq t \}, \;\;t\in (0,1)$$
Under this definition the wikipedia series of equalities continue to hold, for continuous CDFs. The critical equality is
$$\operatorname{Prob}(X\leq F^{-1}_{X} (y)) = \operatorname{Prob}(X\leq \inf  \{x : F_X(x) \geq y \})= \operatorname{Prob}(F_X (X)\leq y)$$
which holds because we are examining a continuous  CDF. This in practice means that its graph is continuous (and without vertical parts, since it is a function and not a correspondence). In turn, these imply that the infimum (the value of inf{...}), denote it $x(y)$, will always be such that $F_X(x(y)) = y$.
The rest is immediate.
Regarding CDFs of discrete (or mixed) distributions, it is not (cannot be) true that $Y=F_X(X)$ follows a uniform $U(0,1)$, but it is still true that the random variable $Z=F_{X}^{-1}(U)$ has distribution function $F_X$ (so the inverse transform sampling can still be used). A proof can be found in Shorack, G. R. (2000). Probability for statisticians. ch.7.
Comment: +1 A similar proof is also provided on pg. 54 of Casella and Berger's Statistical Inference, second edition.
Comment: @Analyst1 Thanks, it's good to have multiple references.


Lista de arquivos dá erros ao passar por .decode()

Question: No seguinte código para transferência de arquivos utilizando sockets em Python:
Cliente:
lista_arquivos = ['C:\Users\fulano\Imagens\passaro.jpg', 'C:\Users\fulano\Imagens\cachorro.jpg', 'C:\Users\fulano\Imagens\gato.jpg']

    def transferir_arquivos(self):

        for arquivo in self.lista_arquivos:
            print(arquivo)
            host = socket.gethostname()
            port = 9000
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((host, port))
            # enviado o nome do arquivo
            nome_arquivo = os.path.basename(arquivo)
            s.send(nome_arquivo.encode('utf-8'))
            # próprio arquivo enviado
            with open(f'{arquivo}', 'rb') as arq:
                print(f"Transferindo {arquivo}")
                s.send(arq.read())
                print("Arquivo enviado")
                s.close()
                arq.close()
        self.excluir_lista()

Servidor:
serversock = socket.socket() host = socket.gethostname() port = 9000 serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversock.bind((host, port)) serversock.listen(5)

while True:
    clientsocket, address = serversock.accept()
    print("Got a connection from %s" % str(address))
    dados = clientsocket.recv(32)
    print(dados) # mostra o conteudo de dados
    nome = dados.decode()
    print(f"Nome: {nome}")
    with open(nome, 'wb') as f:
        print('arquivo aberto')
        print('Recebendo dados...')
        data = clientsocket.recv(301149653)
        f.write(data)
        print("Enviando")
        f.close()
        print('Transferencia Completa!!!') clientsocket.close() print('conexão encerrada')

É retornado o seguinte quando chega no segundo item da lista:
Got a connection from ('meu_ip', 55159)
b'passaro.jpg'
Nome: passaro.jpg
arquivo aberto
Recebendo dados...
Enviando
Transferencia Completa!!!
Got a connection from ('meu_ip', 55160)
b'cachorro.jpg\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00\xff'
Traceback (most recent call last):
  File ".\server_side.py", line 17, in <module>
    nome = dados.decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 11: invalid start byte

Comment: Geralmente não especifico a encodificação, mas se serve de ajuda, github.com/Diolante/Servidor-Web-Simples-em-Python
Answer: O erro é que você está presumindo que o recv() só vai receber os bytes enviados por um comando send(). Mas o TCP não enquadra as mensagens, é tudo uma tripa de bytes, então seu recv() está recebendo o nome do arquivo (do primeiro send) e também um pedaço do conteúdo do arquivo (segundo send).
Para fazer funcionar com o menor número possível de alterações, sugiro que você transforme o nome do arquivo numa string de 32 bytes fixos:
   d = arquivo.encode('utf8')
   d = d + (b" " * (32 - len(d)))
   s.send(d)

No outro lado, você continua fazendo recv(32), que vai receber os 32 bytes esperados, e remove os espaços fazendo
nome = dados.decode().strip()

Mas tendo em mente que é uma solução porca, que vai quebrar se o nome do arquivo tiver mais que 32 caracteres de tamanho. É só pra fazer funcionar e você ter algo funcionando para então aprimorar. O correto é inserir alguma codificação na tripa de bytes para você saber onde termina o nome e começa o conteúdo.


No bean named 'dispatch' is defined

Question: Running a gwtp-sample-basic-spring app in Eclipse, I see the welcome page, but after some server processing I get the following (and, probably, it's like that not only on my machine):
[WARN] /dispatch/
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dispatch' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1083)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:274)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1079)
    at org.springframework.web.context.support.HttpRequestHandlerServlet.init(HttpRequestHandlerServlet.java:57)
    at javax.servlet.GenericServlet.init(GenericServlet.java:212)
    at org.mortbay.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:433)
    at org.mortbay.jetty.servlet.ServletHolder.getServlet(ServletHolder.java:342)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:463)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:324)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
[ERROR] 500 - POST /dispatch/ (127.0.0.1) 3790 bytes

Why can I get this error? Everything's fine when running without Eclipse. Spring libraries are included in the classpath with a help of maven dependencies, as well as all the other needed.
Comment: Are there any strange warning/errors during the Spring initialisation?
Answer: Well, it's a nice tutorial about running these samples, but one step is missed there and as an Eclipse newbie I had this trouble. At first in Project properties/ Google/ Web application/ War directory I set src/main/webapps, which was wrong and needed libraries where in classpath, but coudn't work properly. Setting War directory to target/gwpt-spring-0.6 solved the problem.

No bean named 'dispatch' is defined


como limpar div quando input estiver vazio com autocomplete jquery-json?

Question: Eu tenho este código que não é meu, eu não sei javascript, mas preciso desta funcionalidade, ele está funcionando certinho, conforme eu vou digitando ele vai autocompletando criando li, com imagem e texto com o json, porem quando eu apago todo o texto do input, os li deviam desaparecer, mas eles continuam lá, acredito ser simples resolver este problema, mas não sei nada de javascript. Alguém poderia me ajudar?
Aqui está o código: https://www.webslesson.info/2017/02/live-search-json-data-using-ajax-jquery.html
Answer: Você poderia simplesmente adicionar uma verificação no valor da string. Se ela não existir, ou seja !searchField, utilize return para retornar um valor (nulo) e não executar o restante do código.

$(document).ready(function(){
 $.ajaxSetup({ cache: false });
 $('#search').keyup(function(){
  $('#result').html('');
  $('#state').val('');
  var searchField = $('#search').val();
  if (!searchField) return;

  var expression = new RegExp(searchField, "i");
  //$.getJSON('data.json', function(data) {
   $.each(data, function(key, value){
    if (value.name.search(expression) != -1 || value.location.search(expression) != -1)
    {
     $('#result').append('
 '+value.name+' | '+value.location+'
');
    }
   });
  //});
 });

 $('#result').on('click', 'li', function() {
  var click_text = $(this).text().split('|');
  $('#search').val($.trim(click_text[0]));
  $("#result").html('');
 });
});

var data = [
  {
    "name":"Angel Lewis",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/3/000/0d4/2f7/07a3d35.jpg",
    "location":"Seattle, WA"
  },
  {
    "name":"Justin Dean",
    "image": "https://media.licdn.com/mpr/mpr/shrink_100_100/AAEAAQAAAAAAAAIMAAAAJGExNTE4OWY4LWU4ODMtNDA2ZS1iNWI1LWNkYmIyOWMyMGQ5Zg.jpg",
    "location":"Muscatine, IA"
  },
  {
    "name":"Nora Blake",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/2/005/0b8/118/387e091.jpg",
    "location":"Seattle, WA"
  },
  {
    "name":"Russell Fox",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/2/000/084/26e/2d9e05b.jpg",
    "location":"Albuquerque, NM"
  },
  {
    "name":"Daryl Bradley",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/3/000/042/0ad/197566e.jpg",
    "location":"Buckeystown, MD"
  },
  {
    "name":"Benjamin Gonzales",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/8/005/0b2/1c9/2a423c1.jpg",
    "location":"Atlanta, GA"
  },
  {
    "name":"Viola Francis",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/AAEAAQAAAAAAAASJAAAAJGMyMTUzN2EyLTExY2ItNDZiNS1hMTY1LTI4NDA2NDMwZmFkNg.jpg",
    "location":"Zanesville, OH"
  },
  {
    "name":"Reginald Benson",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/1/000/10f/3cc/275a407.jpg",
    "location":"Gilbert, AZ"
  },
  {
    "name":"Glenda Ray",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/8/005/0ac/1ca/07c25a2.jpg",
    "location":"Baltimore, MD"
  },
  {
    "name":"Paula Vargas",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/5/005/03e/073/36a5c47.jpg",
    "location":"Baltimore, MD"
  },
  {
    "name":"Mark Armstrong",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/5/005/010/09b/39b122d.jpg",
    "location":"Hallandale Beach, FL"
  },
  {
    "name":"Jaime Campbell",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/AAEAAQAAAAAAAATUAAAAJDJkY2Q1Mzk0LTI1YzItNDFhNy04ZmQ0LWY3NzZlZTZlNGVmYw.jpg",
    "location":"Zanesville, OH"
  },
  {
    "name":"Mike Beck",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/2/000/01c/0d4/2b69e7c.jpg",
    "location":"Garner, NC"
  },
  {
    "name":"Ann Lowe",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/7/000/1f6/019/29cd853.jpg",
    "location":"Cabin John, MD"
  },
  {
    "name":"Ryan Wolfe",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/1/000/0bf/335/05a57f6.jpg",
    "location":"Los Angeles, CA"
  },
  {
    "name":"Dwayne Gutierrez",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/3/000/29b/028/2426536.jpg",
    "location":"San Jose, CA"
  },
  {
    "name":"Bill Burke",
    "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/7/000/1bc/12e/1423106.jpg",
    "location":"Bakersfield, CA"
  }
];
<!DOCTYPE html>

  <title>Webslesson Tutorial | Search HTML Table Data by using JQuery</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

JSON Live Data Search using Ajax JQuery

Employee Data

    <input type="text" name="search" id="search" placeholder="Search Employee Details" class="form-control" />

Comment: Resolveu!!! Obrigada!!! <3


Armbian - how to turn off a hard drive connected on SATA

Question: I have an Orange Pi + 2 single board computer with the ability to connect an external hard drive via SATA.
Armbian is installed on the hard disk, the bootloader is in the onboard memory of the board.
Any command to turn off the device leads to the same result: the indicators on the board go out, it is no longer available via SSH, but the hard disk, any devices connected via USB continue to work, and the image via HDMI is also displayed on the screen.
How to completely turn off the device so that the hard drive stops correctly?
Answer: I believe that if you are capable of powering the device off using the operating system's menu, then it should be safe to cut the power off from the device itself. I have a raspberry pi 4 and have a little USB-C adapter that has a simple power switch which makes this concept very convenient for me. Cutting power to a turned-on, working device is very dangerous as it can damage critical files that could be being written. For this reason, it is probably smart to back up the device and also make sure that you are powering the device off through the operating system so that it can finish editing core files in case it needs to.


Criação de um program em Python

Question: Olá, não sou muito boa em programação, e estou com dificuldades nesse exercicio, esta dando erro já procurei e nao consigo solucionar... Gostaria que alguem me ajudasse a refazer esse codigo. Desde ja agradeço quem puder me ajudar
Crie um programa que leia um valor em reais e converta para dolar e euro. Necessario definir o valor de cada moeda
valor = float(input('Digite um valor em reais: '))
while opção != 2:
print('''[1] Dolar[2] Euro''')
opção = float(input('Digite sua opção: '))
if opção == 1:
calcular = valor * (3.70)
print('R$ {} é {} em dolares'.format(valor, calcular))
elif opção == 2:
calcular = valor * 4.24print('R$ {} é {} em euros'.format(valor, calcular))
else:
print('Opção invalida')

Comment: Juu, a indentação do seu código está toda errada na pergunta. Poderia nos dizer se seu código está **exatamente** assim ou se a indentação ficou errada só ao postar aqui?
Comment: @user129140 Não para Python, ele aceita acentuação sem problemas.
Comment: Considerando que seu código esteja propriamente indentado, o problema é que você está declarado uma variável com caracteres especiais, como ç e ã. Sempre declare variáveis sem acentos e sem cedilhas, isso vale para quase todas as linguagens de programação.
Answer: Primeiramente vamos analisar os problemas. Você precisa identar o seu código corretamente, é a base para desenvolver em python!
valor = float(input('Digite um valor em reais: '))

while opção != 2:
    print('''[1] Dolar[2] Euro''')
    opção = float(input('Digite sua opção: '))

    if opção == 1:
        calcular = valor * (3.70)
        print('R$ {} é {} em dolares'.format(valor, calcular))
    elif opção == 2:
        calcular = valor * 4.24
        print('R$ {} é {} em euros'.format(valor, calcular))
    else:
        print('Opção invalida')

Agora podemos ver o seguinte:
# Você está verificando o valor de opcao, antes mesmo de iniciá-la!
while opção != 2:
    print('''[1] Dolar[2] Euro''')
    opção = float(input('Digite sua opção: '))

Quando você executar esse código, você vai cair nesse erro:
Traceback (most recent call last):
  File "so.py", line 3, in <module>
    while opção != 2:
NameError: name 'opção' is not defined

Pra resolver isso, você precisa inicializar essa variável com um valor!
Fazendo isso, seu programa executará corretamente ;)
Note que eu troquei o nome da variável opção por opcao, já que não é uma boa pratica em nenhuma linguagem de programação utilizar variáveis com Ç, acentos, etc.
valor = float(input('Digite um valor em reais: '))
opcao = 0

while opcao != 2:
    print('''[1] Dolar[2] Euro''')
    opcao = float(input('Digite sua opção: '))

    if opcao == 1:
        calcular = valor * (3.70)
        print('R$ {} é {} em dolares'.format(valor, calcular))
    elif opcao == 2:
        calcular = valor * 4.24
        print('R$ {} é {} em euros'.format(valor, calcular))
    else:
        print('Opção invalida')

Eu tomei a liberdade, e adicionei uma pequena validação para a opção selecionada, e adicionei uma terceira opção, que é para sair do programa
valor = float(input('Digite um valor em reais: '))
opcao = 0

while opcao != 3:
    print('''
          1 - Dolar
          2 - Euro
          3 - Sair
          ''')

    entrada = input('Digite sua opção: ')

    if entrada:
        try:
            opcao = int(entrada)
        except:
            print('Insira uma das opções informadas')
            continue

    if opcao == 1:
        calcular = valor * (3.70)
        print('R$ {} é {} em dolares'.format(valor, calcular))

    elif opcao == 2:
        calcular = valor * 4.24
        print('R$ {} é {} em euros'.format(valor, calcular))

    elif opcao == 3:
        print('Até mais ;)')

    else:
        print('Opção invalida')

Qualquer dúvida, é só perguntar.
Grande abraço ;)
Comment: Poderia explicar o porquê de "não é uma boa pratica em nenhuma linguagem de programação utilizar variáveis com Ç, acentos"?
Comment: Pq as linguagens normalmente utilizam apenas caracteres contidos na tabela ascii, assim como o alfabeto em inglês. Se vc testar o seu codigo em python 2, vc verá q ele fará erro, simplesmente por uma string não reconhecer unicode
Answer: Você está utilizando acentos em variáveis.
Não comece variáveis com Letras Maiúsculas e nem com caracteres especiais, caso tenha que utilizar 2 palavras em uma variável use nome_grande ou nomeGrande e nunca utilize acentos.
Utilize \n para pular linha:
print('--------\n[1] Dolar\n[2] Euro\n[0] Sair\n--------')

Seu while está: enquanto for diferente de 2 continue.
Criei uma variável chamada pergunta e atribui a ela o valor True do tipo boolean, enquanto o valor for True seu While vai ficar rodando.
Adicionei:
elif opcao == 0:
    # opcap for 0(ZERO) pergunta = False, While vai parar
    pergunta = False

Quando opcao for igual a zero:
A variável pergunta vai receber o valor de False e assim vai parar seu While.
# inicie o While como True
pergunta = True
valor = float(input('Digite um valor em reais: '))
#  Enquanto pergunta for True(Verdadeira) o While vai funcionar
while pergunta:
    print('--------\n[1] Dolar\n[2] Euro\n[0] Sair\n--------')
    opcao = float(input('Digite sua opção: '))
    if opcao == 1:
        calcular = valor * (3.70)
        print('R$ {} é {} em dolares'.format(valor, calcular))
    elif opcao == 2:
        calcular = valor * 4.24
        print('R$ {} é {} em euros'.format(valor, calcular))
    elif opcao == 0:
        # Opção for 0(ZERO) opcao = False, While vai parar
        pergunta = False
    else:
        print('Opção invalida')

Comment: O primeiro parágrafo da sua resposta não faz o mínimo de sentido. Python aceita sem problemas acentuação nos nomes de objetos, tanto com quanto funções.

Criação de um program em Python


Page always takes at least 30 seconds to load

Question: I have a site set up on Godaddy and a constant frustration is that it always takes at least 30 seconds to load. Total time for queries was under 200ms. I decided to write the following script:
<code>function getmillisecs() {
   list($usec, $sec) = explode (' ', microtime());
   return (double) $sec + $usec;
}

$start = getmillisecs();

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$end = getmillisecs();

$result = $end - $start;

echo round($result * 1000, 3);
</code>
All it does is output how much time passes between the start and end of the script. The time I got was 30521.649ms. Taking out everything related to Drupal dropped the time to 0.089ms. What is causing the huge delay? Thanks.
Answer: It could be several things:

Views executing sql queries that have performance problems.
Cache problems (Do you have enabled the Drupal's cache?).
(If you have a VPS) maybe the server that you are sharing is under heavy load.
(If your site is integrated with web services) maybe the web service is having performance problems or connection problems.

Try to check the logs of the site to see is there are errors or anything that could be related to this problem.
Another alternative is to use a profiler like Xhprof (there is a module for drupal) or XDebug.
Could you share with us the url of the website?
Comment: turned out the culprit was a module my client added. load times got cut down by 90% when I took it out.


How to set the correct RSS row plugin?

Question: I need to add an image to the RSS feed. So I create a new row plugin for the RSS and it extends RssFields row plugin.
/**
 * Renders an RSS item based on fields.
 *
 * @ViewsRow(
 *   id = "image_field_rss_fields",
 *   title = @Translation("Fields with image field"),
 *   help = @Translation("Display fields as RSS items with an image item."),
 *   theme = "views_view_row_rss",
 *   display_types = {"feed"}
 * )
 */
class ImageFieldForRssFields extends RssFields {

I can select it in the format settings.

And it seems that works perfectly when I update the preview, I can see a new field image on every item of the RSS. But when the RSS feed is rendered, it uses the RssFields plugin instead of the ImageFieldForRssFields plugin that is setted.
I debugged it and it seems that always renders the RssFields plugin even if I delete the RssFields plugin, the view tries to locate it.
Am I missing something? How do I have to do to render the correct plugin?
Answer: There is a patch to add an image as an enclosure field to core here:
https://www.drupal.org/project/drupal/issues/2511878

How to set the correct RSS row plugin?