If $f(x) \in C^1$ then number of maxima is finite in any interval.

Question: I am wondering if the following statement is true.

If  $f(x) \in C^1$ (not-constant) then a number of maxima are finite in any finite interval.

Here the set $C^1$ means that on the domain of $f$ we have that
\begin{align}
\sup_{x \in dom(f(x))} |f(x)|<c_0<\infty,\\
\sup_{x \in dom(f(x))} |f^{'}(x)|<c_1<\infty,
\end{align}
Comment: In fact you can have uncountably many maxima in an interval with a $C^\infty$ function that is nonconstant in every subinterval
Answer: I am not sure that I understand completely your question, but perhaps the following function is a counterexample: take $\displaystyle f(x)=\int_0^x t\exp(-t^2)\sin(1/t)dt$ (defining the function under the integral sign to be $0$ if $t=0$). Then $f$ is bounded, $f^{\prime}(x)=x\exp(-x²)\sin(1/x)$ is bounded, but as $f^{\prime}(1/k\pi)=0$ for $k\in \mathbb{Z}$, $k\not =0$, and that the derivative change sign in these points, on $[-1,1]$, $f $ has an infinite number of (local) maxima (and of minima)
Comment: Thank you for your example. This is exactly what I was looking for.  Do you know of any sufficient condition on function and its derivatives for the number of extreme points to be finite on a finite interval?
Comment: One can introduce hypothesis, such as the function has the form $P(x)\exp(-x^2)$, where $P$ is a polynomial (the exponential is here for your condition that the function and its derivative are bounded), but a general sufficient condition, I do not know....
Comment: What if the second derivative is bounded too?
Comment: I think that  if you replace in the counter-example $x\exp(-x^2)\sin(1/x)$ by  $x^n\exp(-x^2)\sin(1/x)$ with $n$ large, you can have the second derivative bounded, but the counter-example works with this new function.
Comment: Ok. One more. What about an analytic function?
Comment: If you have an analytic function on all of $\mathbb{C}$, say $f$, and if you take the restriction of $f$ to any intervall of $\mathbb{R}$, then as its derivative is again analytic, it has a finite number of zeros in any compact, so you have a positive answer.
Comment: Great. Can you provide a reference for this?
Comment: Any book on analytic functions gives you these results. Sorry, I must go....Bye
Comment: @Boby You may want to take a look at https://en.wikipedia.org/wiki/Identity_theorem
Answer: By interval do you mean a finite interval. If not, the statement is not true. Counter example would be $sinc(x)$ on $(0,\infty)$
Comment: yes. Finite. Interval.
Comment: Sin[1/x] has infinite maxima on (0,1), where Cos[1/x] = 0, that is
1/x = pi/2+k pi with integer k  --> x = 2/((2k + 1) pi)


Verificar se a index da listbox existe?

Question: Olá queria saber como faço para identificar se a index (Exemplo: 5 não existe) e retornar para 0.
Segue meu código:
<code>Dim avancarcoordX As Integer
avancarcoordX = lbPosX.SelectedIndex + 1
lbPosX.SelectedIndex = avancarcoordX
PosX.Text = lbPosX.SelectedItem
Dim avancarcoordY As Integer
avancarcoordY = lbPosY.SelectedIndex + 1
lbPosY.SelectedIndex = avancarcoordY
PosY.Text = lbPosY.SelectedItem
</code>
Quando não existe um Item então ele apresenta um erro. Preciso que ao chegar ao último item (Que é variavel) ele retorne ao primeiro. Assim um loop infinito.
Answer: Boa noite.
Tente o seguinte código:
<code>    If ListBox1.Items.Count > 0 Then

        If ListBox1.SelectedIndex = -1 Then
            ListBox1.SelectedIndex = 0
        Else
            If ListBox1.SelectedIndex < ListBox1.Items.Count - 1 Then
                ListBox1.SelectedIndex += 1
            Else
                ListBox1.SelectedIndex = 0
            End If
        End If
    End If
</code>

Verificar se a index da listbox existe?


Evaluation of $\int_{0}^{1}\frac{1}{\sqrt{1+x}+\sqrt{1-x}+2}dx$

Question:
Evaluation of $$\int_{0}^{1}\frac{1}{\sqrt{1+x}+\sqrt{1-x}+2}dx$$

$\bf{My\; Try::}$ Let $$I = \int_{0}^{1}\frac{1}{\sqrt{1+x}+\sqrt{1-x}+2}dx$$
Put $x=\cos 2 \theta\;,$ Then $dx = -2\sin 2 \theta d\theta$ and Changing Limit, We get
$$I = \int_{0}^{\frac{\pi}{4}}\frac{2\sin 2 \theta}{\sqrt{2}\cos \theta+\sqrt{2}\sin \theta+2}d\theta$$
So $$I = \int_{0}^{\frac{\pi}{4}}\frac{\sin 2 \theta}{\cos\left(\theta-\frac{\pi}{4}\right)+1}d\theta$$
Now Put $\displaystyle \theta-\frac{\pi}{4}=t\;,$ Then $d\theta = dt$ and changing limits
So $$I = \int_{-\frac{\pi}{4}}^{0}\frac{\cos 2t}{\cos t+1}dt=2\int_{-\frac{\pi}{4}}^{0}\frac{2\cos^2 t-2+1}{\cos t+1}dt$$
after that we can solve easily,
My question is can we solve it without Using Trig substution,
Plz explain me
Thanks
Comment: This could be tricky; for example $1+(1+\sqrt{1-x})(1+\sqrt{1+x})=2+\sqrt{1-x}+\sqrt{1+x}+\sqrt{1-x^{2}}$
Comment: The integral is solved by [Wolfram Alpha](http://www.wolframalpha.com/input/?i=Integrate%5B1%2F(Sqrt%5B1%2Bx%5D%2BSqrt%5B1-x%5D%2B2),%7Bx,0,1%7D%5D), but it's not trivial. By the way, $$I=2\sqrt{2}-1-\frac{\pi}{2}$$
Answer: I'm not sure this is the most straight forward way, but here it is anyway.
Start with the substitution $\sqrt{1-x}\mapsto x $. The integral transforms into
$$I=\int_0^1 \frac{2 x}{2+x+\sqrt{2-x^2}}dx.$$
Next, rationalize the denominator by multiplying the numerator and the denominator by $2+x-\sqrt{2-x^2}.$
This turns out to work very well, because $\,\,(2+x)^2-(2-x^2)=2(1+x)^2.$
So we get that the integral equals
$$I=\int_0^1 \frac{x(2+x-\sqrt{2-x^2})}{(1+x)^2}dx.$$
Finally, integrate by parts (note that $\displaystyle \frac1{(1+x)^2}=-\frac{d}{dx} \frac1{1+x}$):
$$I=-\frac{x(2+x-\sqrt{2-x^2})}{1+x}\Bigg{|}_0^1+\int_0^1 2\left(1+\frac{x-1}{\sqrt{2-x^2}}\right)dx
\\\\=-1+2-2\left(\sqrt{2-x^2}+\sin^{-1}\frac{x}{\sqrt{2}}\right)\Bigg{|}_0^1
\\\\=2\sqrt{2}-1-\frac{\pi}{2}.$$
Comment: I think this is the best way. +1
Comment: Bravo! - An excellent choice of substitution at the outset.
Answer: multiply the integrand by
$$
1=\frac{\left(-\sqrt{1-x}-\sqrt{x+1}+2\right) \left(\sqrt{1-x^2}+1\right)}{\left(-\sqrt{1-x}-\sqrt{x+1}+2\right) \left(\sqrt{1-x^2}+1\right)}
$$
doing the alegbra correctly this indeed eliminates the roots in the denominator and we end up with
$$
I=\frac{1}{2}\int_{0}^{1}\frac{-\sqrt{1-x} x+\sqrt{1+x} x-2 \sqrt{1-x}+2 \sqrt{1-x^2}-2 \sqrt{x+1}+2}{x^2}dx=\\
$$
taking into account a proper limiting procedure for $x\rightarrow 0,1$, this integral can be split in elementary pieces (solvable by integration by parts and/or subs of the form $y\rightarrow y\pm 1$)


Problem about probabilities of two car engine mounts breaking at the same time

Question: An automobile engine has three independent mounts, their probabilities of breaking in a 10-year period are 0.2, 0.4, and 0.3, respectively. If the driver of the vehicle hears the characteristic noise of two broken mounts, determine the probability that mounts one and two are broken.
I have done problems like this one but never with this kind of question where you have to find the probability of two things breaking at the same time. Can someone help please?
Comment: This is obviously an exercise. Please share first what you have tried to do.
Comment: At best this problem is poorly stated. It says the mounts are independent - which could mean any number of different things physically. It does not say that the probability of them breaking is independent, which is of course what would be useful in solving it. If you are going to a crassly unrealistic assumption (the probability of real motor mounts on a single engine breaking is highly dependent), you should at least state it clearly. (This is a rant against the source of your problem - not against you personally.)
Comment: @KBS i tried to use bayes theorem to calculate de probability of mount A breaking and mount B breaking independently but i got stocked when the problem asks me to calculate the probability of both A and B breaking at the same time and not other combination of two mounts (C and B for example).
Comment: @PaulSinclair i think we can assume that the problem refers to the probability of each mount breaking is independent from the others.
Comment: I didn't deny that was the intent. I just pointed out that it is very poorly stated. A well-stated math problem does not force you to make assumptions beyond the standard conventions ("if the word 'independent' is used anywhere in the description, it means the events are independent" is not a standard convention). And it is particularly poorly stated if the assumption you need to make is a highly unrealistic one like this.
Comment: @PaulSinclair ok I understand what you mean, thanks
Answer: Okay, I'm going to give it a try
We know that for sure two of the mounts are broken. We also know that the mounts breaking are independent of each other(at least that's what I gather from the problem's wording). Let events $A, B, C$ denote the respective breaking of the mounts:
$$P(A) = .2, P(B) = .4, P(C) = .3$$
Let's first find the probability that two mounts(and only two mounts) break:
$$P(\text{Two mounts break}) = P(A\cap B) + P(A\cap C) + P(B\cap C) - 3P(A\cap B\cap C)$$
Where the last term eliminates the probability that all three of them break because we have only heard two mounts break.
The question asks us for
$$P(A \cap B | \text{Two mounts break}) = \frac{P(\text{Two mounts break}|A \cap B)\times P(A \cap B)}{P(\text{Two mounts break})}$$
Where we can likely assume that $P(A \cap B) = .2 \times .3 = .06$
Can you take it from here?
Comment: Alternatively: $\mathsf P(\text{Only two mounts break})=\mathsf P(A\cap B\cap C^\complement)+\mathsf P(A\cap B^\complement\cap C)+\mathsf P(A^\complement\cap B\cap C)$
Comment: @bigBear I think I understand how you solved the problem, thanks a lot for the help
Comment: @GrahamKemp yeah i think this is another way to look at it, thanks a lot.


How to scp one file to remote using drush?

Question: I'd like to send one file to remote host which is defined as alias in drush.
The file is actually private ssh key, so it needs to be placed in ~/.ssh.
I've tried the following command:
drush -v rsync conf/my_rsa @remote:~/.ssh/

but then it's saying:
You will destroy data from drush@remote:'/var/www/~/.ssh/'

I don't want to destroy any existing data in my ~/.ssh.
Any workaround to that?
Comment: I know this is old, but the message is correct, you will destroy that file within the directory which is what you do below anyway. The message is a little ambiguous but it doesn't refer to *all* the files in the directory.
Answer: I've found the following workaround useful:
cat my_rsa | drush @remote ssh "cat > ~/.ssh/my_rsa"

It'll send content of the file directly via ssh into the file.


External Load Balancer not working GCP/Shared-VPC/VPC-native

Question: We are building a new Kubernetes cluster in GCP, using a Shared VPC. The cluster was created with VPC-native (i.e., alias IP) enabled. Everything about the Shared VPC seems to be in order. The node, pod, and service IP addresses are all as expected from the Shared VPC. I even have one service on an internal load balancer on the Shared VPC subnet which works just fine.
But when I run the simplest of tests for an external service
<code>kubectl create deployment hello-web --image=nginxdemos/hello
kubectl expose deployment hello-web --type=LoadBalancer --port 80 --target-port 80
kubectl get service hello-web
</code>
the public IP indicated by the last command, gets "This site can't be reached, x.x.x.x took too long to respond" from Chrome.
I ran the above test in our existing clusters which are not VPC-native nor Shared VPC and it works. So what might I be missing?
Comment: Could you provide steps which you followed? Did you create a firewall rule to allow this traffic? When you created Cluster/VM in second project, did you set in Firewall > Netowrkking > Networking interfaces?
Answer: When a GKE cluster uses a network from within the same project, the permissions are automatically there to allow the Kubernetes cluster service account to create firewall rules within that project. So it just works.
With a Shared VPC, the service project (GKE) needs to be given permission to create firewall rules in the host project. Or you must create the firewall rules manually. If the GKE cluster fails to create the firewall rules, it will be logged in the Kubernetes event long, along with the commands required to create the rules.
My solution was to grant role compute.securityAdmin in the Shared VPC host project to the service account in the GKE service project: service-[project-number]@container-engine-robot.iam.gserviceaccount.com.
The role above may be an overreach. At the very least, the service account needs the compute.firewalls.* rules within that role.
Comment: For addition, you can also check GKE docs about [SharedVPC](https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-shared-vpc)


Anonymous type isn't anonymous

Question: I have a class which has a string property:
public class User
{
    public string Name { get; set; }
    public int OtherProperty { get; set; }
}

I can select a List of the Names from a List<User> MyListOfUsers like so:
List<string> MyNames = MyListOfUsers.Select(x => x.Name).ToList();

In my asbent-mindedness, I had first tried to do the same via an anonymous type:
List<string> MyNames = MyListOfUsers.Select(x => new { x.Name }).ToList();

But that tells me

Cannot convert type List< <anonymous type: string Name> > to List<string>

But it knows it's a string? Why didn't it allow this syntax when it clearly knows the 'anonymous type' is a string?
Comment: `new { }` is an anonymous type object and `new { x.Name }` is an anonymous type object with a string property and `x.Name` is just a string object. So a string object and anonymous type with string a property are not the same.
Comment: Ahhh of course @ChetanRanpariya yes that makes sense thank you, I would have realised if I'd created `new { x.Name, x.OtherProperty }` - and that's why there are two pointy brackets `< < > >`  Silly Me.
Comment: Have a look at the class that gets generated for your anonymous type, tell me if it should be the same as a string https://sharplab.io/#v2:D4AQTAjAsAUCAMACEEAsBuWDkQHQBkBLAOwEdMYsBmZMRAYUQG9ZE3kbxEBVAZwFMATrBYx2HHEgByAQwC2/ZogDm/AC7pEAjYgC+rdiBok1iAPJqAFkIAKggPYAHIWoCeS1Tu2b9MX+KNkVEQAWQAKAEpmA3E2GNiANxlBRBleABNEAF5EYn4Ad0QiXjUAHj4hAD5Iilj2ePEklMF+XgBXABs1XmzUjNwAZX4O/gBjNTCAD2zK3IKlSdxZBT0I3AAVe2KJiNr2X10gA
Comment: @TimSchmelter I might just do that and with a comment for my future self to look back and laugh at.
Answer: The anonymous type you are creating is not a string. It's a class with a string property called Name.
Your code is equivalent to
List<string> MyNames = MyListOfUsers.Select(x => new { Name = x.Name }).ToList();

but C# allows you to infer a property name of an anonymous class from the source by saying new {x.Name} instead of new {Name = x.Name}.
Anonymous types in C# are classes that inherit from object and even if they only contain a single string property, they cannot cast to string as the documentation explains:

Anonymous types are class types that derive directly from object, and
that cannot be cast to any type except object.

As to your initial intention, this is correct
List<string> MyNames = MyListOfUsers.Select(x => x.Name).ToList();

The usage of a new anonymous class would not just be a different syntax but result in different memory footprint and GC load. It's unnecessary in your use case.
Comment: Yup, I've just realised if I'd created two properties in that anonymous type I would have seen this straight away, I think it's too late in the night for me.

Anonymous type isn't anonymous


Tkinter, get value from toplevel window

Question: So, i have two classes, ApplicationWindow is main and LoginWindow is toplevel of main. So i can't return the entered value from toplevel window to main's self.LOGIN and self.PASSW. Looked through SO - found nothing that could help me. Can you help me?
My code:
import os
import sys
import tkinter as tk

class ApplicationWindow(tk.Tk):
    def __init__(self, master=None):
        # print(l,p)
        self.LOGIN = "555"
        self.PASSW = "666"
        self.master = master
        self.master.geometry('800x400')
        self.master.title("app")
        self.master.f_app = tk.Frame(self.master).pack()
        self.menuBuild()

        self.b_log = tk.Button(self.master, width=10, text="button").pack()

    def menuBuild(self):
        menubar = tk.Menu(self.master)
        self.master.config(menu=menubar)

        mainMenu = tk.Menu(menubar, tearoff=0)
        mainMenu.add_command(label="Login", command=self.login)
        mainMenu.add_separator()
        mainMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=mainMenu)

    def login(self):
        self.tl_log = tk.Toplevel(self.master)
        self.login = LoginWindow(self.tl_log)

    def onExit(self):
        self.master.destroy()

class LoginWindow(tk.Tk):
    def __init__(self, master=None):
        self.master = master
        self.master.title("login")
        self.master.f_login = tk.Frame(self.master)
        self.master.geometry("300x100")
        self.l_log = tk.Label(self.master, text="mailbox")
        self.l_psw = tk.Label(self.master, text="password")
        self.e_log = tk.Entry(self.master, width=25)
        self.e_psw = tk.Entry(self.master, show="*", width=25)
        self.b_log = tk.Button(self.master, width=10, text="login", command=self.func)
        self.l_log.grid(row=1, column=1)
        self.l_psw.grid(row=2, column=1)
        self.e_log.grid(row=1, column=2)
        self.e_psw.grid(row=2, column=2)
        self.b_log.grid(row=3, column=1, columnspan=2)

    def func(self):
        l = self.e_log.get()
        p = self.e_psw.get()
        if l == "" or " " in l:
            print("not")
        else:
            return l, p
            self.master.destroy()

def main():
    root = tk.Tk()
    main = ApplicationWindow(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Comment: also putting `self.master.destroy()` after a return statement means it will never execute, the `return` ends the function.
Comment: no no!  do not inherit from `tk.Tk` if you aren't going to use your objects as `Tk` instances!  It may not be giving you issues now but if you do `super().__init__(master)` like you should with inheritance you would see how it explodes on you.
Comment: It's (arguably) OK to have _one_ class inherit from `Tk`, but you definitely shouldn't have more than one.
Comment: @TadhgMcDonald-Jensen i've tried so many variants of making that class - i'm getting confused, and i'm afraid that something will not work after another one struct change. And about `self.master.destroy` - yes, i know that it's bad idea, just don't know how to solve this problem.
Comment: Your two classes do not represent `Tk` objects and do not use any of it's functionality, inheriting from `Tk` doesn't do anything in your code except potentially misleading the reader but it could cause larger issues if left alone. Removing `tk.Tk` from the class declaration won't break your code and will reduce the likelihood that it will break in the future so I highly recommend removing it.
Answer: I think it would make sense to have a function that would handle the login action within ApplicationWindow that would then be passed over to LoginWindow, something like this:
class ApplicationWindow:
    ...
    def handle_login(self,name,passw):
        self.LOGIN = name
        self.PASSW = passw
        print("login was recieved from ApplicationWindow")

then you can pass it as an argument to LoginWindow:
class ApplicationWindow:
    ...
    def login(self):
        self.tl_log = tk.Toplevel(self.master)

        self.login = LoginWindow(self.tl_log, self.handle_login)

and store it as an instance variable for later use:
class LoginWindow():
    def __init__(self, master, login_action):
        self.successful_login_action = login_action
        ...

so instead of return l,p you would just call self.successful_login_action(l,p):
class LoginWindow():
    ...
    def func(self):
        l = self.e_log.get()
        p = self.e_psw.get()
        if l == "" or " " in l:
            print("not")
        else:
            self.successful_login_action(l,p)
            #return l, p
            self.master.destroy() #now this is called! Yay :)

Comment: Thank you very much. I'll keep this moment in mind in further work with classes.

Tkinter, get value from toplevel window


Crystal Report - Report Header Section

Question: I have created a Report using Crystal Report(Visual Studio 2005 and .NET Framework 2.0). In the Report Header section I have added a TextBox control to display header for the report. But when I execute the application the Text in the Report Header section is not displayed.
What should I do to view the text entered in the report header section?
Thanks in advance!
Comment: Is the report header invisible in all the pages?
Answer: 1) Are you sure you're running the most up to date copy of the report in the application?
The default behavior for the report header and textbox is that they are visible unless specified otherwise.
2) If the report header is being suppressed, it will appear as a darker shade than normally visible sections.  If the report header looks to be suppressed, you need to check the Section Expert for the Suppress checkbox associated with the report header section (it can be set conditionally - kill the button next to the Suppress checkbox to see if there's any code.  Generally the button text is red if there is any conditional logic).
3) If the report header is visible with no interference, check the suppression logic for the texbox - right click on the textbox, click properties.  Same checklist as for the report header.

Crystal Report - Report Header Section


media->save gives erros

Question: I am able to create a media object with the below code
 $static_media = Media::create([
'bundle' => 'document',
'uid' => $current_userid ,
'langcode' => "en",
'status' => 1,
 'name' => [
    'target_id' =>$title,

  ],
$file_name => [ 'target_id' => $fid, 'alt' => $title, 'title' => $title, ], ]);

but when I try to do $result=$static_media->save();  I get the error
Error: `Call to a member function isEmpty() on null in Drupal\media_entity_document\Plugin\MediaEntity\Type\Document->getField() (line 43 of profiles\lightning\modules\contrib\media_entity_document\src\Plugin\MediaEntity\Type\Document.php).

How can I debug this to find out what is missing?  I tried putting an echo at that point of the code in the plugin but cannot see anything .  What would you suggest to try to see what field it is looking for at that point?
Thank you .
Comment: Look at what is calling isEmpty and that ought to give you an idea of what it is expecting
Comment: Its the function geField () but when I put in echos in that function there is nothing there .  so i still dont know what field is missing
Answer: instead of this part of the array
$file_name => [ 'target_id' => $fid, 'alt' => $title, 'title' => $title, ], ]);

i had to put the field name , not the file name.
'field_document' => [ 'target_id' => $fid, 'alt' => $title, 'title' => $title, ], ]);

media->save gives erros


shapiro test for exponentiality

Question: After running the shapiro.exp.test in testing for exponentiality I am getting powers of the test as equal to zero. I suppose the issue might be on my rejection criteria (i.e $p.value<0.05). This works for all other tests e.g ks.exp.test and cvm.exp.test
Can anyone assist?
powerSW = mean(replicate(1000,(shapiro.exp.test(rt(50, 7))$p.value<0.05)))

Comment: @Show you should identify the package you're running the function from; it's perfectly possible (and indeed regularly happens) that several packages may use the same name for somewhat different functions (even if they perform the same task their inputs and outputs may differ). Do you mean the function in package `exptest` ?
Comment: @Michael The test for exponentiality is in Shapiro & Wilk (1972) "An Analysis of Variance Test for the Exponential Distribution (Complete Samples)". It's one of a number of tests for exponentiality (among which I'd expect the Lilliefors test to be relatively low powered against many of the alternatives likely to be of interest).
Comment: A better test for exponentiality might be to use Lilliefors test.
Comment: Why would you expect it to be better?  (it may well be, but it has fairly low power so it seems an odd one to suggest)
Comment: Lillefors test is especially designed for the exponential distribution. I am not sure what version of Shapiro's test the OP is referring to. If it is the Shapiro-Wilk test that one is intended for determining normlity.
Comment: Yes i am using the package exptest in r. For example, if the alternative is a t(2) , for n = 10, 20 and 50 i am getting power of 0.0270, 0.0170 and 0.0130 respectively. If we subtract these powers from 1 we do get reasonable powers, 0.9730, 0.9830 and 0.9870 respectively
Answer: Proceeding on the assumption that this is the function in package exptest:
The test stat here is $$W = \frac{n(\overline{X} - X_{(1)})^2}{(n - 1)\sum_{i=1}^n{(X_i - \overline{X})^2}}$$
With that test statistic the test would actually be for testing a shifted exponential against a range of alternatives. (Edit: the original paper confirms this)
After shifting the sample by the minimum (and discarding that value), this statistic is a function of the coefficient of variation which makes sense -- with the ordinary exponential the CV should be close to 1.
Because of the particular form of the statistic I'd have expected it to have good power against the normal (except in a particular subset of cases) -- but trying it on samples from the standard normal it doesn't seem to; this might instead suggest some implementation issue.
Looking at the code, it looks like the implementation of the test might indeed be wrong.
To quote the original paper, $^{[1]}$

As an omnibus procedure, W is to be used as a two tailed statistic

As far as I can see, the code only looks at one tail. There may be other issues with it, I haven't checked closely, but that could easily explain very low power against some alternatives where the CV differs from 1.
[1] Shapiro, S. S. & Wilk, M. B. (1972)
"An Analysis of Variance Test for the Exponential Distribution (Complete Samples)"
Technometrics, 01 May 1972, Vol.14(2), p.355-370

shapiro test for exponentiality


Show that aH and bH contain the same number of elements in G

Question: Let G be a finite group and H a subgroup of G. Let a be an element of G and aH = {ah : h is an element of H} be a left coset of H. If B is an element of G as well show that aH and bH contain the same number of elements in G
Answer: Sketch:
Construct a bijection between the two sets.  For instance, let
$$
\varphi:aH\rightarrow bH
$$
be given by $\varphi(ah)=bh$.  Now, prove that this is a bijection.

To show that this is an injection, suppose that $\varphi(ah_1)=\varphi(ah_2)$.  This implies that $bh_1=bh_2$ or that $h_1=h_2$.
To show that this is surjective, let $bh_3\in bH$, then $\varphi(ah_3)=bh_3$.

It is also important to verify that $\varphi$ is really a function.  This can be done by checking that the function is well-defined.  In other words, that if $ah_1=ah_2$, then $h_1=h_2$.
Answer: Fix $a\in G$ and define $L_a:H\to G$ by $h\mapsto ah.$ The image of this map is obviously $aH$. On the other hand, if $ah_1=ah_2$ then $a^{-1}ah_1=a^{-1}ah_2\Rightarrow h_1=h_2$. Thus, $L_a$ is a bijection so $|H|=|
aH|.$ And since $a$ is arbitrary, we have $|aH|=|H|=|bH|$ for any $a,b\in G$.


Form API Submit Button for Multiple Forms

Question: I created a module with 3 forms on it. Is there a way to only have one submit button at the very bottom of the page that will store all three values?
Answer: Not really. Drupal form may try to redirect you after successful submit. If 3 forms try, which redirect should work? And that's only one example.
Create fourth form function. In it, call all 3 existing ones, clean up mess with submit functions, validators and redirects, and it should work. Or simply merge your forms into one, why you needed three?
Comment: @Ryan whyyy?? You do not need 3 forms, you can have many fields on one form!
Comment: I'm trying to make multiple forms to separate a user's first name, last name, and email address. I guess I can just make a giant textarea instead of three separate textfields.
Answer: You could try the multiform module. This is especially useful if the forms you have on one page are not ones you created, but are instead Drupal forms you need to have on a single page.

This is an API module which lets you put several forms into one
  .
The usage is very simple: there is one API function to call:
  multiform_get_form() and you can pass the form names in the attribute
  list.

You can use it like this:
multiform_get_form(array('form_id', $arg1), array('form_id', $arg1, $arg2));
https://www.drupal.org/project/multiform


map().partitionBy() How many shuffles these 2 commands will do?

Question: Question :
1)
So if i have :
<code>SomeRDD = myRDD.map().partitionBy(new hashPartitioner(2))
</code>
How many shuffles these two commands will make?
Is that 2 shuffles? 1 for the map(), and 1 for the partitionBy()? or 1 ?
It's not yet clear to me...
Answer: A map does not cause a shuffle. It is a narrow transformation, i.e. the function (which is missing in your code sample) would be called on each element individually.
A shuffle would be called when you need to access data from different partitions (i.e. a wide transformation). When you do a partitionBy you tell spark that it needs to repartition according to your request and therefore may cause a shuffle.


Retirar elemento de uma lista encadeada

Question: Estou implementando uma lista encadeada do tipo "com cabeça". Segue struct referente à lista e a criação dela na main()
struct lista{
    int info;
    struct lista *prox;
};
typedef struct lista Lista;

int main ()
{
    Lista *l, *aux;

    l = (Lista*) malloc(sizeof(Lista));

    l->prox = NULL;

    //Trechos de código

    retira_n(l, n);
}

Logo a seguir segue a função que retira todas as ocorrências de um dado número "n" da lista e retorna a lista
Lista* retira_n(Lista *l, int n)
{
    Lista *atual, *ant, *atual2;
    int flag = 0;

    atual = l->prox;
    ant = l->prox;

    while(atual != NULL)
    {
        if(atual == l->prox && atual->info == n)
        {
            l->prox = atual->prox;
            free(atual);
            atual = l->prox;
            flag++;
            continue;
        }
        else if(atual->info == n)
        {
            ant->prox = atual->prox;
            flag++;
        }

        ant = atual;
        atual = atual->prox;
    }

    if(flag == 0)
    {
        printf("O elemento nao esta na lista");
    }

    return l->prox;
}

A função está funcionando de forma parcial, isto é, os elementos da lista não são mostrados quando eu vou "printar" a lista, entretanto por não ter conseguido arrumar um jeito de desalocar a memória com a função free(), pois se eu for desalocar utilizando o ponteiro "atual", por exemplo, não vou poder usá-lo em outras iterações para verificar os outros elementos da lista. Queria uma forma de desalocar o elemento que eu quero excluir e não apenas fazer o anterior apontar para o próximo elemento da lista.
Comment: Se eu entendi bem você tem um problema que não é tão simples de resolver um C. Você tem que controlar o tempo de vida de um elemento que pode ter várias referências. Provavelmente teria que criar um contador de referências (e não permitir referências cíclicas ou ter como usar uma referência fraca). Acho que você não tem ideia do que estou falando. Isto mostre que é um problema complexo demais para atacar em um exercício, a não ser que o exercício seja avançado mesmo e a intenção seja justamente aplicar o *reference counting*. Tem técnicas mais avançadas ainda.
Answer: Seu código estáconfuso em alguns aspectos - mas para responder o que você quer, basta re-escrever o segundo if assim:
    else if(atual->info == n)
    {
        ant->prox = atual->prox;
        free(atual);
        atual = ant->prox;
        flag++;
    } else {
         ant->prox = atual;
         atual = atual->prox;
    }

Perceba que muda também para só avançar o "ant" se o nṍ atual não foi removido  - as linhas fora do if que mudam ant e atual não devem ser executadas caso o nó tenha sido removido (o ant permance o mesmo e o atual avança).
Dica: evite usar uam variável com nome "l"  - é um símbolo difícil de distinguir de "1". Outra dica: sua variável é um contador ou é um flag - se for um contador, evite chama-lo de "flag".
Comment: Não, mais em baixo no código ele reposiciona ambos ponteiros, desse jeito vai pular a verificação de um nó.
Comment: Obrigado @DaviAragao - corrigido.
Comment: Esse  atual = atual->prox; é necessário?
Comment: Sim - sem ele o laço todo vai ficar sempre no mesmo nó, e não vai percorrer a lista.
Answer: Criando um ponteiro adicional e fazendo com que o mesmo aponte para a posição de atual antes de atual receber o próximo você isola o endereço de memória para ser liberado, aí pode usar o free normalmente.
Lista* retira_n(Lista *l, int n)
{
    Lista *atual, *ant, *atual2, *morto;
    int flag = 0;

    atual = l->prox;
    ant = l->prox;

    while(atual != NULL)
    {
        if(atual == l->prox && atual->info == n)
        {
            l->prox = atual->prox;
            morto = atual;
            atual = atual->prox;
            flag++;

        }
        else if(atual->info == n)
        {
            ant->prox = atual->prox;
            morto = atual;
            atual = atual->prox;
            flag++;
        }
        else
        {
            ant = atual;
            atual = atual->prox;
        }
        free(morto);
    }

    if(flag == 0)
    {
        printf("O elemento nao esta na lista");
    }

    return l->prox;
}

Retirar elemento de uma lista encadeada


how to leverage confidence intervals of regression to develop predictive model that generates a distribution of outcomes for a single individual

Question: I'm trying to generate a predictive logistic regression model that in some form accounts for the uncertainty in the model's coefficients such that for the same input of predictor variables the outcome variable varies.
For example, if I have a model as follows:
Train <- createDataPartition(RAVE_filtered$remission_6mo_bool, p=0.60, list=FALSE)
training <- RAVE_filtered[Train, ]
testing <- RAVE_filtered[-Train, ]

ctrl <- trainControl(method = "repeatedcv",
                    number = 10,
                    savePredictions = TRUE)

summary(mod_fit <- train(factor(remission_6mo_bool) ~ `Randomized Treatment Group` + ANCA + AAV + pred_dose + baseline_BVAS,
                 data=training,
                 method="glm",
                 family="binomial",
                 trControl=ctrl,
                 tuneLength=5))

As background:
remission_6mo_bool is a two-level factor (0,1) as is Randomized Treatment Group, ANCA, AAV and pred_dose is a continous variable, while baseline_BVAS is a discrete numerical score ranges from 0-63 with a very strong skew toward 0 (e.g., highly non-normal distribution)
The model outputs:
Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.3899   0.3283   0.5760   0.6516   1.0756

Coefficients:
                                        Estimate Std. Error z value Pr(>|z|)
(Intercept)                            1.5419175  1.2751260   1.209   0.2266
`\\`Randomized Treatment Group\\`RTX`  1.1282269  0.5285303   2.135   0.0328 *
ANCAPR3                               -1.3798677  0.9104766  -1.516   0.1296
AAVMPA                                -0.3882255  0.9320723  -0.417   0.6770
pred_dose                              0.0001030  0.0005594   0.184   0.8539
baseline_BVAS                          0.0462253  0.0835449   0.553   0.5801
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 114.19  on 112  degrees of freedom
Residual deviance: 106.16  on 107  degrees of freedom
AIC: 118.16

Number of Fisher Scoring iterations: 5

I'm looking for:
1) A statistically correct way on how to leverage the uncertainty of this model (or really any model) such that when used to predict outcomes it doesn't just do so formulaically such that for the same inputs the output is always the same.
2) I'm still quite new to R and statistics, so any short examples or pointers on how to implement (1) would be incredibly helpful.
Many thanks!
Comment: If the logistic model is completely pre-specified and all you're doing is estimating the regression coefficients, the simple confidence interval for a predicted probability seems to be what you need.
Answer: If I understand your problem correctly, you want your model to predict a greater variability so that you can use this in simulations? If so, I was faced with a similar problem and the approach in this paper was useful to me:
Model Calibration Under Uncertainty - Matching Distribution Information by Swiler, Eldred and Adams.
Using this approach as a starting point, I was able to calibrate a model using minimization techniques such that the model predictions matched the observed percentiles and variability. In my case, this was more important than predicting an accurate mean value because the model outputs needed to be used as inputs into a larger forecasting model.
I hope that helps!


Choosing the right forecasting technique

Question: I'm currently attempting to forecast visitor data for stores. My dataset includes daily visitor totals of three years. Note that the dataset isn't complete (stores can be closed for a few days, etc). I've augmented the dataset with weather data per day and holiday information (I have about 18 features per datapoint, including weekday,month,holiday,weather-data).
My computer science background doesn't include a lot of statistical methodology, so I have a hard time figuring out which techniques I can use/should look into. My focus right now is on 1-ahead forecasting with a simple neural network in pylearn2, but the predictions that I'm getting out of it are highly inaccurate. I would like to evaluate some other techniques for comparison and evaluation.
I could use some hints in the right directions, so I'm wondering: Which techniques could I look into for forecasting these numbers? And how could I simplify the problem to increase my succes?
Answer: Forecasting is a big field, so it will be hard to give a simple answer. I'd recommend starting with a very simple model. Simple models are often surprisingly hard to beat in terms of forecasting accuracy.
Look first at exponential smoothing with a seasonality of 7, to capture day of week effects, which will quite probably be the main driver of store visits. That will give you a useful baseline, and only once you have mastered that, you should try improving on that. (And I forecast that you won't find that easy.)
Holidays should probably be the next thing to look at. Here, you may want to switch from exponential smoothing to ARIMAX models, with additional explanatory variables around the holidays. Not as simple and easily understood as smoothing, but it can more easily capture external info (although state space formulations of smoothing can do so, too).
At this point, you will want to think about what kind of store you are looking at. Grocery is easy, very stable. Fashion is more volatile, with multiple seasons per year and traffic patterns following these seasons (and markdown periods). Do-it-yourself and home improvement store traffic may depend on the weather, as with everyone rushing to buy snowplowers when the first snow falls. And so on.
Leave weather for last. Yes, weather will have an impact. But you will need to include weather forecasts in your models, not actuals, since you don't yet know the actual weather for tomorrow! This of course adds a level of uncertainty. Don't use the actual weather in your forecasts for assessing your model, since you will lose this additional uncertainty, and your models will necessarily look too good - you will be too sure of yourself. And if you want to use your forecasts in a production environment, you will of course need to worry about the data feed, and what happens if the feed is broken and no weather forecast is available... While weather data may improve your forecasts, you will have to think about whether the additional hassle is worth the accuracy improvement.
You write that your current forecasts are "highly inaccurate". Forecasting is an inexact science, and no forecast will ever be perfect. Be careful about your expectations and about accuracy targets. Don't trust published forecasting accuracy benchmarks.
I highly recommend this free, open source textbook on forecasting. You will find much about exponential smoothing, ARIMA, error measures and so forth in there.
Comment: Unfortunately, no. I mostly forecast unit sales per SKU and location. There *are* approaches to this involving forecasting traffic and basket share separately, but it's never been our approach, and since I'm rather constrained by a lot of architectural decisions made for me, I never had the opportunity to explore traffic forecasting. Sorry and good luck!
Comment: Thanks for the in-depth explanation and tips. I saw that this is quite related to your field of work; got any must-read papers/articles on the subject of customer number/traffic prediction in stores?


React - Como modificar um estado do componente pai a partir do filho?

Question: Digamos que eu tenho um componente pai:
import React from 'react';
import style from './style.less';

export default class Wrapper extends Component {

    this.state = {
         active: false
    }

    render() {
        return (

{props.text}

                     <Button isCentered={true} text="Precisa de alguma ajuda?" bgColor="#673ab7" color="white" />

        )
    }
);

export default Wrapper;

E um componente filho:
import React from 'react';
import style from './style.less';

const Button = (props) => (
    <div class={style.button} style={{textAlign: `${props.isCentered ? "center" : "left"}`}}>
         <a onClick={console.log("Clicou!")} style={{backgroundColor: `${props.bgColor}`, color: `${props.color}`}} class={style.a}>{props.text}

);

export default Button;

Meu App.js:
import { react, Component } from 'react';
import Header from './Wraper';

export default class App extends Component {

    constructor() {
        super();
    }

    render() {
        return (

                <Wraper text="Lorem Ipsum" />

        );
    }
}

De que maneira eu posso modificar o estado active do component Wrapper para true no momento que eu clicar no componente filho Button?
Answer: Você pode usar funções de callbackParent():
Existem frameworks para lidar com o gerenciamento de estado, como por exemplo o Redux. Mas se a ideia não for adicionar um novo modulo no seu projeto, talvez você possa usar funções de callback:
Você pode passar como props para o componente filho uma função que irá chamar um método da sua classe statefull.
import React from 'react';
import style from './style.less';

export default class App extends Component {

    this.state = {
        active: false
    }

    // Função chamada pelo callbackParent();
    onChildChanged(bool) {
        this.setState({active: bool});
    }

    render() {
        return (

{props.text}

                    <Button callbackParent={(bool) => onChildChanged(bool)} isCentered={true} text="Precisa de alguma ajuda?" bgColor="#673ab7" color="white" />

        )
    }
);

export default Wrapper;

Não se esqueça de chamar a sua função no onClick() do seu componente filho:
import React from 'react';
import style from './style.less';

const Button = (props) => (
    <div class={style.button} style={{textAlign: `${props.isCentered ? "center" : "left"}`}}>
         <a onClick={props.callbackParent(true))} style={{backgroundColor: `${props.bgColor}`, color: `${props.color}`}} class={style.a}>{props.text}

 );

 export default Button;


How to make a recursive Dhall sum type containing data

Question: Here is my example code. I haven't been able to figure out how to make my State sum-type recursive, while still allowing it to be used like a sum-type elsewhere. Likewise with my StateMachine type.
let State =
      < Task : { Comment : Text, Resource : Text, End : Bool }
      | Map : { Comment : Text, Iterator : StateMachine }
      | Parallel : { Comment : Text, Branch : List State }
      >

let StateMachine
    : Type
    = { Comment : Optional Text
      , StartAt : Text
      , States : List { mapKey : Text, mapValue : State }
      }

let test
    : StateMachine
    = { Comment = Some "A simple minimal example"
      , StartAt = "Hello World"
      , States =
        [ { mapKey = "Hello World"
          , mapValue =
              State.Task { Type = "Task", Resource = "Test", End = True }
          }
        ]
      }

in  test

Is there a reasonable way to do this that doesn't blow up code size and make the types ergonomic for an end user to import and use? In case it wasn't apparent from the example, I'm trying to mode a state machine.
I have tried the following, but I get a "Not a record or a Union" error for State.Task:
let State
    : Type
    =   ∀(_State : Type)
      → ∀(Task : { Type : Text, Resource : Text, End : Bool })
      → ∀(Map : { Type : Text, Iterator : _State })
      → _Stat

Answer: First, I believe the type you meant to say was:
let State
    : Type
    = ∀(State : Type) →
      ∀(Task : { Type : Text, Resource : Text, End : Bool } → State) →
      ∀(Map : { Type : Text, Iterator : State } → State) →
        State

in  State

To answer your question, the closest thing you can get to a recursive union type is this equivalent representation:
let State
    : Type
    = ∀(State : Type) →
      ( < Task : { Type : Text, Resource : Text, End : Bool }
        | Map : { Type : Text, Iterator : State }
        > →
          State
      ) →
        State

in  State

... but you wouldn't get union constructors for free so I wouldn't recommend using the latter representation anyway.
For either approach you'd have to create functions that behave the same way as constructors; the language won't generate them for you like it does for non-recursive union types.
I'll illustrate how to write the constructors for the first type since that's the representation I'd recommend using:
let Types =
      let Task = { Type : Text, Resource : Text, End : Bool }

      let Map = λ(State : Type) → { Type : Text, Iterator : State }

      let State
          : Type
          = ∀(State : Type) →
            ∀(Task : Task → State) →
            ∀(Map : Map State → State) →
              State

      in  { Task, Map, State }

let -- Record of constructors similar to what you would get from a union type
    State =
      let Task
          : Types.Task → Types.State
          = λ(x : Types.Task) →
            λ(State : Type) →
            λ(Task : Types.Task → State) →
            λ(Map : Types.Map State → State) →
              Task x

      let Map
          : Types.Map Types.State → Types.State
          = λ(x : Types.Map Types.State) →
            λ(State : Type) →
            λ(Task : Types.Task → State) →
            λ(Map : Types.Map State → State) →
              Map (x with Iterator = x.Iterator State Task Map)

      in  { Task, Map }

in  State.Map
      { Type = "Foo"
      , Iterator = State.Task { Type = "Bar", Resource = "CPU", End = False }
      }

For more details, see:

How to translate recursive code to Dhall
Comment: I also just created a pull request to expand the documentation to explain the "smart constructors" trick shown in this answer: https://github.com/dhall-lang/dhall-lang/pull/1008
Comment: I took a look a the PR and that looks great!
Comment: Thanks for answering this with an example! That makes a lot more sense seeing it in the context of my own problem than when I was reading the recursive translation docs.


Google map API doesn't display correctly jQuery slideToggle

Question: I put Google Map inside a div, and made a slideToggle onto the div.
the Google Map doesn't display correctly.

Once the div expanded, it doesn't look right like the map below
Please check the code on jsFiddle Sample

Comment: possible duplicate of [jQuery SlideToggle Google Maps Issue](http://stackoverflow.com/questions/13733482/jquery-slidetoggle-google-maps-issue)
Answer: You could wait until the map is loaded by adding an event listener for idle.  This event will fire once the map is fully loaded and ready.
google.maps.event.addListenerOnce(map, 'idle', function() {
    $('.hide').hide();
});

Here's the JSFiddle.
EDIT:
For anyone with a similar problem, here is the updated JSFiddle with the map positioned offscreen so it remains hidden without using display:none.
Comment: Yeah unfortunately if it has `display:none` the marker won't load.  However there is probably a way to hide it with positioning so you don't have to see the map pop open at first, you might want to check this answer out: http://stackoverflow.com/a/4700611/1091751.
Comment: Thanks! The map has to be loaded first? As the page looks bit odd at the first open.
Comment: I don't quite understand from that answer, I don't think `position: absolute; left: -10000px;` works with `slideToggle` ? is that right? Thanks
Comment: offscreen is a nice solution. Thanks!
Answer: you need to wait until map finished render then you set hide a map
because map div was toggle when div on hiding and that make map looking wrong location
init function should look like this
function initialize() {
  var latlng = new google.maps.LatLng(48.89376,2.33742);
    var settings = {
    zoom: 15,
      center: latlng,
      disableDefaultUI: true,
        zoomControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById("map"), settings);
  var marker=new google.maps.Marker({
    position:latlng,
  });

  marker.setMap(map);

  // on map idle set div hide
  google.maps.event.addListenerOnce(map, 'idle', function() {
      $('.hide').hide();
  });
}

Comment: Thanks for your answer, but if I enable "hide", it doesn't work.
Comment: thanks for the updated answer, there is a bit issue, it really depends on how fast the pageload is. Is there a better way to fix way?


Android NDK clang undefined reference to 'memcpy', version 'GLIBC_2.2.5'

Question: I'm trying to compile the grpc project using Android NDK, for the android-x86_64 ABI I'm getting the following error:
<code>/Users/someuser/Library/Android/sdk/ndk/21.1.6352462/toolchains/llvm/prebuilt/darwin-x86_64/lib/gcc/x86_64-linux-android/4.9.x/../../../../x86_64-linux-android/bin/ld: error: symbol memcpy has undefined version GLIBC_2.2.5
/Users/someuser/Library/Android/sdk/ndk/21.1.6352462/toolchains/llvm/prebuilt/darwin-x86_64/sysroot/usr/include/bits/fortify/string.h:62: error: undefined reference to 'memcpy', version 'GLIBC_2.2.5'
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
</code>
This is reproducing on Windows/Ubuntu/MacOS.
The Android NDK doesn't contain the gcc compiler anymore, how can this be solved?
<code>$ /Users/someuser/Library/Android/sdk/ndk/21.1.6352462/toolchains/llvm/prebuilt/darwin-x86_64/bin/x86_64-linux-android24-clang++ --target=x86_64-none-linux-android24 --sysroot=/Users/someuser/Library/Android/sdk/ndk/21.1.6352462/toolchains/llvm/prebuilt/darwin-x86_64/sysroot -fPIC -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security    -O2 -DNDEBUG  -Wl,--exclude-libs,libgcc.a -Wl,--exclude-libs,libgcc_real.a -Wl,--exclude-libs,libatomic.a -static-libstdc++ -Wl,--build-id -Wl,--fatal-warnings -Wl,--no-undefined -Qunused-arguments  -shared -Wl,-soname,libgpr.so -o libgpr.so CMakeFiles/gpr.dir/src/core/lib/gpr/alloc.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/atm.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/cpu_iphone.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/cpu_linux.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/cpu_posix.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/cpu_windows.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/env_linux.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/env_posix.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/env_windows.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/log.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/log_android.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/log_linux.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/log_posix.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/log_windows.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/murmur_hash.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/string.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/string_posix.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/string_util_windows.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/string_windows.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/sync.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/sync_abseil.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/sync_posix.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/sync_windows.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/time.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/time_posix.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/time_precise.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/time_windows.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/tls_pthread.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/tmpfile_msys.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/tmpfile_posix.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/tmpfile_windows.cc.o CMakeFiles/gpr.dir/src/core/lib/gpr/wrap_memcpy.cc.o CMakeFiles/gpr.dir/src/core/lib/gprpp/arena.cc.o CMakeFiles/gpr.dir/src/core/lib/gprpp/examine_stack.cc.o CMakeFiles/gpr.dir/src/core/lib/gprpp/fork.cc.o CMakeFiles/gpr.dir/src/core/lib/gprpp/global_config_env.cc.o CMakeFiles/gpr.dir/src/core/lib/gprpp/host_port.cc.o CMakeFiles/gpr.dir/src/core/lib/gprpp/mpscq.cc.o CMakeFiles/gpr.dir/src/core/lib/gprpp/stat_posix.cc.o CMakeFiles/gpr.dir/src/core/lib/gprpp/stat_windows.cc.o CMakeFiles/gpr.dir/src/core/lib/gprpp/thd_posix.cc.o CMakeFiles/gpr.dir/src/core/lib/gprpp/thd_windows.cc.o CMakeFiles/gpr.dir/src/core/lib/gprpp/time_util.cc.o CMakeFiles/gpr.dir/src/core/lib/profiling/basic_timers.cc.o CMakeFiles/gpr.dir/src/core/lib/profiling/stap_timers.cc.o  -ldl -lm third_party/abseil-cpp/absl/status/libabsl_status.so third_party/abseil-cpp/absl/synchronization/libabsl_synchronization.so -landroid -llog third_party/abseil-cpp/absl/strings/libabsl_str_format_internal.so third_party/abseil-cpp/absl/strings/libabsl_cord.so third_party/abseil-cpp/absl/types/libabsl_bad_optional_access.so third_party/abseil-cpp/absl/debugging/libabsl_stacktrace.so third_party/abseil-cpp/absl/debugging/libabsl_symbolize.so third_party/abseil-cpp/absl/debugging/libabsl_debugging_internal.so third_party/abseil-cpp/absl/debugging/libabsl_demangle_internal.so third_party/abseil-cpp/absl/synchronization/libabsl_graphcycles_internal.so third_party/abseil-cpp/absl/time/libabsl_time.so third_party/abseil-cpp/absl/strings/libabsl_strings.so third_party/abseil-cpp/absl/strings/libabsl_strings_internal.so third_party/abseil-cpp/absl/base/libabsl_throw_delegate.so third_party/abseil-cpp/absl/numeric/libabsl_int128.so third_party/abseil-cpp/absl/time/libabsl_civil_time.so third_party/abseil-cpp/absl/time/libabsl_time_zone.so third_party/abseil-cpp/absl/base/libabsl_malloc_internal.so third_party/abseil-cpp/absl/base/libabsl_base.so third_party/abseil-cpp/absl/base/libabsl_spinlock_wait.so third_party/abseil-cpp/absl/base/libabsl_raw_logging_internal.so third_party/abseil-cpp/absl/base/libabsl_log_severity.so -pthread -latomic -lm
/Users/someuser/Library/Android/sdk/ndk/21.1.6352462/toolchains/llvm/prebuilt/darwin-x86_64/bin/../lib/gcc/x86_64-linux-android/4.9.x/../../../../x86_64-linux-android/bin/ld: error: symbol memcpy has undefined version GLIBC_2.2.5
/Users/someuser/Library/Android/sdk/ndk/21.1.6352462/toolchains/llvm/prebuilt/darwin-x86_64/sysroot/usr/include/bits/fortify/string.h:62: error: undefined reference to 'memcpy', version 'GLIBC_2.2.5'
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
</code>
Comment: I have the same issue. Have you solved the problem yet?
Answer: The solution was to comment out <code>__asm__(".symver memcpy,memcpy@GLIBC_2.2.5");</code> from the grpc code.


Adding a text overlay on a featured image in Wordpress

Question: I'm trying to display a list of projects (Custom post type). Just the title, tags, featured image and the permalink:

          <a class="full_link" href="<?php the_permalink(); ?>">

<?php the_post_thumbnail(); ?>

<?php the_title(); ?>

<?php the_tags(' '); ?>

Very simple idea, when you hover over the image, the text appears and you can click anywhere on it and view the post.
Usually this would be done by using one anchor tag with the other elements inside it but for some reason that method just seems to create 2 permalinks and messes the whole thing up.
Another issue is i'm trying to make the image responsive. I'm using percentage width and heights but unless I make the parent .blog_item element a fixed height, I can't get the entire image to display.
I've created a test here - https://jsfiddle.net/w54htg7g/
Here's the CSS:
    .blog_item {
      position: relative;
      transition: all 0.5s;
      text-align: center;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .blog_item .abs_bg {
      display: block;
      z-index: 2;
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      transition: all 0.5s;
    }
    .blog_item .blog_item_inner {
      z-index: 1;
      position: relative;
      padding-top: .5em;
      padding-bottom: .7em;
    }
    .blog_item .full_link {
      z-index: 3;
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
    }
    .blog_item:hover {
      background: #000;
    }
    .blog_item:hover .abs_bg {
      opacity: 0.5;
    }

Here's what it looks like now:

And this is how I want it to look like:
Answer: Change the position property of .blog_item .blog_item_inner {} to position: absolute; rather than position:relative;
This will absolutely position that content within the .blog_item element, because .blog_item {} is the parent element and has been positioned relatively.
You may need to further refine the CSS for .blog_item .blog_item_inner {}. However, this should be a step in the correct direction.
It is somewhat difficult to be exact and precise when there's no example to test like a jsFiddle link, and only pieces of code are present.


Sendo H = 1 + ½ +1/3 + ¼ + ... + 1/N, faça um algoritmo para calcular H, sendo que N é digitado pelo usuário

Question: O programa tá printando apenas 1, é como se ele não guardasse o valor da variável h, alguém pode ajudar? Segue o código:
public class MainUmSobreH {
public static void main(String[] args) {
    double h = 0;
    int n = 4;
    for(int i=1; i<=n; i++) {

        h = h + 1/i;

        System.out.println(h);
    }
}
}

Answer: Números de ponto flutuante são bestas mitológicas de comportamento errante. Ou pelo menos são assim caso você não saiba domá-los antes de usá-los.
Usando pontos flutuantes, eu posso somar 3 números em uma ordem e obter um resultado distinto do que somar esses mesmos números em outra ordem:
a + b + c =?= c + a + b

Eu discorro brevemente sobre o assunto em algumas respostas:

nessa aqui, eu tenho de fazer um somatório f(n)*b para diversos valores de n; uma das estratégias eu não coloquei o b em evidência, então a soma era sum = f(1)*b + f(2)*b + f(3)*b, com 3 multiplicações e 2 somas, já na outra alternativa eu só multiplico no final da soma sum = b*(f(1) + f(2) + f(3)) com 2 somas e 1 multiplicação; e, não, não são somas equivalentes ao se levar em conta a precisão do ponto flutuante
nessa outra resposta, eu usei esse fato da perda de precisão como condição de parada em uma soma infinita, inclusive eu mostro que há casos em que somar a + y == a, y != 0, portanto (a + y) + y == a, mas que pode existir a + (y + y) > a

Então qual seria a forma de tentar garantir o máximo de precisão possível na soma? Somando do valor menos significante até o mais significante! Basicamente alterar a ordem do for proposto pelo @Paulo R. F. Amorim. Também é possível fazer isso na recursão proposto pelo @Marcos Andrade com um pouco mais de cautela.
Solução com iteração
double sum = 0d;
int n = 4
for (int i = n; i >= 1; i--) {
    sum += 1d/i;
}

Estou usando a notação indicando que o número é um double conforme proposto pelo @Isac. Outra alternativa seria fazendo 1.0/i, que força o número a ser interpretado como double de qualquer sorte.
Solução recursiva 1
A ideia aqui é ter uma função de interface que chama a função recursiva propriamente dita. Vamos passar, na função recursiva, a soma acumulada até então, assim poderemos ficar somando os menores elementos primeiros para do então somar o elemento mais significativo.
Essa estratégia lembra um pouco algumas soluções usadas em prolog quando não se deseja que quem vá consultar na base de dados precise saber que a lista a ser passada como um terceiro argumento não intuitivo precisa ser uma lista vazia.
public static double somaInverso(int n) {
    return somaInversoPrivado(n, 0.0);
}

private static double somaInversoPrivado(int n, double acumulado) {
  if (n == 1) {
    return 1.0 + acumulado;
  }
  return somaInversoPrivado(n-1, 1.0/n + acumulado);
}

Note que aqui eu deixei o método somaInversoPrivado como um método privado à classe que faz esses cálculo. É uma função auxiliar cuja API não deve ser exposta.
Solução recursiva 2
Aqui as coisas acontecem de modo semelhante à outra, mas no lugar de enviar a soma acumulada, eu envio em qual passo na recursão estou. Tenho de parar quando estou no passo n. A ideia é que o resultado do passo i é 1.0/i + sum(i+1, n), isso garante que no último passo recursivo seja retornado o menor valor, que será então somado com o segundo menor valor e assim por diante.
public static double somaInverso(int n) {
    return somaInversoPrivado(1, n);
}

private static double somaInversoPrivado(int i, int n) {
  if (n == i) {
    return 1.0/i;
  }
  return 1.0/i + somaInversoPrivado(i + 1, n);
}

Answer: Necessário converter em double ao fazer a adição/divisão:
public class MainUmSobreH {
    public static void main(String[] args) {
      double h = 0;
      int n = 4;
      for(int i=1; i<=n; i++) {

        h = h + (double)1/i;

        System.out.println(h);
    }
}

Assim deve funcionar corretamente.
Comment: Porque do jeito que estava sendo feito antes, ambos os números (tanto o 1 fixo, como o "i" do for) eram definidos como inteiros, logo a divisão sempre dava um número inteiro arredondando. Por exemplo, 1/2 não dava 0.5 e sim 0
Comment: Outra solução simples é `1d/i`.
Comment: Agora funcionou, mas poderia explicar o porque disso?
Comment: Em casos extremos, a resposta pode acabar gerando um possível erro de precisão. Não sei se esse erro será sensível com o formato de ponto flutuante de precisão dupla, mas existe a possibilidade disso acontecer
Answer: Esse algoritmo também é um clássico exemplo de recursividade. Acho interessante deixar aqui como uma forma alternativa de finalizar o exemplo.
Simplificando o algoritmo (sem verificar por exceções etc):
package recursividade;

public class Progressao {

    public static void main(String[] args) {
        double inicial = 0;
        int limite = 4;
        double resultado = inicial + CalcularProgressao(limite);
        System.out.println(resultado);
    }

    public static double CalcularProgressao(int limite) {
        if (limite == 1) {
            return 1.0;
        }
        else {
            return 1.0/limite + CalcularProgressao(limite-1);
        }
    }
}

É importante citar que o return utiliza 1.0 ao invés de 1, já que é necessário retornar um Double.
Answer: solução correta
import java.util.Scanner;

public class Main {

    public static void main(String[] Args) {

     double h = 0;
     Scanner sc = new Scanner(System.in);
     double n = sc.nextDouble();

     for (int i = 1; i <= n; i++) {
     //TODO: Calcule o valor de H de forma que resulte na soma dos termos

           h = h + (double)1/i;

      }
     //TODO: Imprima a soma dos termos, considerando um resultado com duas casas decimais:
        System.out.println(Math.round(h));
   }
}

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Show that the congruence $x^4 - 17y^4 \equiv 2z^2 \pmod p$ has non-trivial solutions for all primes $p$

Question: I want to show that $$x^4 - 17y^4 \equiv 2z^2 \pmod p$$ has non-trivial solutions for all primes $p$.
I haven't been able to progress much, but one attempt was to consider the case that $p$ is such that $2$ is a square (a quadratic residue) mod $p$, and thus $2z^2$ is a square, therefore there is a solution if and only if $x^4 - 17y^4$ is congruent to a square for some $x$ and $y$.
Then we can consider when $17$ is a square, then show there exist $x$ and $y$ such that $x^4 - 2z^2$ is congruent to a square. Then I suppose we will have to consider the case that neither $17$ nor $2$ is a square mod $p$, so then we have to show $2z^2 + 17y^4$ is congruent to a square.
So far I have not been able to get anywhere with this approach. Any help is appreciated.
Answer:
For $p=2$, $(x,y,z)=(1,1,1)$ is a solution.
If $(-2/p)=1$ then $(2a,a,a)$ is a solution when $a^2\equiv-2\pmod{p}$.
If $(-2/p)=-1$ and $(17/p)=-1$, then $(-34/p)=1$ and $(0,2,2a)$ is a solution when $a^2\equiv-34\pmod{p}$.
If $(5/p)=1$, then $(a,1,2)$ is a solution when $a^2\equiv5\pmod{p}$.
If $(7/p)=1$, then $(a,1,4)$ is a solution when $a^2\equiv7\pmod{p}$.

Since $p=17$ and $p=5,7$ are covered by case 2 and case 3 respectively, it remains to consider the case that $(17/p)=1$ and $(5/p)=(7/p)=-1$, which implies $(35/p)=1$. So we may take integers $a,b$ such that $a^2\equiv17\pmod{p}$ and $b^2\equiv35\pmod{p}$. Then we complete the proof by the following observations:

If $(a/p)=1$, then $(c,1,0)$ is a solution when $c^2\equiv a\pmod{p}$.
If $(b/p)=1$, then $(c,1,3)$ is a solution when $c^2\equiv b\pmod{p}$.
If $(a/p)=(b/p)=-1$, then $(ab/p)=1$ and $(c,1,17)$ is a solution when $c^2\equiv ab\pmod{p}$.
Comment: Hi, I was searching about this equations and I found this answer. I have to prove that there are solutions mod p for every p, but the equation is a bit different: $x^4-17=2y^2$. How can I generalize  your proof? I've done the first two cases but I have difficulties with the third. Thanks!
Comment: @robbis $x^4-17y^4=2z^2$ nearly implies $(x/y)^4-17=2(z/y^2)^2$, so you only need to check that $y$ is invertible mod $p$ in each case.
Comment: Right, just by change of variables! I haven't thought of this smple trick! thanks!
Comment: do you also know about non-solvability over the rationals?


$\ell^p \subset c_0$ with continuous injection.

Question: Let $1 \le p < \infty$. How do I see that$$\ell^p \subset \left\{x ; \lim_{k \to \infty} x_k = 0\right\}$$with continuous injection?
Comment: By considering the formal identity operator between the spaces.
Answer: $ \|id (x_{n})\| _{sup} \le sup {x_{n}} \le \|(x_{n})\|_{\ell^{p}}$ and the Cauchy criterion for convergence of the norm in ${\ell^{p}}$


LilyPond: help to merge notes in different voices, \omit Stem and \omit Flag don't help

Question: I tried previously suggested solutions, and they didn't work. I am trying to merge noteheads to draw a melody guideline. In the code below I show them to demonstrate the effect, in the final version they will be hidden.
<code>\version "2.24.3"
\language "italiano"

\score {
    \new PianoStaff <<
        \new Staff = "right" \relative do'' {
            <>
            \key re \minor
            \numericTimeSignature
            \time 3/4
            <<
                {
                    sold8-- (sol16 sold la4) r4
                    \oneVoice
                    <\single\override NoteHead.color = "firebrick" sib re mi sol sib>8-> [
                    <la dod mi sol la>->
                    <fad do' re fad>->]
                    <sol, do! sol'>16-- [(la' <fad, do' fad>8--)] r8
                }\\
                {
                    re'4~ 16 dod (mi sol la dod mi sol)
                }\\
                {
                    s2 s8 s16
                    \change Staff = "left"
                    \stemDown
                    %\hideNotes
                    la,
                    \showStaffSwitch
                    \once \omit Stem
                    \once \omit Flag
                    \change Staff = "right"
                    \once \override NoteHead.color = "seagreen"
                    sib8
                    \hideStaffSwitch
                    %\unHideNotes
                }
            >>
        }
        \new Staff = "left" \relative do {
            \key re \minor
            \clef bass
            <<
                {
                    fa4 (mi)
                }\\
                {
                    la,2
                }
            >>
            \clef treble
            dod'16 mi sol la
            <sol, re' mi sol>8_> [<la dod mi sol>_> \clef bass <re, la' re>_>]
            <la mib'>_- [<re, la' re>_- ] \clef treble
            la'''16 sib
        }
    >>
}
</code>
I highlighted not merged noteheads:
Answer: Try ignoring note column collisions:
<code>                %\hideNotes
                la,
                \showStaffSwitch
                \once \omit Stem
                \once \omit Flag
                \change Staff = "right"
                \once \override NoteHead.color = "seagreen"
                \override NoteColumn.ignore-collision = ##t % <-- new
                sib8
                \hideStaffSwitch
                %\unHideNotes
</code>
Since it's so usual to want to hide a single note head, I have this defined in global variables file:
<code>hideNoteHead = \once {
  \omit Stem
  \omit Dots
  \omit Flag
  \hideNotes
  \override NoteColumn.ignore-collision = ##t
}
</code>
Then I can just write:
<code>\hideNoteHead sib8
</code>
Comment: This is magic. Thanks!


How to prefix parent category to child category php

Question: How to create a category prefixing its parent such as
category
category -> sub Category
category -> sub Category
category -> sub Category -> sub sub Category
category -> sub Category -> sub sub Category -> so on
here is Mysql table
|| id || name || parent_id || status || sort_order ||
any how tryied following to achive but i got only up to two levels i.e category -> subcategory
here is my code
  $data['categories'] = array();
    foreach($categories as $category){

        if($category['parent_id'] != 0 && $category['parent_id'] != null){
           $name = $this->getparent($category['parent_id']) . '->' . $category['name'];
        } else {
            $name = $category['name'];
        }

        $data['categories'][] = array(
            'name' => $name,
            'id' => $category['id'],
            'sort_order' => $category['sort_order'],
            'status'    => $category['status'],
        );
    }

here is getParent() function
public function getparent($id){
        $model = new ModelCategory();
        $parent = $model->where('id', $id)->first();

        if($parent['parent_id'] != 0){

        }

        return $parent['name'];

    }

could anyone help me.. Thanks
Comment: If when you call `getparent()`, you could then load the new parent and call `getparent()` again until this fails.  There isn't enough information to be able to implement this ATM.
Comment: @NigelRen could you please  give me example in code i add getparent() function in code
Answer: you can call getparent() inside it
 public function getparent($id){
    $model = new ModelCategory();
    $parent = $model->where('id', $id)->first();

    if($parent['parent_id'] != 0){
           $name = $this->getparent($parent['parent_id']) . '->' . $parent['name'];
        } else {
            $name = $parent['name'];
        }

    return $name;

you already applied if() statement you were only few steps away to get desired.
Hope this answer might Help you
Answer: I think what you need is a recursive function. That's a function wich is calling itself based on a condition.
In your case, you don't know how many parents has you original category, so the condition is : "stop when there's no more parent id"
And the basic thing to do is : "append the parent category name to the current one"
Now in php it can be translated to :
public function getparent($id)
    {
        $model = new ModelCategory();
        $parent = $model->where('id', $id)->first();

        // your category HAS NO parent
        if (!$parent['parent_id']) {
            return ''; // no ancestor
        }

        $separator = '->';

        return $this->getparent($parent['parent_id']) . $separator . $parent['name'];
    }


Why does error alert not working for getJSON?

Question: I am loading json data as below
<code>$.getJSON('data.json', function (data, status, xhr) {
    if (status === "success") {
        myData= data;
    } else {
        window.alert("Unexpected error happened. Please refresh your browser window to reload the page. Error: " + xhr + status);
    }
});
</code>
However, I tested this by deleting the json file. And expecting 404 result. HOwever, that didn't show up with alter message. On the console, it does say 404 for the json data. But , why does the alert box not showing up?
Answer: getJSON segments calls into success (ie HTTP code 200) and error (ie HTTP non-200).  It doesn't get called when there is a failure (ie non-200).  Therefore, status will always be "success" when its called because when its not this callback isn't called.
You should consider converting to using promises because it's much more flexible.  Use the done() method to register the section of code for when a 200 is received, and the fail() method for when a non-200 is received. try this:
<code>$.getJSON('someurl').done( function( data ) {
   myData = data;
}).fail( function(jqXHR, textStatus, errorThrown) {
   console.log("Unexpected error happened. Please refresh your browser window to reload the page. Error: ", textStatus, " ", errorThrown);
});
</code>
Also consider using console.log instead of alert when writing debugging code.  You can leave console.log() calls in your code where alerts() you have to remember to remove them.
Answer: because the callback function of getJSON only works when requesting successfully.
you should use
<code>$.ajax({
  statusCode: {404: function() {
    alert('page not found');
  }
});
</code>
Comment: Is it possible to take my code and add some more status code to it test for errors like those?
Comment: you can visit [jQuery API Document](http://api.jquery.com/jQuery.ajax/), find "statusCode", and check it.
Comment: Just so other people are aware this will only work for when 404 is returned.  It won't handle the plethora of other status codes that could be returned like 500, 550, 403, etc.  Also you have converted from using a call that interprets JSON for you to raw ajax call that you will need to configure to handle JSON data for you.  This really doesn't fix the OPs problem and arguably creates more problems to solve.


Alterar entre janelas - Python 3

Question: Boa tarde.
Estou precisando de uma ajuda para alterar entre janelas durante um processo. Criei um código com selenium para acessar um site, acessar uma área logada e depois clicar em opções para anexar o arquivo.
É necessário clicar nesses "três pontinhos"

e após isso abre a janela do windows para selecionar o arquivo:

A minha dificuldade é acessar essa janela e realizar o "alt tab" entre a janela do navegador e do windows. Já tentei utilizando o send_keys, o Keys e o actionChains mas mesmo assim não consegui.
Obrigado.
Comment: Use pyautogui.click, pyautogui.moveTo, e pyautogui.move e seja feliz
Answer: Para o envio de arquivos você não precisa realizar o click, você pode apenar usar dessa forma, passando o localizador e o caminho do arquivo:

Imagepath = "C:\User\Desktop\image.png"
driver.find_element_by_xpath('//html/body/input').send_keys(Imagepath)

Se quiser fazer o click e abrir essa janela de envio, você vai ter de usar o pyautogui.
Comment: Mas o problema é que o arquivo que eu vou usar tem um nome variavel, pois varia de acordo com a data e o horario que serão salvos. Eu defini uma variavel para o caminho (a) e uma variavel para o nome(b) e uma terceira variavel (a+b), se eu inserir o caminho como variavel deve funcionar?
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Alterar entre janelas - Python 3


Create points pattern in R using spatstat package with specified number of points

Question: Is it possible to generate points pattern with Poisson and Thomas process in R using spatstat package with specified number of points?
I had genereted Strauss point pattern using the Metropolis-Hastings algorithm with specified number of points (20 points) like this:
Model <- list(cif="straush",par=list(beta=10,gamma=0.5,r=0.5,hc=0.5),
          w=c(0,10,0,10))
P <- rmh(model=Model,start=list(n.start=20),
              control=list(p=1,nrep=1e5,nverb=5000))

but I can not generate Poisson or Thomas point pattern using the Metropolis-Hastings algorithm.
Answer: As also pointed out in off-site correspondence:
A Poisson process conditional on the number of points is just a collection of independent and identically distributed points with density proportional to the intensity, so you can use the spatstat function rpoint to simulate that process.
I don't think it is mathematical tractable to express the distribution of a Thomas process conditional on the total number of points inside the observation window.


While implementing an interface in an enum, why eclipse automatically puts a semicolon before the interface method being overridden?

Question: I have an interface and an enum
I am implementing the interface in the enum
I am using eclipse as my IDE
Following is my interface file -
ITrafficSignal.java -->
public interface ITrafficSignal {
    public void showAction();
}

Following is my enum file -
ETrafficSignal.java -->
public enum ETrafficSignal implements ITrafficSignal {
    ;

    @Override
    public void showAction() {

    }
}

here the ; in line 2 is being automatically being put by eclipse
If I remove ;, then in the method being implemented -
public void showAction()
is having a red line below the keyword void and the error says -
Multiple markers at this line
- implements ITrafficSignal.showAction
- Syntax error on token "void", volatile expected

I am unable to understand this.
Answer: That's simply the syntax of enum types. From §8.9 Enum Types of the Java Language Specification:

EnumDeclaration:
  {ClassModifier} enum TypeIdentifier [Superinterfaces] EnumBody

And the syntax of EnumBody is:

EnumBody:
  { [EnumConstantList] [,] [EnumBodyDeclarations] }

EnumConstantList:
  EnumConstant {, EnumConstant}

EnumConstant:
  {EnumConstantModifier} Identifier [( [ArgumentList] )] [ClassBody]

EnumConstantModifier:
  Annotation

And finally the syntax of EnumBodyDeclarations is:

EnumBodyDeclarations:
  ; {ClassBodyDeclaration}

As you can see, the above shows that the enum body declarations must be preceded by a semicolon (;) separating it from the enum constants. Unlike the EnumConstantList the semicolon is not optional1. This means the semicolon must be present if there's enum body declarations regardless of there being any enum constants declared, though I personally don't see the point in having an enum type without constants.

 1. The entire EnumBodyDeclarations is optional, however, meaning if there's no body declarations then the semicolon can be omitted.
Comment: Good answer, somehow I knew that it was needed, but never cared to look at the spec. Also to the statement: *though I personally don't see the point in having an enum type without constants.*, [`enum`s can (sadly) be used like static classes for holding utility methods](https://stackoverflow.com/questions/4992893/using-enums-to-implement-utility-classes-and-singletons)


How to make a block showing the content entity the author of the node is linked to?

Question: I have a 'business' content type and an 'information' content type on my page.
The author of the business is the webmaster and from the information the authors are the users of the site. The contenttype 'business' has an entity reference field targeting the users linked to that business
On the 'business' pages there is a block showing the 'information'articles published by the users linked to that specific business. So far no problem.
I would like to have a block on the 'information' pages showing the business the author of that node/article is linked to. The author of the contenttype business is always the webmaster and the author of the article is the user. I think that I don't understand the relationship that I must make to get this correct. The block has to look at the author of the node where the block is displayed and see the business where that user is linked to.
I'm completely blocked getting that done. I'm new to Drupal, there were no serious problems so far. But this I can't get done.I'm missing something in the contextual filters and relationships.
Answer: You've stumbled into the issue of Context. Blocks can be placed anywhere, and has a very limited concept of context (the only context that Blocks know of are logged in user, and parameters taken from the url).
Normally one will use CTools (the Context specialist) and Panels to solve this type of problem. You are lucky in that Views has a relationship that can solve it for you.
Construct your block as follow:
Type Content, filtered by content type Information.
Contextual filter:
Content: Nid (The node ID.), no relationship, and for WHEN THE FILTER VALUE IS NOT AVAILABLE you add Content ID from URL
Relationships:

Content: Author (Relate content to the user who created it.), and Require this relationship
Entity Reference: Referencing entity (A bridge to the Content entity that is referencing User via field_users - Your field will be differently named, mine is field_users). Set the relationship to 'author' (the first relationship added), and Require this relationship.

Fields:
I assume you are adding the node title. Make sure to set the relationship to: Content referencing Users from field_users (the 2nd relationship you added - yours will be named slightly different)
If you add any other fields make sure to set the relationship as well.
If you find that it lists any duplicates, just go to OTHER in views, and under Query Settings, set it to Distinct (I'm sure this won't be necessary though).
Answer: Thanks very much for your quick reply! Really appreciate it.
The setting u describe is the way i have the blocks working on the nodes with the 'business' content. The blocks show the articles written by the users that are linked to that business.
I cant get it working the other way around. On the 'article' nodes i would like to have a block that shows the business that the author of that particular node is linked to. I was thinking that the problem is maybe in the relationship author. The contenttype business has as author the webmaster and not the users of the site who are writing the articles.
Could that be? English is not my mothertongue.. so maybe i completly misunderstand?


What are the various ways of vocalizing rhythmic figures?

Question: I know of the standard western technique where the beats (quarter notes) are numbered and eighths are vocalized as 'and' and sixteenths are vocalized as 'ee' and 'uh' (One-ee-and-uh Two-ee-and-uh).
I've also come across "Ta titi Ta Ta", but don't know how to subdivide it further.
And in the liner notes to some Sheila Chandra recordings entitled Vocal Percussion, there's reference to a traditional Indian system (or several) of associating syllables with rhythms?
What other systems exist? Note: the more complete, the better; does it have provisions for triplets or higher compressed-time figures?
Comment: @luserdroog: I'm guessing you referred to tis question: http://music.stackexchange.com/questions/6352/rhythm-drum-exercises-without-drums
Comment: @UlfÅkerstedt That's one's good, too. But this is the one I remembered: http://music.stackexchange.com/questions/7682/how-do-i-read-this-text-only-musical-notation-from-wikipedia/7730#7730
Comment: There was another question that touched on this, mentioning something like *lu-la-li* for triplets. But I couldn't find it when I searched.
Answer: The takadimi system solved my rhythmic needs.
Here's the creator's website: http://www.takadimi.net/
Answer: For the most part when it gets faster than 16ths, it's easier to to slow it down so you can count the 32nds using 'ee and uh'.  The more fun vocal rhythms that I've come across are usually from things that aren't straight 4s (quarter, sixteenth, etc.) but from triplets, pentuplets, interesting time signatures, and groovy beats (swing, etc).
For exapmle: 7/8 was once explained to me as 'yaba daba dabadoo' with emphasis on the first syllables.  'tuduh tuduh tuhduhkah' works as well.
Pentuplets are usually just any 5 syllable word that you can think of.  I'm a fan of 'hippopotamus', but words like 'incrementally' work. Triplets are similar, except using 3 syllables.  Usually I've heard 'trip-uh-let', but 'squish-flop-ape' works as well (as long as they're not particularly fast).
When you start dealing with swung beats, in my experience, people either start scatting or imitating drum sets.  'Buddha' is a good one though
Answer: Having learned the already familiar "one-ee-and-uh" system, what I can add to this question is a way to handle triplets:
"Tri-pul-let" is how I learned it
Answer: The Kodaly system uses logically built up names for rhymic patterns. Ta is one beat, ti-ti is quavers, tika-tika is semi-quavers, t-k-t for triplets, etc. There are variations for ease of pronounciation in different languages, or personal preference. It's worth noting that these are only viewed as aids until rhythmic patterns are well embedded. The Kodaly Method page on Wikipedia can take you further on this, including useful publications.
Answer: The Indian system is highly developed and the syllables used to vocalize specific drum rhythms and sounds are referred to as bols. They are often encountered in North Indian music as 'tabla bols,' though the tabla is usually played together with a lower drum called the baya. I studied this system only for a year many years ago. Now there are many text and video resources on Indian rhythm that can be found through Googling the above terms, but I don't know what is best.
Nigerian-born Babatunde Olatunji used a simple system of syllables for large African drums. There does not seem to be a comparable system for the currently popular West African djembe--dunun ensembles, though the Olatunji system is still in use.
Answer: Carnatic tradition konnakol, maybe - Konnakol in Wikipedia. Here's an example from Steve Smith and Vital Information: Interwoven Rhythms - Synchronous. John McLaughlin uses the system as well.


Samsung Experience version

Question: I'm writing an android application and i need to detect what version of Samsung Experience the device is running to do a special check. Galaxy S8 with android 7.0 allows the navigation bar to be on the left. And from my understanding only android 7.1 allows that. My application apply margins based on android version and I need to check if the version is 7 and we are running Samsung Experience 8.1.
Here you can find an example of About phone.
Another posibility is detect the position of the navigation bar on the screen (right or left). I could not find a way to do it.
thanks in advance.
I tried reading with Build.MODEL, Build.TAGS, Build.MANUFACTURER.
Answer: Take a look at Checking external app version name in android
I don't have a Samsung Galaxy S8 available at the moment, but I think you can check the version of packages com.sec.android.app.launcher or com.samsung.android.mobileservice.

Samsung Experience version


Combining XML records into meaningful sentence: "Dale, Harry and Lucy"

Question: Say I have this in XML
<people>
    <name>Dale</name>
    <name>Harry</name>
    <name>Lucy</name>
</people>

How would I go about transforming this into
Dale, Harry and Lucy

using just XSLT? It has to be flexible to a certain point, so that where there are more names, it would still make sense.
Dale, Harry, Lucy, James, Andy, Shelly and Norma

Comment: possible duplicate of [How do I generate a comma-separated list with XSLT/XPath?](http://stackoverflow.com/questions/666584/how-do-i-generate-a-comma-separated-list-with-xslt-xpath)
Comment: Just a quick reminder -- though i know stack exchange hates offsite references  -- that there's an xslt FAQ website, easily findable by websearching that phrase,  which contains all the best tips from the first several years of the xsl mailing lisr, back when this tool was new. It's still a great resource for previous solutions, including some which achieve things we thought xslt 1.0 couldn't do!
Answer: This question is very similar to this question, but not identical to it. The only thing you need to add is a second condition that determines when and should be inserted.
XML Input
<people>
    <name>Dale</name>
    <name>Harry</name>
    <name>Lucy</name>
    <name>John</name>
</people>

Stylesheet
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="text"/>

    <xsl:strip-space elements="*"/>

    <xsl:template match="name">
        <xsl:variable name="pos" select="position()"/>

        <xsl:if test="$pos = last() and $pos != 1">
            <xsl:text> and </xsl:text>
        </xsl:if>

        <xsl:value-of select="."/>

        <xsl:if test="$pos != last() and $pos + 1 != last()">
            <xsl:text>, </xsl:text>
        </xsl:if>
    </xsl:template>

</xsl:transform>

Text Output
Dale, Harry, Lucy and John

Or, if you prefer cryptic code, but fewer lines, it can be done with a single XPath expression (XSLT 1.0):
<xsl:template match="name">
    <xsl:value-of select="concat(.,
    substring(', ', 3 - ((position() != last() and position() + 1 != last()) * 2)),
    substring(' and ', 6 - ((position() = last() - 1) * 5)))"/>
</xsl:template>

Comment: @michael.hor257k Edited the answer. Now it works for a single `name`, too - I'd prefer your solution though.
Answer: Try:
<xsl:template match="/people">
    <xsl:for-each select="name">
        <xsl:value-of select="."/>
        <xsl:choose>
            <xsl:when test="position()=last() - 1"> and </xsl:when>
            <xsl:when test="position()!=last()">, </xsl:when>
        </xsl:choose>
    </xsl:for-each>
</xsl:template>


How to handle unknown-length header (TFTP related)

Question: It is probably relevant to other questions too.
I need to build a simple TFTP server in C (octet mode only) that will work with most TFTP clients available today (I only need to implement the server).
<code>opcode   //2 byte
filename // string (unknown size)
0        // 1 byte
mode     // string (unknows size, max 9 chars considering 'netascii')
0        // 1 byte
</code>
But I'm having a problem: the RRQ/WRQ packets have a unknown length field "filename" (and "mode"). Because my server needs to be generic, how can I implement this option?
Create a ridiculously large buffer and wait until recvfrom() returns 0?
Thanks!
Answer: make the buffer no much larger than the payload size of an Ethernet packet...
with TFTP recvfrom won't return buffers larger than that...


select faz aparecer campos de input e de select

Question: Pessoal preciso que que o campo de imput aparece e o campo select com os estado quando o usuário seleciona sua área te atuação caso ele selecione Acadêmico, Outros ou Não sou da Areá da Saúde não apareça isso foi que que consegui ate agora alguém pode me ajudar

                    <select id="TipoDocumento" name="TipoDocumento" class="form-control" required>
                        <option data-tipo=""></option>
                        <option data-tipo="Biomédico">Biomédico</option>
                        <option data-tipo="Dentista">Dentista</option>
                        <option data-tipo="Médico">Médico</option>
                        <option data-tipo="Farmacêutico">Farmacêutico</option>
                        <option data-tipo="Enfermeiro">Enfermeiro</option>
                        <option data-tipo="Acadêmico">Acadêmico</option>
                        <option data-tipo="Outros">Outros</option>
                        <option data-tipo="nao">Não sou da Areá da Saúde</option>
                        </select>

                         <input class="form-control" type="hidden" name="CRO" id="Biomédico" placeholder="Digite seu CRO" disabled>
                         <input class="form-control" type="hidden" name="CRO" id="Dentista" placeholder="Digite seu CRO" disabled>
                         <input class="form-control" type="hidden" name="CRO" id="Médico" placeholder="Digite seu CRO" disabled>
                         <input class="form-control" type="hidden" name="CRO" id="Farmacêutico" placeholder="Digite seu CRO" disabled>
                         <input class="form-control" type="hidden" name="CRO" id="Enfermeiro" placeholder="Digite seu CRO" disabled>
                         <input class="form-control" type="hidden" name="Acadêmico" id="Acadêmico" placeholder="Digite seu RG" disabled>
                         <input class="form-control" type="hidden" name="outros" id="Outros" placeholder="Digite seu CRO" disabled>
                         <input class="form-control" type="hidden" name="CRO" id="Não sou da Areá da Saúde" placeholder="CPF" disabled>

                        <select name="estado" class="form-control" id="TipoDocumento" required>
                            <option value="AC">Acre</option>
                            <option value="AL">Alagoas</option>
                            <option value="AP">Amapá</option>
                            <option value="AM">Amazonas</option>
                            <option value="BA">Bahia</option>
                            <option value="CE">Ceará</option>
                            <option value="ES">Espírito Santo</option>
                            <option value="GO.">Goiás</option>
                            <option value="MA">Maranhão</option>
                            <option value="MT">Mato Grosso</option>
                            <option value="MS">Mato Grosso do Sul</option>
                            <option value="MG">Minas Gerais</option>
                            <option value="PA">Pará</option>
                            <option value="PB.">Paraíba</option>
                            <option value="PR">Paraná</option>
                            <option value="PE">Pernambuco</option>
                            <option value="PI">Piauí</option>
                            <option value="RJ">Rio de Janeiro</option>
                            <option value="RN">Rio Grande do Norte</option>
                            <option value="RS">Rio Grande do Sul</option>
                            <option value="RO.">Rondônia</option>
                            <option value="RR">Roraima</option>
                            <option value="SC">Santa Catarina</option>
                            <option value="SP">São Paulo</option>
                            <option value="SE.">Sergipe</option>
                            <option value="TO">Tocantins</option>
                            <option value="DF">Distrito Federal</option>
                        </select>

aqui o js
 //desabilita e esconde todos os inputs do campo area de atuação
      $('#TipoDocumento').change(function(e) {
         let opcaoSelecionada = this.querySelector('option:checked');

  //desabilita e esconde todos os inputs
        let inputs = $('#InputsDocumento input');
         inputs.attr('type', 'hidden');
         inputs.attr('disabled', '');

  //habilita e mostra o input relevante
        let inputEscolhido = inputs.filter('#'+ opcaoSelecionada.dataset.tipo);
         inputEscolhido.attr('type', 'text');
         if (opcaoSelecionada.dataset.tipo !== 'placeholder')
         inputEscolhido.removeAttr('disabled');
        });

Answer: Primeiramente altere o id do select "estado", estava o mesmo do tipo:
<select name="estado" class="form-control" id="estado" required>

No exemplo que fiz coloquei estado
Depois no Js, verifica o valor e se for um dos três, esconde o select, caso não, mostra.
Este código vai dentro da função onchange que fez.
//mostra ou não o estado
      switch($('#TipoDocumento').val()) {
        case "Acadêmico":
        case "Outros":
        case "Não sou da Areá da Saúde":
                $("#estado").hide();
            break;
        default:
            $("#estado").show();
          break;
      }

Seu Js completo fica assim:
//desabilita e esconde todos os inputs do campo area de atuação
  $('#TipoDocumento').change(function(e) {
         let opcaoSelecionada = this.querySelector('option:checked');

  //desabilita e esconde todos os inputs
        let inputs = $('#InputsDocumento input');
         inputs.attr('type', 'hidden');
         inputs.attr('disabled', '');

  //habilita e mostra o input relevante
        let inputEscolhido = inputs.filter('#'+ opcaoSelecionada.dataset.tipo);
         inputEscolhido.attr('type', 'text');
         if (opcaoSelecionada.dataset.tipo !== 'placeholder')
         inputEscolhido.removeAttr('disabled');

      //mostra/nãom mostra o estado
      switch($('#TipoDocumento').val()) {
        case "Acadêmico":
        case "Outros":
        case "Não sou da Areá da Saúde":
                $("#estado").hide();
            break;
        default:
            $("#estado").show();
          break;
      }
   });

Fiddle do código rodando: https://jsfiddle.net/woLfvs72/3/